You are viewing a plain text version of this content. The canonical link for it is here.
Posted to cvs@cocoon.apache.org by jo...@apache.org on 2003/07/05 06:44:57 UTC
cvs commit: cocoon-2.1/src/java/org/apache/cocoon/generation WebServiceProxyGenerator.java
joerg 2003/07/04 21:44:57
Modified: src/java/org/apache/cocoon/generation
WebServiceProxyGenerator.java
Log:
refactoring:
final String constants,
bugfix 21340 (host null),
replaced all deprecated stuff and removed all work arounds (hopefully no longer needed),
removed the buggy <?xml test - what is if no XML declaration is sent? Let this handle the parser!, furthermore indexOf(<?xml) was not used to substring the response
using getResponseBody() (byte[]) instead of getResponseBodyAsString(), but this does not fix the encoding issue :-(,
logging TODOs fixed,
code formatting
Revision Changes Path
1.4 +205 -237 cocoon-2.1/src/java/org/apache/cocoon/generation/WebServiceProxyGenerator.java
Index: WebServiceProxyGenerator.java
===================================================================
RCS file: /home/cvs/cocoon-2.1/src/java/org/apache/cocoon/generation/WebServiceProxyGenerator.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- WebServiceProxyGenerator.java 16 Mar 2003 17:49:15 -0000 1.3
+++ WebServiceProxyGenerator.java 5 Jul 2003 04:44:57 -0000 1.4
@@ -1,36 +1,36 @@
/*
-
+
============================================================================
The Apache Software License, Version 1.1
============================================================================
-
+
Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
-
+
Redistribution and use in source and binary forms, with or without modifica-
tion, are permitted provided that the following conditions are met:
-
+
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
-
+
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
-
+
3. The end-user documentation included with the redistribution, if any, must
include the following acknowledgment: "This product includes software
developed by the Apache Software Foundation (http://www.apache.org/)."
Alternately, this acknowledgment may appear in the software itself, if
and wherever such third-party acknowledgments normally appear.
-
+
4. The names "Apache Cocoon" and "Apache Software Foundation" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
apache@apache.org.
-
+
5. Products derived from this software may not be called "Apache", nor may
"Apache" appear in their name, without prior written permission of the
Apache Software Foundation.
-
+
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
@@ -41,20 +41,14 @@
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
+
This software consists of voluntary contributions made by many individuals
on behalf of the Apache Software Foundation and was originally created by
Stefano Mazzocchi <st...@apache.org>. For more information on the Apache
Software Foundation, please see <http://www.apache.org/>.
-
- */
-package org.apache.cocoon.generation;
-import java.io.IOException;
-import java.io.StringReader;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.Map;
+ */
+package org.apache.cocoon.generation;
import org.apache.avalon.framework.component.Component;
import org.apache.avalon.framework.component.ComponentException;
@@ -67,16 +61,24 @@
import org.apache.cocoon.environment.SourceResolver;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.HttpUrlMethod;
+import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
-import org.apache.commons.httpclient.methods.UrlGetMethod;
-import org.apache.commons.httpclient.methods.UrlPostMethod;
+import org.apache.commons.httpclient.URI;
+import org.apache.commons.httpclient.URIException;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.excalibur.source.Source;
import org.apache.excalibur.source.SourceException;
import org.apache.excalibur.xml.sax.SAXParser;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.Map;
+
/**
*
* The WebServiceProxyGenerator is intended to:
@@ -106,226 +108,192 @@
*/
public class WebServiceProxyGenerator extends ComposerGenerator {
- /**
- * Setup the WSP generator.
- *
- */
- public void setup(SourceResolver resolver, Map objectModel, String src, Parameters par)
- throws ProcessingException, SAXException, IOException
- {
- super.setup(resolver, objectModel, src, par);
-
- try {
- Source inputSource = resolver.resolveURI(super.source);
- this.source = inputSource.getURI();
- } catch (SourceException se) {
- throw SourceUtil.handle("Unable to resolve " + super.source, se);
- }
-
- configuredHttpMethod = par.getParameter("wsproxy-method", METHOD_GET);
-
- httpClient = getHttpClient();
-
- }
-
-
- /**
- * Recycle this component.
- * All instance variables are set to <code>null</code>.
- */
- public void recycle()
- {
- httpClient = null;
-
- super.recycle();
- }
-
-
- /**
- * Generate XML data.
- */
- public void generate()
- throws IOException, SAXException, ProcessingException
- {
- SAXParser parser = null;
- try
- {
- if (this.getLogger().isDebugEnabled()) {
- this.getLogger().debug("processing Web Service request: " + this.source );
- }
-
- // forward request and bring response back
- String remoteResponseXml = fetch();
-
- InputSource inputSource = new InputSource(new StringReader( remoteResponseXml ));
-
- if (getLogger().isDebugEnabled()) {
- getLogger().debug( "processing Web Service Response " + remoteResponseXml );
- }
-
- parser = (SAXParser)this.manager.lookup(SAXParser.ROLE);
- parser.parse(inputSource, super.xmlConsumer);
-
- }
- catch (ComponentException ex)
- {
- throw new ProcessingException( "WebServiceProxyGenerator.generate() error", ex);
- }
- finally
- {
- this.manager.release((Component)parser);
- }
-
- } // generate
-
-
- /**
- *
- * Forward the request and return the response
- *
- * Will use an UrlGetMethod to benefit the cacheing mechanism
- * and intermediate proxy servers.
- * It is potentially possible that the size of the request
- * may grow beyond a certain limit for GET and it will require POST instead.
- *
- * @return String XML response
- *
- */
- public String fetch() throws ProcessingException
- {
- try
- {
-
-
- // TODO: Write a log entry detailing which httpMethod was configured
-
- HttpUrlMethod method = null;
-
- // check which method (GET or POST) to use.
- if ( this.configuredHttpMethod.equalsIgnoreCase( METHOD_POST ) )
- {
- method = new UrlPostMethod( this.source );
- ((UrlPostMethod)method).setUseDisk(false);
- } else {
- method = new UrlGetMethod( this.source );
- ((UrlGetMethod)method).setUseDisk(false);
- }
-
- // this should probably be exposed as a sitemap option
- method.setFollowRedirects( true );
-
- // copy request parameters and merge with URL parameters
- Request request = ObjectModelHelper.getRequest( objectModel );
-
-
- ArrayList paramList = new ArrayList();
- Enumeration enum = request.getParameterNames();
- while ( enum.hasMoreElements() )
- {
- String pname = (String)enum.nextElement();
- String[] paramsForName = request.getParameterValues( pname );
- for (int i = 0; i < paramsForName.length; i++)
- {
- NameValuePair pair =
- new NameValuePair( pname, paramsForName[i] );
- paramList.add( pair );
+ private static final String HTTP_CLIENT = "HTTP_CLIENT";
+ private static final String METHOD_GET = "GET";
+ private static final String METHOD_POST = "POST";
+
+ private HttpClient httpClient = null;
+ private String configuredHttpMethod = null;
+
+ public void setup(SourceResolver resolver, Map objectModel, String src, Parameters par) throws ProcessingException, SAXException, IOException {
+ super.setup(resolver, objectModel, src, par);
+
+ try {
+ Source inputSource = resolver.resolveURI(super.source);
+ this.source = inputSource.getURI();
+ } catch (SourceException se) {
+ throw SourceUtil.handle("Unable to resolve " + super.source, se);
}
- }
- if ( paramList.size() > 0 )
- {
- NameValuePair[] allSubmitParams =
- new NameValuePair[ paramList.size() ];
- paramList.toArray( allSubmitParams );
-
- String urlQryString = method.getQueryString();
-
- // use HttpClient encoding routines
- method.setQueryString( allSubmitParams );
- String submitQryString = method.getQueryString();
-
- // set final web service query string
- method.setQueryString( urlQryString + "&" + submitQryString );
- } // if there are submit parameters
-
- int htcode = httpClient.executeMethod( method );
-
- // meaningful reaction to htcodes different than 200
- // TODO: We should probably be logging this, as well.
- if (htcode >= 400) {
- throw new ProcessingException( "The remote returned error " + htcode + " when attempting to access remote URL:" + method.getUrl() );
- }
-
-
- // FIXME: This sleep() is a temporary workaround
- // to avoid NullPointerException in the next line.
- Thread.sleep( 100 );
-
- String ret = method.getResponseBodyAsString();
-
- int startOfXML = ret.indexOf("<?xml");
- if (startOfXML == -1)
- { // No xml?!
- throw new ProcessingException("Invalid (non XML) response returned from remote URL: " + method.getUrl() );
- }
-
- ret.substring(startOfXML);
-
- return ret;
-
- } catch (Exception ex)
- {
- throw new ProcessingException("Error invoking remote service: " + ex,
- ex);
+ this.configuredHttpMethod = par.getParameter("wsproxy-method", METHOD_GET);
+ this.httpClient = this.getHttpClient();
}
- } // fetch
-
-
-/**
- * Create once per client session and
- * consequetively return an HttpMultiClient
- *
- */
-protected HttpClient getHttpClient()
-{
- Request request = ObjectModelHelper.getRequest( objectModel );
- Session session = request.getSession( true );
- HttpClient httpClient = null;
- if (session != null)
- {
- httpClient = (HttpClient) session.getAttribute( HTTP_CLIENT );
- }
- if (httpClient == null)
- {
- httpClient = new HttpClient();
-
- if (System.getProperty("http.proxyHost") != null)
- {
- String proxyHost = System.getProperty("http.proxyHost");
- int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort"));
- HostConfiguration config = httpClient.getHostConfiguration();
- if (config == null) {
- config = new HostConfiguration();
- }
- config.setProxy(proxyHost, proxyPort);
- httpClient.setHostConfiguration(config);
+
+ /**
+ * Generate XML data.
+ */
+ public void generate() throws IOException, SAXException, ProcessingException {
+ SAXParser parser = null;
+ try {
+ if (this.getLogger().isDebugEnabled()) {
+ this.getLogger().debug("processing Web Service request: " + this.source);
+ }
+
+ // forward request and bring response back
+ byte[] response = this.fetch();
+ if (this.getLogger().isDebugEnabled()) {
+ this.getLogger().debug("response: " + new String(response));
+ }
+
+ /* TODO: Though I avoided the getResponseBodyAsString(), the content
+ * seems not to be parsed correctly. Who cares about the encoding
+ * in the XML declaration?
+ * {@link http://jakarta.apache.org/commons/httpclient/apidocs/org/apache/commons/httpclient/HttpMethodBase.html#getResponseBodyAsString()}
+ */
+ ByteArrayInputStream responseStream = new ByteArrayInputStream(response);
+ InputSource inputSource = new InputSource(responseStream);
+ parser = (SAXParser)this.manager.lookup(SAXParser.ROLE);
+ parser.parse(inputSource, super.xmlConsumer);
+
+ } catch (ComponentException ex) {
+ throw new ProcessingException("WebServiceProxyGenerator.generate() error", ex);
+ } finally {
+ this.manager.release((Component)parser);
+ }
+
+ } // generate
+
+ /**
+ * Recycle this component.
+ * All instance variables are set to <code>null</code>.
+ */
+ public void recycle() {
+ this.httpClient = null;
+ this.configuredHttpMethod = null;
+ super.recycle();
}
-
- session.setAttribute( HTTP_CLIENT, httpClient );
- }
- return httpClient;
-}
-
-// private attributes section
-private static String HTTP_CLIENT = "HTTP_CLIENT";
-private HttpClient httpClient;
-
-// for GET/POST configurability
-private static String METHOD_GET = "GET";
-private static String METHOD_POST = "POST";
-// default to GET
-private String configuredHttpMethod = METHOD_GET;
+ /**
+ * Forwards the request and returns the response.
+ *
+ * The rest is probably out of date:
+ * Will use a UrlGetMethod to benefit the cacheing mechanism
+ * and intermediate proxy servers.
+ * It is potentially possible that the size of the request
+ * may grow beyond a certain limit for GET and it will require POST instead.
+ *
+ * @return byte[] XML response
+ */
+ public byte[] fetch() throws ProcessingException {
+ HttpMethod method = null;
+
+ // check which method (GET or POST) to use.
+ if (this.configuredHttpMethod.equalsIgnoreCase(METHOD_POST)) {
+ method = new PostMethod(this.source);
+ } else {
+ method = new GetMethod(this.source);
+ }
+
+ if (this.getLogger().isDebugEnabled()) {
+ this.getLogger().debug("request HTTP method: " + method.getName());
+ }
+
+ // this should probably be exposed as a sitemap option
+ method.setFollowRedirects(true);
+
+ // copy request parameters and merge with URL parameters
+ Request request = ObjectModelHelper.getRequest(objectModel);
+
+ ArrayList paramList = new ArrayList();
+ Enumeration enum = request.getParameterNames();
+ while (enum.hasMoreElements()) {
+ String pname = (String)enum.nextElement();
+ String[] paramsForName = request.getParameterValues(pname);
+ for (int i = 0; i < paramsForName.length; i++) {
+ NameValuePair pair = new NameValuePair(pname, paramsForName[i]);
+ paramList.add(pair);
+ }
+ }
+
+ if (paramList.size() > 0) {
+ NameValuePair[] allSubmitParams = new NameValuePair[paramList.size()];
+ paramList.toArray(allSubmitParams);
+
+ String urlQryString = method.getQueryString();
+
+ // use HttpClient encoding routines
+ method.setQueryString(allSubmitParams);
+ String submitQryString = method.getQueryString();
+
+ // set final web service query string
+ method.setQueryString(urlQryString + "&" + submitQryString);
+ } // if there are submit parameters
+
+ byte[] response = null;
+ try {
+ int httpStatus = httpClient.executeMethod(method);
+ if (httpStatus < 400) {
+ if (this.getLogger().isDebugEnabled()) {
+ this.getLogger().debug("Return code when accessing the remote Url: " + httpStatus);
+ }
+ } else {
+ throw new ProcessingException("The remote returned error " + httpStatus + " when attempting to access remote URL:" + method.getURI());
+ }
+ } catch (URIException e) {
+ throw new ProcessingException("There is a problem with the URI: " + this.source, e);
+ } catch (IOException e) {
+ try {
+ throw new ProcessingException("Exception when attempting to access the remote URL: " + method.getURI(), e);
+ } catch (URIException ue) {
+ throw new ProcessingException("There is a problem with the URI: " + this.source, ue);
+ }
+ } finally {
+ /* It is important to always read the entire response and release the
+ * connection regardless of whether the server returned an error or not.
+ * {@link http://jakarta.apache.org/commons/httpclient/tutorial.html}
+ */
+ response = method.getResponseBody();
+ method.releaseConnection();
+ }
+
+ return response;
+ } // fetch
+
+ /**
+ * Create one per client session.
+ */
+ protected HttpClient getHttpClient() throws ProcessingException {
+ Request request = ObjectModelHelper.getRequest(objectModel);
+ Session session = request.getSession(true);
+ HttpClient httpClient = null;
+ if (session != null) {
+ httpClient = (HttpClient)session.getAttribute(HTTP_CLIENT);
+ }
+ if (httpClient == null) {
+ httpClient = new HttpClient();
+ HostConfiguration config = httpClient.getHostConfiguration();
+ if (config == null) {
+ config = new HostConfiguration();
+ }
+
+ try {
+ config.setHost(new URI(this.source));
+ } catch (URIException ex) {
+ throw new ProcessingException("URI format error: " + ex, ex);
+ }
+
+ if (System.getProperty("http.proxyHost") != null) {
+ String proxyHost = System.getProperty("http.proxyHost");
+ int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort"));
+ config.setProxy(proxyHost, proxyPort);
+ }
+
+ httpClient.setHostConfiguration(config);
+
+ session.setAttribute(HTTP_CLIENT, httpClient);
+ }
+ return httpClient;
+ }
} // class