KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > environment > wrapper > EnvironmentWrapper


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.wrapper;
17
18 import java.io.IOException JavaDoc;
19 import java.io.OutputStream JavaDoc;
20 import java.net.MalformedURLException JavaDoc;
21 import java.util.HashMap JavaDoc;
22 import java.util.Iterator JavaDoc;
23 import java.util.Map JavaDoc;
24
25 import org.apache.avalon.framework.component.ComponentManager;
26 import org.apache.avalon.framework.logger.Logger;
27 import org.apache.cocoon.Constants;
28 import org.apache.cocoon.environment.AbstractEnvironment;
29 import org.apache.cocoon.environment.Environment;
30 import org.apache.cocoon.environment.ObjectModelHelper;
31 import org.apache.cocoon.environment.Request;
32 import org.apache.cocoon.environment.Response;
33 import org.apache.cocoon.util.BufferedOutputStream;
34 import org.apache.cocoon.util.Deprecation;
35
36
37 /**
38  * This is a wrapper class for the <code>Environment</code> object.
39  * It has the same properties except that the object model
40  * contains a <code>RequestWrapper</code> object.
41  *
42  * @author <a HREF="mailto:bluetkemeier@s-und-n.de">Bj&ouml;rn L&uuml;tkemeier</a>
43  * @author <a HREF="mailto:cziegeler@apache.org">Carsten Ziegeler</a>
44  * @version CVS $Id: EnvironmentWrapper.java 157288 2005-03-12 22:42:07Z sylvain $
45  */

46 public class EnvironmentWrapper
47     extends AbstractEnvironment
48     implements Environment {
49
50     /** The wrapped environment */
51     protected Environment environment;
52
53     /** The object model */
54     protected Map JavaDoc objectModel;
55
56     /** The redirect url */
57     protected String JavaDoc redirectURL;
58
59     /** The request object */
60     protected Request request;
61
62     /** The stream to output to */
63     protected OutputStream JavaDoc outputStream;
64     
65     protected String JavaDoc contentType;
66
67     protected boolean internalRedirect = false;
68     
69     /**
70      * Constructs an EnvironmentWrapper object from a Request
71      * and Response objects
72      */

73     public EnvironmentWrapper(Environment env,
74                               String JavaDoc requestURI,
75                               String JavaDoc queryString,
76                               Logger logger)
77     throws MalformedURLException JavaDoc {
78         this(env, requestURI, queryString, logger, false);
79     }
80
81     /**
82      * Constructs an EnvironmentWrapper object from a Request
83      * and Response objects
84      */

85     public EnvironmentWrapper(Environment env,
86                               String JavaDoc requestURI,
87                               String JavaDoc queryString,
88                               Logger logger,
89                               boolean rawMode)
90     throws MalformedURLException JavaDoc {
91         this(env, requestURI, queryString, logger, null, rawMode);
92     }
93
94     /**
95      * Constructs an EnvironmentWrapper object from a Request
96      * and Response objects
97      */

98     public EnvironmentWrapper(Environment env,
99                               String JavaDoc requestURI,
100                               String JavaDoc queryString,
101                               Logger logger,
102                               ComponentManager manager,
103                               boolean rawMode)
104     throws MalformedURLException JavaDoc {
105         this(env, requestURI, queryString, logger, null, rawMode,env.getView(), true);
106     }
107     
108     /**
109      * Constructs an EnvironmentWrapper object from a Request
110      * and Response objects
111      */

112     public EnvironmentWrapper(Environment env,
113                               String JavaDoc requestURI,
114                               String JavaDoc queryString,
115                               Logger logger,
116                               ComponentManager manager,
117                               boolean rawMode,
118                               String JavaDoc view)
119     throws MalformedURLException JavaDoc {
120         this(env, requestURI, queryString, logger, manager, rawMode, view, true);
121     }
122
123     /**
124      * Constructs an EnvironmentWrapper object from a Request
125      * and Response objects
126      */

127     public EnvironmentWrapper(Environment env,
128                               String JavaDoc requestURI,
129                               String JavaDoc queryString,
130                               Logger logger,
131                               ComponentManager manager,
132                               boolean rawMode,
133                               String JavaDoc view,
134                               boolean wrapResponse)
135     throws MalformedURLException JavaDoc {
136         super(env.getURI(), view, env.getContext(), env.getAction());
137         init(env, requestURI, queryString, logger, manager, rawMode, view, wrapResponse);
138     }
139
140     private void init(Environment env,
141                       String JavaDoc requestURI,
142                       String JavaDoc queryString,
143                       Logger logger,
144                       ComponentManager manager,
145                       boolean rawMode,
146                       String JavaDoc view,
147                       boolean wrapResponse)
148         throws MalformedURLException JavaDoc {
149 // super(env.getURI(), view, env.getContext(), env.getAction());
150
this.rootContext = env.getRootContext();
151
152         this.enableLogging(logger);
153         this.environment = env;
154         this.view = view;
155
156         this.prefix = new StringBuffer JavaDoc(env.getURIPrefix());
157
158         // create new object model and replace the request object
159
Map JavaDoc oldObjectModel = env.getObjectModel();
160         if (oldObjectModel instanceof HashMap JavaDoc) {
161             this.objectModel = (Map JavaDoc)((HashMap JavaDoc)oldObjectModel).clone();
162         } else {
163             this.objectModel = new HashMap JavaDoc(oldObjectModel.size()*2);
164             Iterator JavaDoc entries = oldObjectModel.entrySet().iterator();
165             Map.Entry JavaDoc entry;
166             while (entries.hasNext()) {
167                 entry = (Map.Entry JavaDoc)entries.next();
168                 this.objectModel.put(entry.getKey(), entry.getValue());
169             }
170         }
171         this.request = new RequestWrapper(ObjectModelHelper.getRequest(oldObjectModel),
172                                           requestURI,
173                                           queryString,
174                                           this,
175                                           rawMode);
176         this.objectModel.put(ObjectModelHelper.REQUEST_OBJECT, this.request);
177         if (wrapResponse) {
178             Response response = new ResponseWrapper(ObjectModelHelper.getResponse(oldObjectModel));
179             this.objectModel.put(ObjectModelHelper.RESPONSE_OBJECT, response);
180         }
181     }
182    
183     public EnvironmentWrapper(Environment env, ComponentManager manager, String JavaDoc uri, Logger logger, boolean wrapResponse) throws MalformedURLException JavaDoc {
184         super(env.getURI(), env.getView(), env.getContext(), env.getAction());
185
186         // FIXME(SW): code stolen from SitemapSource. Factorize somewhere...
187
boolean rawMode = false;
188
189         // remove the protocol
190
int position = uri.indexOf(':') + 1;
191         if (position != 0) {
192 // this.protocol = uri.substring(0, position-1);
193
// check for subprotocol
194
if (uri.startsWith("raw:", position)) {
195                 position += 4;
196                 rawMode = true;
197             }
198         } else {
199             throw new MalformedURLException JavaDoc("No protocol found for sitemap source in " + uri);
200         }
201
202         // does the uri point to this sitemap or to the root sitemap?
203
String JavaDoc prefix;
204         if (uri.startsWith("//", position)) {
205             position += 2;
206 // try {
207
// this.processor = (Processor)this.manager.lookup(Processor.ROLE);
208
// } catch (ComponentException e) {
209
// throw new MalformedURLException("Cannot get Processor instance");
210
// }
211
prefix = ""; // start at the root
212
} else if (uri.startsWith("/", position)) {
213             position ++;
214             prefix = null;
215 // this.processor = CocoonComponentManager.getCurrentProcessor();
216
} else {
217             throw new MalformedURLException JavaDoc("Malformed cocoon URI: " + uri);
218         }
219
220         // create the queryString (if available)
221
String JavaDoc queryString = null;
222         int queryStringPos = uri.indexOf('?', position);
223         if (queryStringPos != -1) {
224             queryString = uri.substring(queryStringPos + 1);
225             uri = uri.substring(position, queryStringPos);
226         } else if (position > 0) {
227             uri = uri.substring(position);
228         }
229
230         
231         // determine if the queryString specifies a cocoon-view
232
String JavaDoc view = null;
233         if (queryString != null) {
234             int index = queryString.indexOf(Constants.VIEW_PARAM);
235             if (index != -1
236                 && (index == 0 || queryString.charAt(index-1) == '&')
237                 && queryString.length() > index + Constants.VIEW_PARAM.length()
238                 && queryString.charAt(index+Constants.VIEW_PARAM.length()) == '=') {
239                 
240                 String JavaDoc tmp = queryString.substring(index+Constants.VIEW_PARAM.length()+1);
241                 index = tmp.indexOf('&');
242                 if (index != -1) {
243                     view = tmp.substring(0,index);
244                 } else {
245                     view = tmp;
246                 }
247             } else {
248                 view = env.getView();
249             }
250         } else {
251             view = env.getView();
252         }
253
254         // build the request uri which is relative to the context
255
String JavaDoc requestURI = (prefix == null ? env.getURIPrefix() + uri : uri);
256
257 // // create system ID
258
// this.systemId = queryString == null ?
259
// this.protocol + "://" + requestURI :
260
// this.protocol + "://" + requestURI + "?" + queryString;
261

262         this.init(env, requestURI, queryString, logger, manager, rawMode, view, wrapResponse);
263         this.setURI(prefix, uri);
264         
265     }
266
267     /**
268      * Redirect the client to a new URL is not allowed
269      */

270     public void redirect(boolean sessionmode, String JavaDoc newURL)
271     throws IOException JavaDoc {
272         this.redirectURL = newURL;
273
274         // check if session mode shall be activated
275
if (sessionmode) {
276             // get session from request, or create new session
277
request.getSession(true);
278         }
279     }
280
281     /**
282      * Redirect in the first non-wrapped environment
283      */

284     public void globalRedirect(boolean sessionmode, String JavaDoc newURL)
285     throws IOException JavaDoc {
286         if (environment instanceof EnvironmentWrapper) {
287             ((EnvironmentWrapper)environment).globalRedirect(sessionmode, newURL);
288         } else if ( environment instanceof MutableEnvironmentFacade ) {
289             ((MutableEnvironmentFacade)environment).getDelegate().globalRedirect(sessionmode, newURL);
290         } else {
291             environment.redirect(sessionmode,newURL);
292         }
293     }
294
295     /**
296      * Get the output stream
297      * @deprecated use {@link #getOutputStream(int)} instead.
298      */

299     public OutputStream JavaDoc getOutputStream()
300     throws IOException JavaDoc {
301         Deprecation.logger.warn("The method Environment.getOutputStream() " +
302         "is deprecated. Use getOutputStream(-1) instead.");
303         return this.outputStream == null
304             ? this.environment.getOutputStream()
305             : this.outputStream;
306     }
307
308     /**
309      * Get the output stream
310      */

311     public OutputStream JavaDoc getOutputStream(int bufferSize)
312     throws IOException JavaDoc {
313         return this.outputStream == null
314                 ? this.environment.getOutputStream(bufferSize)
315                 : this.outputStream;
316     }
317
318     /**
319      * Set the output stream for this environment. It hides the one of the
320      * wrapped environment.
321      */

322     public void setOutputStream(OutputStream JavaDoc stream) {
323         this.outputStream = stream;
324     }
325
326     /**
327      * Reset the response if possible. This allows error handlers to have
328      * a higher chance to produce clean output if the pipeline that raised
329      * the error has already output some data.
330      *
331      * @return true if the response was successfully reset
332     */

333     public boolean tryResetResponse()
334     throws IOException JavaDoc {
335         if (getOutputStream() != null
336             && getOutputStream() instanceof BufferedOutputStream) {
337             ((BufferedOutputStream)getOutputStream()).clearBuffer();
338             return true;
339         }
340         else
341           return super.tryResetResponse();
342     }
343
344     /**
345      * Commit the response
346      */

347     public void commitResponse()
348     throws IOException JavaDoc {
349         if (getOutputStream() != null
350             && getOutputStream() instanceof BufferedOutputStream) {
351             ((BufferedOutputStream)getOutputStream()).realFlush();
352         }
353         else
354           super.commitResponse();
355     }
356
357     /**
358      * if a redirect should happen this returns the url,
359      * otherwise <code>null</code> is returned
360      */

361     public String JavaDoc getRedirectURL() {
362         return this.redirectURL;
363     }
364     
365     public void reset() {
366         this.redirectURL = null;
367     }
368
369     /**
370      * Set the StatusCode
371      */

372     public void setStatus(int statusCode) {
373         // ignore this
374
}
375
376     public void setContentLength(int length) {
377         // ignore this
378
}
379
380     /**
381      * Set the ContentType
382      */

383     public void setContentType(String JavaDoc contentType) {
384         this.contentType = contentType;
385     }
386
387     /**
388      * Get the ContentType
389      */

390     public String JavaDoc getContentType() {
391         return this.contentType;
392     }
393
394     /**
395      * Get the underlying object model
396      */

397     public Map JavaDoc getObjectModel() {
398         return this.objectModel;
399     }
400
401     /**
402      * Set a new URI for processing. If the prefix is null the
403      * new URI is inside the current context.
404      * If the prefix is not null the context is changed to the root
405      * context and the prefix is set.
406      */

407     public void setURI(String JavaDoc prefix, String JavaDoc uris) {
408         if(getLogger().isDebugEnabled()) {
409             getLogger().debug("Setting uri (prefix=" + prefix + ", uris=" + uris + ")");
410         }
411         if ( !this.initializedComponents) {
412             this.initComponents();
413         }
414         if (prefix != null) {
415             setContext(getRootContext());
416             setURIPrefix(prefix);
417         }
418         this.uris = uris;
419     }
420
421     /**
422      * Lookup an attribute in this instance, and if not found search it
423      * in the wrapped environment.
424      *
425      * @param name a <code>String</code>, the name of the attribute to
426      * look for
427      * @return an <code>Object</code>, the value of the attribute or
428      * null if no such attribute was found.
429      */

430     public Object JavaDoc getAttribute(String JavaDoc name)
431     {
432         Object JavaDoc value = super.getAttribute(name);
433         
434         // get it from the wrapped env only if it's not defined here with a null value
435
if (value == null && !hasAttribute(name)) {
436             value = this.environment.getAttribute(name);
437         }
438
439         return value;
440     }
441
442     /**
443      * Remove attribute from the current instance.
444      *
445      * @param name a <code>String</code> value
446      */

447     public void removeAttribute(String JavaDoc name) {
448         super.removeAttribute(name);
449     }
450
451     /**
452      * Always return <code>false</code>.
453      */

454     public boolean isExternal() {
455         return false;
456     }
457
458     public void setInternalRedirect(boolean flag) {
459         this.internalRedirect = flag;
460         if ( flag ) {
461             ((RequestWrapper)this.request).setRequestURI(this.prefix.toString(), this.uris);
462         }
463     }
464
465     /* (non-Javadoc)
466      * @see org.apache.cocoon.environment.Environment#isInternRedirect()
467      */

468     public boolean isInternalRedirect() {
469         return this.internalRedirect;
470     }
471 }
472
Popular Tags