KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > lenya > cms > cocoon > generation > ProxyGenerator


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5  * use this file except in compliance with the License. You may obtain a copy of
6  * 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, WITHOUT
12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13  * License for the specific language governing permissions and limitations under
14  * the License.
15  *
16  */

17
18 /* $Id: ProxyGenerator.java 111427 2004-12-09 20:08:58Z michi $ */
19
20 package org.apache.lenya.cms.cocoon.generation;
21
22 import java.io.ByteArrayInputStream JavaDoc;
23 import java.io.ByteArrayOutputStream JavaDoc;
24 import java.io.InputStream JavaDoc;
25 import java.net.MalformedURLException JavaDoc;
26 import java.net.URL JavaDoc;
27 import java.util.Enumeration JavaDoc;
28
29 import org.apache.avalon.framework.component.Component;
30 import org.apache.avalon.framework.parameters.ParameterException;
31 import org.apache.avalon.framework.parameters.Parameterizable;
32 import org.apache.avalon.framework.parameters.Parameters;
33 import org.apache.cocoon.environment.Cookie;
34 import org.apache.cocoon.environment.ObjectModelHelper;
35 import org.apache.cocoon.environment.Request;
36 import org.apache.cocoon.environment.http.HttpRequest;
37 import org.apache.commons.httpclient.HostConfiguration;
38 import org.apache.commons.httpclient.HttpClient;
39 import org.apache.commons.httpclient.HttpState;
40 import org.apache.commons.httpclient.methods.PostMethod;
41 import org.apache.excalibur.xml.sax.SAXParser;
42 import org.apache.log4j.Category;
43 import org.xml.sax.InputSource JavaDoc;
44 import org.xml.sax.SAXException JavaDoc;
45 import org.xml.sax.helpers.AttributesImpl JavaDoc;
46
47 public class ProxyGenerator extends org.apache.cocoon.generation.ServletGenerator implements
48         Parameterizable {
49     private static Category log = Category.getInstance(ProxyGenerator.class);
50
51     // The URI of the namespace of this generator
52
private String JavaDoc URI = "http://apache.org/cocoon/lenya/proxygenerator/1.0";
53
54     /**
55      * No parameters implemented.
56      * @see org.apache.avalon.framework.parameters.Parameterizable#parameterize(org.apache.avalon.framework.parameters.Parameters)
57      */

58     public void parameterize(Parameters parameters) throws ParameterException {
59     }
60
61     /**
62      * @see org.apache.cocoon.generation.Generator#generate()
63      */

64     public void generate() throws SAXException JavaDoc {
65         Request request = (Request) objectModel.get(ObjectModelHelper.REQUEST_OBJECT);
66
67         log.debug("\n----------------------------------------------------------------"
68                 + "\n- Request: (" + request.getClass().getName() + ") at port "
69                 + request.getServerPort()
70                 + "\n----------------------------------------------------------------");
71
72         String JavaDoc submitMethod = request.getMethod();
73
74         SAXParser parser = null;
75
76         try {
77             // DEBUG
78
if (submitMethod.equals("POST")) {
79                 // FIXME: Andreas
80
if (request instanceof HttpRequest) {
81                     java.io.InputStream JavaDoc is = intercept(((HttpRequest) request).getInputStream());
82                 }
83             }
84
85             URL JavaDoc url = createURL(request);
86
87             // Forward "InputStream", Parameters, QueryString to Servlet
88
org.apache.commons.httpclient.HttpMethod httpMethod = null;
89
90             if (submitMethod.equals("POST")) {
91                 httpMethod = new PostMethod();
92
93                 Enumeration JavaDoc params = request.getParameterNames();
94
95                 while (params.hasMoreElements()) {
96                     String JavaDoc paramName = (String JavaDoc) params.nextElement();
97                     String JavaDoc[] paramValues = request.getParameterValues(paramName);
98
99                     for (int i = 0; i < paramValues.length; i++) {
100                         ((PostMethod) httpMethod).setParameter(paramName, paramValues[i]);
101                     }
102                 }
103             } else if (submitMethod.equals("GET")) {
104                 httpMethod = new org.apache.commons.httpclient.methods.GetMethod();
105                 httpMethod.setQueryString(request.getQueryString());
106             }
107
108             // Copy/clone Cookies
109
Cookie[] cookies = request.getCookies();
110             org.apache.commons.httpclient.Cookie[] transferedCookies = null;
111
112             if (cookies != null) {
113                 transferedCookies = new org.apache.commons.httpclient.Cookie[cookies.length];
114
115                 for (int i = 0; i < cookies.length; i++) {
116                     boolean secure = false; // http: false, https: true
117
transferedCookies[i] = new org.apache.commons.httpclient.Cookie(url.getHost(),
118                             cookies[i].getName(), cookies[i].getValue(), url.getFile(), null,
119                             secure);
120                 }
121             }
122
123             // Initialize HttpClient
124
HttpClient httpClient = new HttpClient();
125
126             // Set cookies
127
if ((transferedCookies != null) && (transferedCookies.length > 0)) {
128                 HttpState httpState = new HttpState();
129                 httpState.addCookies(transferedCookies);
130                 httpClient.setState(httpState);
131             }
132
133             // DEBUG cookies
134
// Send request to servlet
135
httpMethod.setRequestHeader("Content-type", "text/plain");
136             httpMethod.setPath(url.getPath());
137
138             // FIXME
139
for (Enumeration JavaDoc e = request.getHeaderNames(); e.hasMoreElements();) {
140                 String JavaDoc name = (String JavaDoc) e.nextElement();
141                 httpMethod.addRequestHeader(name, request.getHeader(name));
142             }
143             HostConfiguration hostConfiguration = new HostConfiguration();
144             hostConfiguration.setHost(url.getHost(), url.getPort());
145
146             log.debug("\n----------------------------------------------------------------"
147                     + "\n- Starting session at URI: " + url + "\n- Host: "
148                     + url.getHost() + "\n- Port: " + url.getPort()
149                     + "\n----------------------------------------------------------------");
150
151             int result = httpClient.executeMethod(hostConfiguration, httpMethod);
152
153             log.debug("\n----------------------------------------------------------------"
154                     + "\n- Result: " + result
155                     + "\n----------------------------------------------------------------");
156
157             byte[] sresponse = httpMethod.getResponseBody();
158
159             httpMethod.releaseConnection();
160
161             // Return XML
162
InputSource JavaDoc input = new InputSource JavaDoc(new ByteArrayInputStream JavaDoc(sresponse));
163             parser = (SAXParser) this.manager.lookup(SAXParser.ROLE);
164             parser.parse(input, this.xmlConsumer);
165         } catch (SAXException JavaDoc e) {
166             throw e;
167         } catch (Exception JavaDoc e) {
168             getLogger().error("Generation failed: ", e);
169             throw new SAXException JavaDoc(e);
170         } finally {
171             this.manager.release((Component) parser);
172         }
173     }
174
175     /**
176      * Log input stream for debugging
177      *
178      * @param in an <code>InputStream</code> value
179      *
180      * @return an <code>InputStream</code> value
181      *
182      * @exception Exception if an error occurs
183      */

184     private InputStream JavaDoc intercept(InputStream JavaDoc in) throws Exception JavaDoc {
185         byte[] buffer = new byte[1024];
186         int bytes_read;
187         ByteArrayOutputStream JavaDoc bufferOut = new ByteArrayOutputStream JavaDoc();
188
189         while ((bytes_read = in.read(buffer)) != -1) {
190             bufferOut.write(buffer, 0, bytes_read);
191         }
192
193         return new ByteArrayInputStream JavaDoc(bufferOut.toByteArray());
194     }
195
196     private URL JavaDoc createURL(Request request) throws MalformedURLException JavaDoc {
197         URL JavaDoc url = null;
198
199         try {
200             url = new URL JavaDoc(this.source);
201             log.debug(".createURL(): " + url);
202         } catch (MalformedURLException JavaDoc e) {
203             url = new URL JavaDoc("http://" + request.getServerName() + ":" + request.getServerPort() + this.source);
204             log.debug(".createURL(): Add localhost and port: " + url);
205         }
206
207         return url;
208     }
209
210     private void attribute(AttributesImpl JavaDoc attr, String JavaDoc name, String JavaDoc value) {
211         attr.addAttribute("", name, name, "CDATA", value);
212     }
213
214     private void start(String JavaDoc name, AttributesImpl JavaDoc attr) throws SAXException JavaDoc {
215         super.contentHandler.startElement(URI, name, name, attr);
216         attr.clear();
217     }
218
219     private void end(String JavaDoc name) throws SAXException JavaDoc {
220         super.contentHandler.endElement(URI, name, name);
221     }
222
223     private void data(String JavaDoc data) throws SAXException JavaDoc {
224         super.contentHandler.characters(data.toCharArray(), 0, data.length());
225     }
226 }
227
Popular Tags