You are viewing a plain text version of this content. The canonical link for it is here.
Posted to java-dev@axis.apache.org by de...@apache.org on 2008/06/24 13:07:10 UTC
svn commit: r671127 [5/8] - in /webservices/axis2/trunk/java: ./
modules/addressing/ modules/clustering/
modules/clustering/test/org/apache/axis2/clustering/ modules/integration/
modules/integration/test-resources/deployment/ modules/integration/test/o...
Added: webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/HTTPTransportUtils.java
URL: http://svn.apache.org/viewvc/webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/HTTPTransportUtils.java?rev=671127&view=auto
==============================================================================
--- webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/HTTPTransportUtils.java (added)
+++ webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/HTTPTransportUtils.java Tue Jun 24 04:07:03 2008
@@ -0,0 +1,404 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+package org.apache.axis2.transport.http;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.OMException;
+import org.apache.axiom.om.OMNamespace;
+import org.apache.axiom.soap.SOAP11Constants;
+import org.apache.axiom.soap.SOAP12Constants;
+import org.apache.axiom.soap.SOAPEnvelope;
+import org.apache.axiom.soap.SOAPFactory;
+import org.apache.axiom.soap.SOAPProcessingException;
+import org.apache.axiom.soap.impl.llom.soap11.SOAP11Factory;
+import org.apache.axiom.soap.impl.llom.soap12.SOAP12Factory;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.Constants;
+import org.apache.axis2.addressing.EndpointReference;
+import org.apache.axis2.builder.BuilderUtil;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.context.OperationContext;
+import org.apache.axis2.description.AxisService;
+import org.apache.axis2.description.Parameter;
+import org.apache.axis2.engine.AxisEngine;
+import org.apache.axis2.engine.Handler.InvocationResponse;
+import org.apache.axis2.transport.TransportUtils;
+import org.apache.axis2.util.JavaUtils;
+import org.apache.axis2.util.Utils;
+
+import javax.xml.parsers.FactoryConfigurationError;
+import javax.xml.stream.XMLStreamException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.zip.GZIPInputStream;
+
+public class HTTPTransportUtils {
+
+
+ /**
+ * @deprecated This was used only by the now deprecated processHTTPGetRequest() method.
+ */
+ public static SOAPEnvelope createEnvelopeFromGetRequest(String requestUrl,
+ Map map, ConfigurationContext configCtx)
+ throws AxisFault {
+ String[] values =
+ Utils.parseRequestURLForServiceAndOperation(requestUrl,
+ configCtx.getServiceContextPath());
+ if (values == null) {
+ return new SOAP11Factory().getDefaultEnvelope();
+ }
+
+ if ((values[1] != null) && (values[0] != null)) {
+ String srvice = values[0];
+ AxisService service = configCtx.getAxisConfiguration().getService(srvice);
+ if (service == null) {
+ throw new AxisFault("service not found: " + srvice);
+ }
+ String operation = values[1];
+ SOAPFactory soapFactory = new SOAP11Factory();
+ SOAPEnvelope envelope = soapFactory.getDefaultEnvelope();
+ OMNamespace omNs = soapFactory.createOMNamespace(service.getSchemaTargetNamespace(),
+ service.getSchemaTargetNamespacePrefix());
+ soapFactory.createOMNamespace(service.getSchemaTargetNamespace(),
+ service.getSchemaTargetNamespacePrefix());
+ OMElement opElement = soapFactory.createOMElement(operation, omNs);
+ Iterator it = map.keySet().iterator();
+
+ while (it.hasNext()) {
+ String name = (String) it.next();
+ String value = (String) map.get(name);
+ OMElement omEle = soapFactory.createOMElement(name, omNs);
+
+ omEle.setText(value);
+ opElement.addChild(omEle);
+ }
+
+ envelope.getBody().addChild(opElement);
+
+ return envelope;
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * <p>
+ * Checks whether MTOM needs to be enabled for the message represented by
+ * the msgContext. We check value assigned to the "enableMTOM" property
+ * either using the config files (axis2.xml, services.xml) or
+ * programatically. Programatic configuration is given priority. If the
+ * given value is "optional", MTOM will be enabled only if the incoming
+ * message was an MTOM message.
+ * </p>
+ *
+ * @param msgContext
+ * @return true if SwA needs to be enabled
+ */
+ public static boolean doWriteMTOM(MessageContext msgContext) {
+ boolean enableMTOM;
+ Object enableMTOMObject = null;
+ // First check the whether MTOM is enabled by the configuration
+ // (Eg:Axis2.xml, services.xml)
+ Parameter parameter = msgContext.getParameter(Constants.Configuration.ENABLE_MTOM);
+ if (parameter != null) {
+ enableMTOMObject = parameter.getValue();
+ }
+ // Check whether the configuration is overridden programatically..
+ // Priority given to programatically setting of the value
+ Object property = msgContext.getProperty(Constants.Configuration.ENABLE_MTOM);
+ if (property != null) {
+ enableMTOMObject = property;
+ }
+ enableMTOM = JavaUtils.isTrueExplicitly(enableMTOMObject);
+ // Handle the optional value for enableMTOM
+ // If the value for 'enableMTOM' is given as optional and if the request
+ // message was a MTOM message we sent out MTOM
+ if (!enableMTOM && msgContext.isDoingMTOM() && (enableMTOMObject instanceof String)) {
+ if (((String) enableMTOMObject).equalsIgnoreCase(Constants.VALUE_OPTIONAL)) {
+ enableMTOM = true;
+ }
+ }
+ return enableMTOM;
+ }
+
+ /**
+ * <p>
+ * Checks whether SOAP With Attachments (SwA) needs to be enabled for the
+ * message represented by the msgContext. We check value assigned to the
+ * "enableSwA" property either using the config files (axis2.xml,
+ * services.xml) or programatically. Programatic configuration is given
+ * priority. If the given value is "optional", SwA will be enabled only if
+ * the incoming message was SwA type.
+ * </p>
+ *
+ * @param msgContext
+ * @return true if SwA needs to be enabled
+ */
+ public static boolean doWriteSwA(MessageContext msgContext) {
+ boolean enableSwA;
+ Object enableSwAObject = null;
+ // First check the whether SwA is enabled by the configuration
+ // (Eg:Axis2.xml, services.xml)
+ Parameter parameter = msgContext.getParameter(Constants.Configuration.ENABLE_SWA);
+ if (parameter != null) {
+ enableSwAObject = parameter.getValue();
+ }
+ // Check whether the configuration is overridden programatically..
+ // Priority given to programatically setting of the value
+ Object property = msgContext.getProperty(Constants.Configuration.ENABLE_SWA);
+ if (property != null) {
+ enableSwAObject = property;
+ }
+ enableSwA = JavaUtils.isTrueExplicitly(enableSwAObject);
+ // Handle the optional value for enableSwA
+ // If the value for 'enableSwA' is given as optional and if the request
+ // message was a SwA message we sent out SwA
+ if (!enableSwA && msgContext.isDoingSwA() && (enableSwAObject instanceof String)) {
+ if (((String) enableSwAObject).equalsIgnoreCase(Constants.VALUE_OPTIONAL)) {
+ enableSwA = true;
+ }
+ }
+ return enableSwA;
+ }
+
+ /**
+ * Utility method to query CharSetEncoding. First look in the
+ * MessageContext. If it's not there look in the OpContext. Use the defualt,
+ * if it's not given in either contexts.
+ *
+ * @param msgContext
+ * @return CharSetEncoding
+ */
+ public static String getCharSetEncoding(MessageContext msgContext) {
+ String charSetEnc = (String) msgContext
+ .getProperty(Constants.Configuration.CHARACTER_SET_ENCODING);
+
+ if (charSetEnc == null) {
+ OperationContext opctx = msgContext.getOperationContext();
+ if (opctx != null) {
+ charSetEnc = (String) opctx
+ .getProperty(Constants.Configuration.CHARACTER_SET_ENCODING);
+ }
+ /**
+ * If the char set enc is still not found use the default
+ */
+ if (charSetEnc == null) {
+ charSetEnc = MessageContext.DEFAULT_CHAR_SET_ENCODING;
+ }
+ }
+ return charSetEnc;
+ }
+
+ /**
+ * @param msgContext - The MessageContext of the Request Message
+ * @param out - The output stream of the response
+ * @param soapAction - SoapAction of the request
+ * @param requestURI - The URL that the request came to
+ * @param configurationContext - The Axis Configuration Context
+ * @param requestParameters - The parameters of the request message
+ * @return - boolean indication whether the operation was succesfull
+ * @throws AxisFault - Thrown in case a fault occurs
+ * @deprecated use RESTUtil.processURLRequest(MessageContext msgContext, OutputStream out, String contentType) instead
+ */
+
+ public static boolean processHTTPGetRequest(MessageContext msgContext,
+ OutputStream out, String soapAction,
+ String requestURI,
+ ConfigurationContext configurationContext,
+ Map requestParameters)
+ throws AxisFault {
+ if ((soapAction != null) && soapAction.startsWith("\"") && soapAction.endsWith("\"")) {
+ soapAction = soapAction.substring(1, soapAction.length() - 1);
+ }
+
+ msgContext.setSoapAction(soapAction);
+ msgContext.setTo(new EndpointReference(requestURI));
+ msgContext.setProperty(MessageContext.TRANSPORT_OUT, out);
+ msgContext.setServerSide(true);
+ SOAPEnvelope envelope = HTTPTransportUtils.createEnvelopeFromGetRequest(requestURI,
+ requestParameters,
+ configurationContext);
+
+ if (envelope == null) {
+ return false;
+ } else {
+ msgContext.setDoingREST(true);
+ msgContext.setEnvelope(envelope);
+ AxisEngine.receive(msgContext);
+ return true;
+ }
+ }
+
+ private static final int VERSION_UNKNOWN = 0;
+ private static final int VERSION_SOAP11 = 1;
+ private static final int VERSION_SOAP12 = 2;
+
+ public static InvocationResponse processHTTPPostRequest(MessageContext msgContext,
+ InputStream in,
+ OutputStream out,
+ String contentType,
+ String soapActionHeader,
+ String requestURI)
+ throws AxisFault {
+ int soapVersion = VERSION_UNKNOWN;
+ try {
+ soapVersion = initializeMessageContext(msgContext, soapActionHeader, requestURI, contentType);
+ msgContext.setProperty(MessageContext.TRANSPORT_OUT, out);
+
+ msgContext.setEnvelope(
+ TransportUtils.createSOAPMessage(
+ msgContext,
+ handleGZip(msgContext, in),
+ contentType));
+ return AxisEngine.receive(msgContext);
+ } catch (SOAPProcessingException e) {
+ throw AxisFault.makeFault(e);
+ } catch (AxisFault e) {
+ throw e;
+ } catch (IOException e) {
+ throw AxisFault.makeFault(e);
+ } catch (OMException e) {
+ throw AxisFault.makeFault(e);
+ } catch (XMLStreamException e) {
+ throw AxisFault.makeFault(e);
+ } catch (FactoryConfigurationError e) {
+ throw AxisFault.makeFault(e);
+ } finally {
+ if ((msgContext.getEnvelope() == null) && soapVersion != VERSION_SOAP11) {
+ msgContext.setEnvelope(new SOAP12Factory().getDefaultEnvelope());
+ }
+ }
+ }
+
+ public static int initializeMessageContext(MessageContext msgContext,
+ String soapActionHeader,
+ String requestURI,
+ String contentType) {
+ int soapVersion = VERSION_UNKNOWN;
+ // remove the starting and trailing " from the SOAP Action
+ if ((soapActionHeader != null)
+ && soapActionHeader.length() > 0
+ && soapActionHeader.charAt(0) == '\"'
+ && soapActionHeader.endsWith("\"")) {
+ soapActionHeader = soapActionHeader.substring(1, soapActionHeader.length() - 1);
+ }
+
+ // fill up the Message Contexts
+ msgContext.setSoapAction(soapActionHeader);
+ msgContext.setTo(new EndpointReference(requestURI));
+ msgContext.setServerSide(true);
+
+ // get the type of char encoding
+ String charSetEnc = BuilderUtil.getCharSetEncoding(contentType);
+ if (charSetEnc == null) {
+ charSetEnc = MessageContext.DEFAULT_CHAR_SET_ENCODING;
+ }
+ msgContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
+
+ if (contentType != null) {
+ if (contentType.indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) > -1) {
+ soapVersion = VERSION_SOAP12;
+ TransportUtils.processContentTypeForAction(contentType, msgContext);
+ } else if (contentType
+ .indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) > -1) {
+ soapVersion = VERSION_SOAP11;
+ } else if (isRESTRequest(contentType)) {
+ // If REST, construct a SOAP11 envelope to hold the rest message and
+ // indicate that this is a REST message.
+ soapVersion = VERSION_SOAP11;
+ msgContext.setDoingREST(true);
+ }
+ if (soapVersion == VERSION_SOAP11) {
+ // TODO Keith : Do we need this anymore
+ // Deployment configuration parameter
+ Parameter enableREST = msgContext
+ .getParameter(Constants.Configuration.ENABLE_REST);
+ if ((soapActionHeader == null) && (enableREST != null)) {
+ if (Constants.VALUE_TRUE.equals(enableREST.getValue())) {
+ // If the content Type is text/xml (BTW which is the
+ // SOAP 1.1 Content type ) and the SOAP Action is
+ // absent it is rest !!
+ msgContext.setDoingREST(true);
+ }
+ }
+ }
+ }
+ return soapVersion;
+ }
+
+ public static InputStream handleGZip(MessageContext msgContext, InputStream in)
+ throws IOException {
+ Map headers = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
+
+ if (headers != null) {
+ if (HTTPConstants.COMPRESSION_GZIP
+ .equals(headers.get(HTTPConstants.HEADER_CONTENT_ENCODING)) ||
+ HTTPConstants.COMPRESSION_GZIP.equals(headers.get(
+ HTTPConstants.HEADER_CONTENT_ENCODING_LOWERCASE))) {
+ in = new GZIPInputStream(in);
+ }
+ }
+ return in;
+ }
+
+ public static boolean isDoingREST(MessageContext msgContext) {
+ boolean enableREST = false;
+
+ // check whether isDoingRest is already true in the message context
+ if (msgContext.isDoingREST()) {
+ return true;
+ }
+
+ Object enableRESTProperty = msgContext.getProperty(Constants.Configuration.ENABLE_REST);
+ if (enableRESTProperty != null) {
+ enableREST = JavaUtils.isTrueExplicitly(enableRESTProperty);
+ }
+
+ msgContext.setDoingREST(enableREST);
+
+ return enableREST;
+ }
+
+ /**
+ * This will match for content types that will be regarded as REST in WSDL2.0.
+ * This contains,
+ * 1. application/xml
+ * 2. application/x-www-form-urlencoded
+ * 3. multipart/form-data
+ * <p/>
+ * If the request doesnot contain a content type; this will return true.
+ *
+ * @param contentType
+ * @return Boolean
+ */
+ public static boolean isRESTRequest(String contentType) {
+ if (contentType == null) {
+ return false;
+ }
+ return (contentType.indexOf(HTTPConstants.MEDIA_TYPE_APPLICATION_XML) > -1 ||
+ contentType.indexOf(HTTPConstants.MEDIA_TYPE_X_WWW_FORM) > -1 ||
+ contentType.indexOf(HTTPConstants.MEDIA_TYPE_MULTIPART_FORM_DATA) > -1);
+ }
+}
Added: webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/HTTPWorker.java
URL: http://svn.apache.org/viewvc/webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/HTTPWorker.java?rev=671127&view=auto
==============================================================================
--- webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/HTTPWorker.java (added)
+++ webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/HTTPWorker.java Tue Jun 24 04:07:03 2008
@@ -0,0 +1,374 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.axis2.transport.http;
+
+import org.apache.axis2.Constants;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.deployment.DeploymentConstants;
+import org.apache.axis2.description.AxisService;
+import org.apache.axis2.engine.Handler.InvocationResponse;
+import org.apache.axis2.transport.RequestResponseTransport;
+import org.apache.axis2.transport.TransportUtils;
+import org.apache.axis2.transport.http.server.AxisHttpRequest;
+import org.apache.axis2.transport.http.server.AxisHttpResponse;
+import org.apache.axis2.transport.http.server.HttpUtils;
+import org.apache.axis2.transport.http.server.Worker;
+import org.apache.axis2.transport.http.util.RESTUtil;
+import org.apache.http.Header;
+import org.apache.http.HttpException;
+import org.apache.http.HttpStatus;
+import org.apache.http.MethodNotSupportedException;
+import org.apache.http.message.BasicHeader;
+import org.apache.http.protocol.HTTP;
+import org.apache.http.util.EncodingUtils;
+import org.apache.ws.commons.schema.XmlSchema;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.ByteArrayInputStream;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+public class HTTPWorker implements Worker {
+
+ public HTTPWorker() {
+ }
+
+ public void service(
+ final AxisHttpRequest request,
+ final AxisHttpResponse response,
+ final MessageContext msgContext) throws HttpException, IOException {
+
+ ConfigurationContext configurationContext = msgContext.getConfigurationContext();
+ final String servicePath = configurationContext.getServiceContextPath();
+ final String contextPath =
+ (servicePath.startsWith("/") ? servicePath : "/" + servicePath) + "/";
+
+ String uri = request.getRequestURI();
+ String method = request.getMethod();
+ String soapAction = HttpUtils.getSoapAction(request);
+ InvocationResponse pi;
+
+ if (method.equals(HTTPConstants.HEADER_GET)) {
+ if (uri.equals("/favicon.ico")) {
+ response.setStatus(HttpStatus.SC_MOVED_PERMANENTLY);
+ response.addHeader(new BasicHeader("Location", "http://ws.apache.org/favicon.ico"));
+ return;
+ }
+ if (!uri.startsWith(contextPath)) {
+ response.setStatus(HttpStatus.SC_MOVED_PERMANENTLY);
+ response.addHeader(new BasicHeader("Location", contextPath));
+ return;
+ }
+ if (uri.endsWith("axis2/services/")) {
+ String s = HTTPTransportReceiver.getServicesHTML(configurationContext);
+ response.setStatus(HttpStatus.SC_OK);
+ response.setContentType("text/html");
+ OutputStream out = response.getOutputStream();
+ out.write(EncodingUtils.getBytes(s, HTTP.ISO_8859_1));
+ return;
+ }
+ if (uri.indexOf("?") < 0) {
+ if (!uri.endsWith(contextPath)) {
+ if (uri.endsWith(".xsd") || uri.endsWith(".wsdl")) {
+ HashMap services = configurationContext.getAxisConfiguration().getServices();
+ String file = uri.substring(uri.lastIndexOf("/") + 1,
+ uri.length());
+ if ((services != null) && !services.isEmpty()) {
+ Iterator i = services.values().iterator();
+ while (i.hasNext()) {
+ AxisService service = (AxisService) i.next();
+ InputStream stream = service.getClassLoader().
+ getResourceAsStream("META-INF/" + file);
+ if (stream != null) {
+ OutputStream out = response.getOutputStream();
+ response.setContentType("text/xml");
+ ListingAgent.copy(stream, out);
+ out.flush();
+ out.close();
+ return;
+ }
+ }
+ }
+ } else {
+ String serviceName = uri.replaceAll(contextPath, "");
+ if (serviceName.indexOf("/") < 0) {
+ String s = HTTPTransportReceiver
+ .printServiceHTML(serviceName, configurationContext);
+ response.setStatus(HttpStatus.SC_OK);
+ response.setContentType("text/html");
+ OutputStream out = response.getOutputStream();
+ out.write(EncodingUtils.getBytes(s, HTTP.ISO_8859_1));
+ return;
+ }
+ }
+ }
+ }
+ if (uri.endsWith("?wsdl2")) {
+ String serviceName = uri.substring(uri.lastIndexOf("/") + 1, uri.length() - 6);
+ HashMap services = configurationContext.getAxisConfiguration().getServices();
+ AxisService service = (AxisService) services.get(serviceName);
+ if (service != null) {
+ response.setStatus(HttpStatus.SC_OK);
+ response.setContentType("text/xml");
+ service.printWSDL2(response.getOutputStream(), getHost(request));
+ return;
+ }
+ }
+ if (uri.endsWith("?wsdl")) {
+ String serviceName = uri.substring(uri.lastIndexOf("/") + 1, uri.length() - 5);
+ HashMap services = configurationContext.getAxisConfiguration().getServices();
+ AxisService service = (AxisService) services.get(serviceName);
+ if (service != null) {
+ response.setStatus(HttpStatus.SC_OK);
+ response.setContentType("text/xml");
+ service.printWSDL(response.getOutputStream(), getHost(request));
+ return;
+ }
+ }
+ if (uri.endsWith("?xsd")) {
+ String serviceName = uri.substring(uri.lastIndexOf("/") + 1, uri.length() - 4);
+ HashMap services = configurationContext.getAxisConfiguration().getServices();
+ AxisService service = (AxisService) services.get(serviceName);
+ if (service != null) {
+ response.setStatus(HttpStatus.SC_OK);
+ response.setContentType("text/xml");
+ service.printSchema(response.getOutputStream());
+ return;
+ }
+ }
+ //cater for named xsds - check for the xsd name
+ if (uri.indexOf("?xsd=") > 0) {
+ String serviceName =
+ uri.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf("?xsd="));
+ String schemaName = uri.substring(uri.lastIndexOf("=") + 1);
+
+ HashMap services = configurationContext.getAxisConfiguration().getServices();
+ AxisService service = (AxisService) services.get(serviceName);
+ if (service != null) {
+ //run the population logic just to be sure
+ service.populateSchemaMappings();
+ //write out the correct schema
+ Map schemaTable = service.getSchemaMappingTable();
+ XmlSchema schema = (XmlSchema) schemaTable.get(schemaName);
+ if (schema == null) {
+ int dotIndex = schemaName.indexOf('.');
+ if (dotIndex > 0) {
+ String schemaKey = schemaName.substring(0,dotIndex);
+ schema = (XmlSchema) schemaTable.get(schemaKey);
+ }
+ }
+ //schema found - write it to the stream
+ if (schema != null) {
+ response.setStatus(HttpStatus.SC_OK);
+ response.setContentType("text/xml");
+ schema.write(response.getOutputStream());
+ return;
+ } else {
+ InputStream instream = service.getClassLoader()
+ .getResourceAsStream(DeploymentConstants.META_INF + "/" + schemaName);
+
+ if (instream != null) {
+ response.setStatus(HttpStatus.SC_OK);
+ response.setContentType("text/xml");
+ OutputStream outstream = response.getOutputStream();
+ boolean checkLength = true;
+ int length = Integer.MAX_VALUE;
+ int nextValue = instream.read();
+ if (checkLength) length--;
+ while (-1 != nextValue && length >= 0) {
+ outstream.write(nextValue);
+ nextValue = instream.read();
+ if (checkLength) length--;
+ }
+ outstream.flush();
+ return;
+ } else {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ int ret = service.printXSD(baos, schemaName);
+ if(ret>0) {
+ baos.flush();
+ instream = new ByteArrayInputStream(baos.toByteArray());
+ response.setStatus(HttpStatus.SC_OK);
+ response.setContentType("text/xml");
+ OutputStream outstream = response.getOutputStream();
+ boolean checkLength = true;
+ int length = Integer.MAX_VALUE;
+ int nextValue = instream.read();
+ if (checkLength) length--;
+ while (-1 != nextValue && length >= 0) {
+ outstream.write(nextValue);
+ nextValue = instream.read();
+ if (checkLength) length--;
+ }
+ outstream.flush();
+ return;
+ }
+ // no schema available by that name - send 404
+ response.sendError(HttpStatus.SC_NOT_FOUND, "Schema Not Found!");
+ return;
+ }
+ }
+ }
+ }
+ if (uri.indexOf("?wsdl2=") > 0) {
+ String serviceName =
+ uri.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf("?wsdl2="));
+ if (processInternalWSDL(uri, configurationContext, serviceName, response)) return;
+ }
+ if (uri.indexOf("?wsdl=") > 0) {
+ String serviceName =
+ uri.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf("?wsdl="));
+ if (processInternalWSDL(uri, configurationContext, serviceName, response)) return;
+ }
+
+ String contentType = null;
+ Header[] headers = request.getHeaders(HTTPConstants.HEADER_CONTENT_TYPE);
+ if (headers != null && headers.length > 0) {
+ contentType = headers[0].getValue();
+ int index = contentType.indexOf(';');
+ if (index > 0) {
+ contentType = contentType.substring(0, index);
+ }
+ }
+
+ // deal with GET request
+ pi = RESTUtil.processURLRequest(
+ msgContext,
+ response.getOutputStream(),
+ contentType);
+
+ } else if (method.equals(HTTPConstants.HEADER_POST)) {
+ // deal with POST request
+
+ String contentType = request.getContentType();
+
+ if (HTTPTransportUtils.isRESTRequest(contentType)) {
+ pi = RESTUtil.processXMLRequest(
+ msgContext,
+ request.getInputStream(),
+ response.getOutputStream(),
+ contentType);
+ } else {
+ String ip = (String)msgContext.getProperty(MessageContext.TRANSPORT_ADDR);
+ if (ip != null){
+ uri = ip + uri;
+ }
+ pi = HTTPTransportUtils.processHTTPPostRequest(
+ msgContext,
+ request.getInputStream(),
+ response.getOutputStream(),
+ contentType,
+ soapAction,
+ uri);
+ }
+
+ } else if (method.equals(HTTPConstants.HEADER_PUT)) {
+
+ String contentType = request.getContentType();
+ msgContext.setProperty(Constants.Configuration.CONTENT_TYPE, contentType);
+
+ pi = RESTUtil.processXMLRequest(
+ msgContext,
+ request.getInputStream(),
+ response.getOutputStream(),
+ contentType);
+
+ } else if (method.equals(HTTPConstants.HEADER_DELETE)) {
+
+ pi = RESTUtil.processURLRequest(
+ msgContext,
+ response.getOutputStream(),
+ null);
+
+ } else {
+ throw new MethodNotSupportedException(method + " method not supported");
+ }
+
+ Boolean holdResponse =
+ (Boolean) msgContext.getProperty(RequestResponseTransport.HOLD_RESPONSE);
+ if (pi.equals(InvocationResponse.SUSPEND) ||
+ (holdResponse != null && Boolean.TRUE.equals(holdResponse))) {
+ try {
+ ((RequestResponseTransport) msgContext
+ .getProperty(RequestResponseTransport.TRANSPORT_CONTROL)).awaitResponse();
+ }
+ catch (InterruptedException e) {
+ throw new IOException("We were interrupted, so this may not function correctly:" +
+ e.getMessage());
+ }
+ }
+
+ // Finalize response
+ RequestResponseTransport requestResponseTransportControl =
+ (RequestResponseTransport) msgContext.
+ getProperty(RequestResponseTransport.TRANSPORT_CONTROL);
+
+ if (TransportUtils.isResponseWritten(msgContext) ||
+ ((requestResponseTransportControl != null) &&
+ requestResponseTransportControl.getStatus().equals(
+ RequestResponseTransport.RequestResponseTransportStatus.SIGNALLED))) {
+ // The response is written or signalled. The current status is used (probably SC_OK).
+ } else {
+ // The response may be ack'd, mark the status as accepted.
+ response.setStatus(HttpStatus.SC_ACCEPTED);
+ }
+ }
+
+ private boolean processInternalWSDL(String uri, ConfigurationContext configurationContext,
+ String serviceName, AxisHttpResponse response)
+ throws IOException {
+ String wsdlName = uri.substring(uri.lastIndexOf("=") + 1);
+
+ HashMap services = configurationContext.getAxisConfiguration().getServices();
+ AxisService service = (AxisService) services.get(serviceName);
+
+ if (service != null) {
+ response.setStatus(HttpStatus.SC_OK);
+ response.setContentType("text/xml");
+ service.printUserWSDL(response.getOutputStream(), wsdlName);
+ response.getOutputStream().flush();
+ return true;
+
+ } else {
+ // no schema available by that name - send 404
+ response.sendError(HttpStatus.SC_NOT_FOUND, "Schema Not Found!");
+ return true;
+ }
+
+ }
+
+ public String getHost(AxisHttpRequest request) throws java.net.SocketException {
+ String host = null;
+ Header hostHeader = request.getFirstHeader("host");
+ if (hostHeader != null) {
+ String parts[] = hostHeader.getValue().split("[:]");
+ if (parts.length > 0) {
+ host = parts[0].trim();
+ }
+ }
+ return host;
+ }
+
+}
Added: webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/HTTPWorkerFactory.java
URL: http://svn.apache.org/viewvc/webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/HTTPWorkerFactory.java?rev=671127&view=auto
==============================================================================
--- webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/HTTPWorkerFactory.java (added)
+++ webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/HTTPWorkerFactory.java Tue Jun 24 04:07:03 2008
@@ -0,0 +1,35 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.axis2.transport.http;
+
+import org.apache.axis2.transport.http.server.Worker;
+import org.apache.axis2.transport.http.server.WorkerFactory;
+
+public class HTTPWorkerFactory implements WorkerFactory {
+
+ public HTTPWorkerFactory() {
+ super();
+ }
+
+ public Worker newWorker() {
+ return new HTTPWorker();
+ }
+
+}
Added: webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/HttpTransportProperties.java
URL: http://svn.apache.org/viewvc/webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/HttpTransportProperties.java?rev=671127&view=auto
==============================================================================
--- webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/HttpTransportProperties.java (added)
+++ webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/HttpTransportProperties.java Tue Jun 24 04:07:03 2008
@@ -0,0 +1,249 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.axis2.transport.http;
+
+import org.apache.commons.httpclient.HttpVersion;
+import org.apache.commons.httpclient.auth.AuthPolicy;
+import org.apache.commons.httpclient.auth.AuthScope;
+
+import java.util.List;
+import java.util.Properties;
+
+/**
+ * Utility bean for setting transport properties in runtime.
+ */
+public class HttpTransportProperties {
+ protected boolean chunked;
+ protected HttpVersion httpVersion;
+ protected String protocol;
+
+ public HttpTransportProperties() {
+ }
+
+ public boolean getChunked() {
+ return chunked;
+ }
+
+ public HttpVersion getHttpVersion() {
+ return httpVersion;
+ }
+
+ public String getProtocol() {
+ return protocol;
+ }
+
+ public void setChunked(boolean chunked) {
+ this.chunked = chunked;
+ }
+
+ public void setHttpVersion(HttpVersion httpVerion) {
+ this.httpVersion = httpVerion;
+ }
+
+ public void setProtocol(String protocol) {
+ this.protocol = protocol;
+ }
+
+ public static class ProxyProperties {
+ protected int proxyPort = -1;
+ protected String domain = null;
+ protected String passWord = null;
+ protected String proxyHostName = null;
+ protected String userName = null;
+
+ public ProxyProperties() {
+ }
+
+ public String getDomain() {
+ return domain;
+ }
+
+ public String getPassWord() {
+ return passWord;
+ }
+
+ public String getProxyHostName() {
+ return proxyHostName;
+ }
+
+ public int getProxyPort() {
+ return proxyPort;
+ }
+
+ public String getUserName() {
+ return userName;
+ }
+
+ public void setDomain(String domain) {
+ this.domain = domain;
+ }
+
+ public void setPassWord(String passWord) {
+ this.passWord = passWord;
+ }
+
+ public void setProxyName(String proxyHostName) {
+ this.proxyHostName = proxyHostName;
+ }
+
+ public void setProxyPort(int proxyPort) {
+ this.proxyPort = proxyPort;
+ }
+
+ public void setUserName(String userName) {
+ this.userName = userName;
+ }
+ }
+
+ /*
+ This class is responsible for holding all the necessary information needed for NTML, Digest
+ and Basic Authentication. Authentication itself is handled by httpclient. User doesn't need to
+ warry about what authentication mechanism it uses. Axis2 uses httpclinet's default authentication
+ patterns.
+ */
+ public static class Authenticator {
+ /*host that needed to be authenticated with*/
+ private String host;
+ /*port of the host that needed to be authenticated with*/
+ private int port = AuthScope.ANY_PORT;
+ /*Realm for authentication scope*/
+ private String realm = AuthScope.ANY_REALM;
+ /*Domain needed by NTCredentials for NT Domain*/
+ private String domain;
+ /*User for authenticate*/
+ private String username;
+ /*Password of the user for authenticate*/
+ private String password;
+ /* Switch to use preemptive authentication or not*/
+ private boolean preemptive = false;
+ /* if Authentication scheme needs retry just turn on the following flag */
+ private boolean allowedRetry = false;
+ /* Changing the priorty or adding a custom AuthPolicy*/
+ private List authSchemes;
+
+ /* Default Auth Schems*/
+ public static final String NTLM = AuthPolicy.NTLM;
+ public static final String DIGEST = AuthPolicy.DIGEST;
+ public static final String BASIC = AuthPolicy.BASIC;
+
+ public String getHost() {
+ return host;
+ }
+
+ public void setHost(String host) {
+ this.host = host;
+ }
+
+ public int getPort() {
+ return port;
+ }
+
+ public void setPort(int port) {
+ this.port = port;
+ }
+
+ public String getRealm() {
+ return realm;
+ }
+
+ public void setRealm(String realm) {
+ this.realm = realm;
+ }
+
+ public String getUsername() {
+ return username;
+ }
+
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+ public void setPreemptiveAuthentication(boolean preemptive) {
+ this.preemptive = preemptive;
+ }
+
+ public boolean getPreemptiveAuthentication() {
+ return this.preemptive;
+ }
+
+ public String getDomain() {
+ return domain;
+ }
+
+ public void setDomain(String domain) {
+ this.domain = domain;
+ }
+
+ public void setAuthSchemes(List authSchemes) {
+ this.authSchemes = authSchemes;
+ }
+
+ public List getAuthSchemes() {
+ return this.authSchemes;
+ }
+
+ public void setAllowedRetry(boolean allowedRetry) {
+ this.allowedRetry = allowedRetry;
+ }
+
+ public boolean isAllowedRetry() {
+ return this.allowedRetry;
+ }
+ }
+
+ /**
+ * @deprecated org.apache.axis2.transport.http.HttpTransportProperties.MailProperties has been
+ * deprecated and user are encourage the use of java.util.Properties instead.
+ */
+ public static class MailProperties {
+ final Properties mailProperties = new Properties();
+
+ private String password;
+
+ public void addProperty(String key, String value) {
+ mailProperties.put(key, value);
+ }
+
+ public void deleteProperty(String key) {
+ mailProperties.remove(key);
+ }
+
+ public Properties getProperties() {
+ return mailProperties;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+ }
+}
Added: webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/ListingAgent.java
URL: http://svn.apache.org/viewvc/webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/ListingAgent.java?rev=671127&view=auto
==============================================================================
--- webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/ListingAgent.java (added)
+++ webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/ListingAgent.java Tue Jun 24 04:07:03 2008
@@ -0,0 +1,463 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+package org.apache.axis2.transport.http;
+
+import org.apache.axiom.attachments.utils.IOUtils;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.Constants;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.deployment.DeploymentConstants;
+import org.apache.axis2.description.AxisDescription;
+import org.apache.axis2.description.AxisService;
+import org.apache.axis2.description.PolicyInclude;
+import org.apache.axis2.description.TransportInDescription;
+import org.apache.axis2.util.ExternalPolicySerializer;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.neethi.Policy;
+import org.apache.neethi.PolicyRegistry;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.xml.stream.FactoryConfigurationError;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+
+public class ListingAgent extends AbstractAgent {
+
+ private static final Log log = LogFactory.getLog(ListingAgent.class);
+
+ private static final String LIST_MULTIPLE_SERVICE_JSP_NAME =
+ "listServices.jsp";
+ private static final String LIST_SINGLE_SERVICE_JSP_NAME =
+ "listSingleService.jsp";
+ private static final String LIST_FAULTY_SERVICES_JSP_NAME = "listFaultyService.jsp";
+
+ public static final String RUNNING_PORT = "RUNNING_PORT";
+
+ public ListingAgent(ConfigurationContext aConfigContext) {
+ super(aConfigContext);
+ }
+
+ private void addTransportListener(String schema, int port) {
+ try {
+ TransportInDescription trsIn =
+ configContext.getAxisConfiguration().getTransportIn(schema);
+ if (trsIn == null) {
+ trsIn = new TransportInDescription(schema);
+ CustomListener httspReceiver = new CustomListener(port, schema);
+ httspReceiver.init(configContext, trsIn);
+ trsIn.setReceiver(httspReceiver);
+ configContext.getListenerManager().addListener(trsIn, true);
+ }
+ } catch (AxisFault axisFault) {
+ //
+ }
+ }
+
+ public void handle(HttpServletRequest httpServletRequest,
+ HttpServletResponse httpServletResponse)
+ throws IOException, ServletException {
+
+ initTransportListener(httpServletRequest);
+
+ String query = httpServletRequest.getQueryString();
+ if (query != null) {
+ if (query.indexOf("wsdl2") > 0 || query.indexOf("wsdl") > 0 ||
+ query.indexOf("xsd") > 0 || query.indexOf("policy") > 0) {
+ processListService(httpServletRequest, httpServletResponse);
+ } else {
+ super.handle(httpServletRequest, httpServletResponse);
+ }
+ } else {
+ super.handle(httpServletRequest, httpServletResponse);
+ }
+ }
+
+ protected void initTransportListener(HttpServletRequest httpServletRequest) {
+ // httpServletRequest.getLocalPort() , giving me a build error so I had to use the followin
+ String filePart;
+ try {
+ filePart = httpServletRequest.getRequestURL().toString();
+ } catch (Throwable t){
+ log.info("Old Servlet API (fallback to HttpServletRequest.getRequestURI) :" + t);
+ filePart = httpServletRequest.getRequestURI();
+ }
+ int ipindex = filePart.indexOf("//");
+ String ip;
+ if (ipindex >= 0) {
+ ip = filePart.substring(ipindex + 2, filePart.length());
+ int seperatorIndex = ip.indexOf(":");
+ int slashIndex = ip.indexOf("/");
+ String portstr;
+ if (seperatorIndex >= 0) {
+ portstr = ip.substring(seperatorIndex + 1, slashIndex);
+ } else {
+ portstr = "80";
+ }
+ try {
+ addTransportListener(httpServletRequest.getScheme(), Integer.parseInt(portstr));
+ } catch (NumberFormatException e) {
+ log.debug(e.toString(), e);
+ }
+ }
+ }
+
+ protected void processListFaultyServices(HttpServletRequest req, HttpServletResponse res)
+ throws IOException, ServletException {
+ String serviceName = req.getParameter("serviceName");
+ if (serviceName != null) {
+ AxisService service = configContext.getAxisConfiguration().getService(serviceName);
+ try {
+ req.getSession().setAttribute(Constants.SINGLE_SERVICE, service);
+ } catch (Throwable t) {
+ log.info("Old Servlet API :" + t);
+ }
+ }
+ renderView(LIST_FAULTY_SERVICES_JSP_NAME, req, res);
+ }
+
+
+ protected void processIndex(HttpServletRequest httpServletRequest,
+ HttpServletResponse httpServletResponse)
+ throws IOException, ServletException {
+ processListServices(httpServletRequest, httpServletResponse);
+ }
+
+ private String extractHostAndPort(String filePart, boolean isHttp) {
+ int ipindex = filePart.indexOf("//");
+ String ip = null;
+ if (ipindex >= 0) {
+ ip = filePart.substring(ipindex + 2, filePart.length());
+ int seperatorIndex = ip.indexOf(":");
+ int slashIndex = ip.indexOf("/");
+ String port;
+ if (seperatorIndex >= 0) {
+ port = ip.substring(seperatorIndex + 1, slashIndex);
+ ip = ip.substring(0, seperatorIndex);
+ } else {
+ ip = ip.substring(0, slashIndex);
+ port = "80";
+ }
+ if (isHttp) {
+ configContext.setProperty(RUNNING_PORT, port);
+ }
+ }
+ return ip;
+ }
+
+ public void processExplicitSchemaAndWSDL(HttpServletRequest req,
+ HttpServletResponse res)
+ throws IOException, ServletException {
+ HashMap services = configContext.getAxisConfiguration().getServices();
+ String filePart = req.getRequestURL().toString();
+ String schema = filePart.substring(filePart.lastIndexOf("/") + 1,
+ filePart.length());
+ if ((services != null) && !services.isEmpty()) {
+ Iterator i = services.values().iterator();
+ while (i.hasNext()) {
+ AxisService service = (AxisService) i.next();
+ InputStream stream = service.getClassLoader().getResourceAsStream("META-INF/" + schema);
+ if (stream != null) {
+ OutputStream out = res.getOutputStream();
+ res.setContentType("text/xml");
+ copy(stream, out);
+ out.flush();
+ out.close();
+ return;
+ }
+ }
+ }
+ }
+
+ /**
+ * Copies the input stream to the output stream
+ *
+ * @param stream the <code>InputStream</code>
+ * @param ostream the <code>OutputStream</code>
+ */
+ public static void copy(InputStream stream, OutputStream ostream) throws IOException {
+ int nextValue = stream.read();
+ while (-1 != nextValue) {
+ ostream.write(nextValue);
+ nextValue = stream.read();
+ }
+ }
+
+ public String extractServiceName(String urlString) {
+ int n = urlString.indexOf(configContext.getServiceContextPath());
+ if (n != -1) {
+ String serviceName = urlString.substring(n + configContext.getServiceContextPath().length(),
+ urlString.length());
+ if (serviceName.length() > 0) {
+ if(serviceName.charAt(0)=='/'){
+ serviceName = serviceName.substring(1);
+ }
+ return serviceName;
+ }
+ }
+ return urlString.substring(urlString.lastIndexOf("/") + 1,
+ urlString.length());
+ }
+
+ public void processListService(HttpServletRequest req,
+ HttpServletResponse res)
+ throws IOException, ServletException {
+
+ String url;
+ try {
+ url = req.getRequestURL().toString();
+ } catch (Throwable t) {
+ log.info("Old Servlet API (Fallback to HttpServletRequest.getRequestURI) :" + t);
+ url = req.getRequestURI();
+ }
+ String serviceName = extractServiceName(url);
+ HashMap services = configContext.getAxisConfiguration().getServices();
+ String query = req.getQueryString();
+ int wsdl2 = query.indexOf("wsdl2");
+ int wsdl = query.indexOf("wsdl");
+ int xsd = query.indexOf("xsd");
+ int policy = query.indexOf("policy");
+
+ if ((services != null) && !services.isEmpty()) {
+ Object serviceObj = services.get(serviceName);
+ if (serviceObj != null) {
+ boolean isHttp = "http".equals(req.getScheme());
+ if (wsdl2 >= 0) {
+ res.setContentType("text/xml");
+ String ip = extractHostAndPort(url, isHttp);
+ String wsdlName = req.getParameter("wsdl2");
+ if (wsdlName != null && wsdlName.length()>0) {
+ InputStream in = ((AxisService) serviceObj).getClassLoader()
+ .getResourceAsStream(DeploymentConstants.META_INF + "/" + wsdlName);
+ if (in != null) {
+ OutputStream out = res.getOutputStream();
+ out.write(IOUtils.getStreamAsByteArray(in));
+ out.flush();
+ out.close();
+ } else {
+ res.sendError(HttpServletResponse.SC_NOT_FOUND);
+ }
+ } else {
+ OutputStream out = res.getOutputStream();
+ ((AxisService) serviceObj)
+ .printWSDL2(out, ip);
+ out.flush();
+ out.close();
+ }
+ return;
+ } else if (wsdl >= 0) {
+ OutputStream out = res.getOutputStream();
+ res.setContentType("text/xml");
+ String ip = extractHostAndPort(url, isHttp);
+ String wsdlName = req.getParameter("wsdl");
+
+ if (wsdlName != null && wsdlName.length()>0) {
+ AxisService axisServce = (AxisService) serviceObj;
+ axisServce.printUserWSDL(out, wsdlName);
+ out.flush();
+ out.close();
+ } else {
+ ((AxisService) serviceObj).printWSDL(out, ip);
+ out.flush();
+ out.close();
+ }
+ return;
+ } else if (xsd >= 0) {
+ res.setContentType("text/xml");
+ int ret = ((AxisService) serviceObj).printXSD(res.getOutputStream(), req.getParameter("xsd"));
+ if (ret == 0) {
+ //multiple schemas are present and the user specified
+ //no name - in this case we cannot possibly pump a schema
+ //so redirect to the service root
+ res.sendRedirect("");
+ } else if (ret == -1) {
+ res.sendError(HttpServletResponse.SC_NOT_FOUND);
+ }
+ return;
+ } else if (policy >= 0) {
+
+ ExternalPolicySerializer serializer = new ExternalPolicySerializer();
+ serializer.setAssertionsToFilter(configContext
+ .getAxisConfiguration().getLocalPolicyAssertions());
+
+ // check whether Id is set
+ String idParam = req.getParameter("id");
+
+ if (idParam != null) {
+ // Id is set
+
+ Policy targetPolicy = findPolicy(idParam, (AxisService) serviceObj);
+
+ if (targetPolicy != null) {
+ XMLStreamWriter writer;
+
+ try {
+ OutputStream out = res.getOutputStream();
+ writer = XMLOutputFactory.newInstance()
+ .createXMLStreamWriter(out);
+
+ res.setContentType("application/wspolicy+xml");
+ targetPolicy.serialize(writer);
+ writer.flush();
+
+ } catch (XMLStreamException e) {
+ throw new ServletException(
+ "Error occured when serializing the Policy",
+ e);
+
+ } catch (FactoryConfigurationError e) {
+ throw new ServletException(
+ "Error occured when serializing the Policy",
+ e);
+ }
+
+ } else {
+
+ OutputStream out = res.getOutputStream();
+ res.setContentType("text/html");
+ String outStr = "<b>No policy found for id="
+ + idParam + "</b>";
+ out.write(outStr.getBytes());
+ }
+
+ } else {
+
+ PolicyInclude policyInclude = ((AxisService) serviceObj).getPolicyInclude();
+ Policy effecPolicy = policyInclude.getEffectivePolicy();
+
+ if (effecPolicy != null) {
+ XMLStreamWriter writer;
+
+ try {
+ OutputStream out = res.getOutputStream();
+ writer = XMLOutputFactory.newInstance()
+ .createXMLStreamWriter(out);
+
+ res.setContentType("application/wspolicy+xml");
+ effecPolicy.serialize(writer);
+ writer.flush();
+
+ } catch (XMLStreamException e) {
+ throw new ServletException(
+ "Error occured when serializing the Policy",
+ e);
+
+ } catch (FactoryConfigurationError e) {
+ throw new ServletException(
+ "Error occured when serializing the Policy",
+ e);
+ }
+ } else {
+
+ OutputStream out = res.getOutputStream();
+ res.setContentType("text/html");
+ String outStr = "<b>No effective policy for "
+ + serviceName + " servcie</b>";
+ out.write(outStr.getBytes());
+ }
+ }
+
+ return;
+ } else {
+ try {
+ req.getSession().setAttribute(Constants.SINGLE_SERVICE,
+ serviceObj);
+ } catch (Throwable t) {
+ log.info("Old Servlet API :" + t);
+ }
+ }
+ } else {
+ try {
+ req.getSession().setAttribute(Constants.SINGLE_SERVICE, null);
+ } catch (Throwable t){
+ log.info("Old Servlet API :" + t);
+ }
+
+ res.sendError(HttpServletResponse.SC_NOT_FOUND, url);
+ }
+ }
+
+ renderView(LIST_SINGLE_SERVICE_JSP_NAME, req, res);
+ }
+
+ protected void processListServices(HttpServletRequest req,
+ HttpServletResponse res)
+ throws IOException, ServletException {
+
+ populateSessionInformation(req);
+ try {
+ req.getSession().setAttribute(Constants.ERROR_SERVICE_MAP,
+ configContext.getAxisConfiguration().getFaultyServices());
+ } catch (Throwable t){
+ log.info("Old Servlet API :" + t);
+ }
+ renderView(LIST_MULTIPLE_SERVICE_JSP_NAME, req, res);
+ }
+
+ private Policy findPolicy(String id, AxisDescription des) {
+
+ List policyElements = des.getPolicyInclude().getPolicyElements();
+ PolicyRegistry registry = des.getPolicyInclude().getPolicyRegistry();
+
+ Object policyComponent;
+
+ Policy policy = registry.lookup(id);
+
+ if (policy != null) {
+ return policy;
+ }
+
+ for (Iterator iterator = policyElements.iterator(); iterator.hasNext();) {
+ policyComponent = iterator.next();
+
+ if (policyComponent instanceof Policy) {
+ // policy found for the id
+
+ if (id.equals(((Policy) policyComponent).getId())) {
+ return (Policy) policyComponent;
+ }
+ }
+ }
+
+ AxisDescription child;
+
+ for (Iterator iterator = des.getChildren(); iterator.hasNext();) {
+ child = (AxisDescription) iterator.next();
+ policy = findPolicy(id, child);
+
+ if (policy != null) {
+ return policy;
+ }
+ }
+
+ return null;
+ }
+
+}
Added: webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/ProxyConfiguration.java
URL: http://svn.apache.org/viewvc/webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/ProxyConfiguration.java?rev=671127&view=auto
==============================================================================
--- webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/ProxyConfiguration.java (added)
+++ webservices/axis2/trunk/java/modules/transports/src/org/apache/axis2/transport/http/ProxyConfiguration.java Tue Jun 24 04:07:03 2008
@@ -0,0 +1,521 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.axis2.transport.http;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.description.Parameter;
+import org.apache.commons.httpclient.Credentials;
+import org.apache.commons.httpclient.HostConfiguration;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.NTCredentials;
+import org.apache.commons.httpclient.UsernamePasswordCredentials;
+import org.apache.commons.httpclient.auth.AuthScope;
+
+import javax.xml.namespace.QName;
+import java.net.URL;
+import java.util.StringTokenizer;
+
+
+/**
+ * The purpose of this class is to configure the proxy auth regardles of the protocol.
+ * Proxy will be set only for HTTP connection
+ */
+
+public class ProxyConfiguration {
+
+ protected String proxyHost;
+ protected String nonProxyHosts;
+ protected int proxyPort = -1; //If port is not set, default is set to -1
+ protected String proxyUser;
+ protected String proxyPassword;
+
+ protected static final String HTTP_PROXY_HOST = "http.proxyHost";
+ protected static final String HTTP_PROXY_PORT = "http.proxyPort";
+ protected static final String HTTP_NON_PROXY_HOSTS = "http.nonProxyHosts";
+
+ protected static final String ATTR_PROXY = "Proxy";
+ protected static final String PROXY_HOST_ELEMENT = "ProxyHost";
+ protected static final String PROXY_PORT_ELEMENT = "ProxyPort";
+ protected static final String PROXY_USER_ELEMENT = "ProxyUser";
+ protected static final String PROXY_PASSWORD_ELEMENT = "ProxyPassword";
+
+ public void configure(MessageContext messageContext,
+ HttpClient httpClient,
+ HostConfiguration config) throws AxisFault {
+
+ // <parameter name="Proxy">
+ // <Configuration>
+ // <ProxyHost>example.org</ProxyHost>
+ // <ProxyPort>5678</ProxyPort>
+ // <ProxyUser>EXAMPLE\saminda</ProxyUser>
+ // <ProxyPassword>ppp</ProxyPassword>
+ // </Configuration>
+ // </parameter>
+ Credentials proxyCred = null;
+
+ //Getting configuration values from Axis2.xml
+ Parameter param = messageContext.getConfigurationContext().getAxisConfiguration()
+ .getParameter(ATTR_PROXY);
+
+ if (param != null) {
+ OMElement configurationEle = param.getParameterElement().getFirstElement();
+ if (configurationEle == null) {
+ throw new AxisFault(
+ ProxyConfiguration.class.getName() + " Configuration element is missing");
+ }
+
+ OMElement proxyHostEle =
+ configurationEle.getFirstChildWithName(new QName(PROXY_HOST_ELEMENT));
+ OMElement proxyPortEle =
+ configurationEle.getFirstChildWithName(new QName(PROXY_PORT_ELEMENT));
+ OMElement proxyUserEle =
+ configurationEle.getFirstChildWithName(new QName(PROXY_USER_ELEMENT));
+ OMElement proxyPasswordEle =
+ configurationEle.getFirstChildWithName(new QName(PROXY_PASSWORD_ELEMENT));
+
+ if (proxyHostEle == null) {
+ throw new AxisFault(
+ ProxyConfiguration.class.getName() + " ProxyHost element is missing");
+ }
+ String text = proxyHostEle.getText();
+ if (text == null) {
+ throw new AxisFault(
+ ProxyConfiguration.class.getName() + " ProxyHost's value is missing");
+ }
+
+ this.setProxyHost(text);
+
+ if (proxyPortEle != null) {
+ this.setProxyPort(Integer.parseInt(proxyPortEle.getText()));
+ }
+
+ if (proxyUserEle != null) {
+ this.setProxyUser(proxyUserEle.getText());
+ }
+
+ if (proxyPasswordEle != null) {
+ this.setProxyPassword(proxyPasswordEle.getText());
+ }
+
+ if (this.getProxyUser() == null && this.getProxyUser() == null) {
+ proxyCred = new UsernamePasswordCredentials("", "");
+ } else {
+ proxyCred =
+ new UsernamePasswordCredentials(this.getProxyUser(),
+ this.getProxyPassword());
+ }
+
+ // if the username is in the form "DOMAIN\\user"
+ // then use NTCredentials instead.
+ if (this.getProxyUser() != null) {
+ int domainIndex = this.getProxyUser().indexOf("\\");
+ if (domainIndex > 0) {
+ String domain = this.getProxyUser().substring(0, domainIndex);
+ if (this.getProxyUser().length() > domainIndex + 1) {
+ String user = this.getProxyUser().substring(domainIndex + 1);
+ proxyCred = new NTCredentials(user,
+ this.getProxyPassword(),
+ this.getProxyHost(),
+ domain);
+ }
+ }
+ }
+ }
+
+ // Overide the property setting in runtime.
+ HttpTransportProperties.ProxyProperties proxyProperties =
+ (HttpTransportProperties.ProxyProperties) messageContext
+ .getProperty(HTTPConstants.PROXY);
+
+ if (proxyProperties != null) {
+ String host = proxyProperties.getProxyHostName();
+ if (host == null || host.length() == 0) {
+ throw new AxisFault(ProxyConfiguration.class.getName() +
+ " Proxy host is not available. Host is a MUST parameter");
+
+ } else {
+ this.setProxyHost(host);
+ }
+
+
+ this.setProxyPort(proxyProperties.getProxyPort());
+
+ //Setting credentials
+
+ String userName = proxyProperties.getUserName();
+ String password = proxyProperties.getPassWord();
+ String domain = proxyProperties.getDomain();
+
+ if (userName == null && password == null) {
+ proxyCred = new UsernamePasswordCredentials("", "");
+ } else {
+ proxyCred = new UsernamePasswordCredentials(userName, password);
+ }
+
+ if (userName != null && password != null && domain != null) {
+ proxyCred = new NTCredentials(userName, password, host, domain);
+ }
+
+ }
+
+ //Using Java Networking Properties
+
+ String host = System.getProperty(HTTP_PROXY_HOST);
+ if (host != null) {
+ this.setProxyHost(host);
+ proxyCred = new UsernamePasswordCredentials("","");
+ }
+
+ String port = System.getProperty(HTTP_PROXY_PORT);
+
+ if (port != null) {
+ this.setProxyPort(Integer.parseInt(port));
+ }
+
+ if (proxyCred == null) {
+ throw new AxisFault(ProxyConfiguration.class.getName() +
+ " Minimum proxy credentials are not set");
+ }
+ httpClient.getState().setProxyCredentials(AuthScope.ANY, proxyCred);
+ config.setProxy(this.getProxyHost(), this.getProxyPort());
+ }
+
+ /**
+ * Check first if the proxy is configured or active.
+ * If yes this will return true. This is not a deep check
+ *
+ * @param messageContext
+ * @return boolean
+ */
+
+ public static boolean isProxyEnabled(MessageContext messageContext, URL targetURL)
+ throws AxisFault {
+
+ boolean state = false;
+
+
+ Parameter param = messageContext.getConfigurationContext().getAxisConfiguration()
+ .getParameter(ATTR_PROXY);
+
+ //If configuration is over ridden
+ Object obj = messageContext.getProperty(HTTPConstants.PROXY);
+
+ //From Java Networking Properties
+ String sp = System.getProperty(HTTP_PROXY_HOST);
+
+ if (param != null || obj != null || sp != null) {
+ state = true;
+ }
+
+ boolean isNonProxyHost = validateNonProxyHosts(targetURL.getHost());
+
+ return state && !isNonProxyHost;
+
+ }
+
+ /**
+ * Validates for names that shouldn't be listered as proxies.
+ * The http.nonProxyHosts can be set to specify the hosts which should be
+ * connected to directly (not through the proxy server).
+ * The value of the http.nonProxyHosts property can be a list of hosts,
+ * each separated by a |; it can also take a regular expression for matches;
+ * for example: *.sfbay.sun.com would match any fully qualified hostname in the sfbay domain.
+ *
+ * For more information refer to : http://java.sun.com/features/2002/11/hilevel_network.html
+ *
+ * false : validation fail : User can use the proxy
+ * true : validation pass ; User can't use the proxy
+ *
+ * @return boolean
+ */
+ public static boolean validateNonProxyHosts(String host) {
+ //From system property http.nonProxyHosts
+ String nonProxyHosts = System.getProperty(HTTP_NON_PROXY_HOSTS);
+ return isHostInNonProxyList(host, nonProxyHosts);
+ }
+
+ /**
+ * Check if the specified host is in the list of non proxy hosts.
+ *
+ * @param host host name
+ * @param nonProxyHosts string containing the list of non proxy hosts
+ *
+ * @return true/false
+ */
+ public static boolean isHostInNonProxyList(String host, String nonProxyHosts) {
+ if ((nonProxyHosts == null) || (host == null)) {
+ return false;
+ }
+
+ /*
+ * The http.nonProxyHosts system property is a list enclosed in
+ * double quotes with items separated by a vertical bar.
+ */
+ StringTokenizer tokenizer = new StringTokenizer(nonProxyHosts, "|\"");
+
+ while (tokenizer.hasMoreTokens()) {
+ String pattern = tokenizer.nextToken();
+ if (match(pattern, host, false)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Matches a string against a pattern. The pattern contains two special
+ * characters:
+ * '*' which means zero or more characters,
+ *
+ * @param pattern the (non-null) pattern to match against
+ * @param str the (non-null) string that must be matched against the
+ * pattern
+ * @param isCaseSensitive
+ *
+ * @return <code>true</code> when the string matches against the pattern,
+ * <code>false</code> otherwise.
+ */
+ protected static boolean match(String pattern, String str,
+ boolean isCaseSensitive) {
+
+ char[] patArr = pattern.toCharArray();
+ char[] strArr = str.toCharArray();
+ int patIdxStart = 0;
+ int patIdxEnd = patArr.length - 1;
+ int strIdxStart = 0;
+ int strIdxEnd = strArr.length - 1;
+ char ch;
+ boolean containsStar = false;
+
+ for (int i = 0; i < patArr.length; i++) {
+ if (patArr[i] == '*') {
+ containsStar = true;
+ break;
+ }
+ }
+ if (!containsStar) {
+
+ // No '*'s, so we make a shortcut
+ if (patIdxEnd != strIdxEnd) {
+ return false; // Pattern and string do not have the same size
+ }
+ for (int i = 0; i <= patIdxEnd; i++) {
+ ch = patArr[i];
+ if (isCaseSensitive && (ch != strArr[i])) {
+ return false; // Character mismatch
+ }
+ if (!isCaseSensitive
+ && (Character.toUpperCase(ch)
+ != Character.toUpperCase(strArr[i]))) {
+ return false; // Character mismatch
+ }
+ }
+ return true; // String matches against pattern
+ }
+ if (patIdxEnd == 0) {
+ return true; // Pattern contains only '*', which matches anything
+ }
+
+ // Process characters before first star
+ while ((ch = patArr[patIdxStart]) != '*'
+ && (strIdxStart <= strIdxEnd)) {
+ if (isCaseSensitive && (ch != strArr[strIdxStart])) {
+ return false; // Character mismatch
+ }
+ if (!isCaseSensitive
+ && (Character.toUpperCase(ch)
+ != Character.toUpperCase(strArr[strIdxStart]))) {
+ return false; // Character mismatch
+ }
+ patIdxStart++;
+ strIdxStart++;
+ }
+ if (strIdxStart > strIdxEnd) {
+
+ // All characters in the string are used. Check if only '*'s are
+ // left in the pattern. If so, we succeeded. Otherwise failure.
+ for (int i = patIdxStart; i <= patIdxEnd; i++) {
+ if (patArr[i] != '*') {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ // Process characters after last star
+ while ((ch = patArr[patIdxEnd]) != '*' && (strIdxStart <= strIdxEnd)) {
+ if (isCaseSensitive && (ch != strArr[strIdxEnd])) {
+ return false; // Character mismatch
+ }
+ if (!isCaseSensitive
+ && (Character.toUpperCase(ch)
+ != Character.toUpperCase(strArr[strIdxEnd]))) {
+ return false; // Character mismatch
+ }
+ patIdxEnd--;
+ strIdxEnd--;
+ }
+ if (strIdxStart > strIdxEnd) {
+
+ // All characters in the string are used. Check if only '*'s are
+ // left in the pattern. If so, we succeeded. Otherwise failure.
+ for (int i = patIdxStart; i <= patIdxEnd; i++) {
+ if (patArr[i] != '*') {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ // process pattern between stars. padIdxStart and patIdxEnd point
+ // always to a '*'.
+ while ((patIdxStart != patIdxEnd) && (strIdxStart <= strIdxEnd)) {
+ int patIdxTmp = -1;
+
+ for (int i = patIdxStart + 1; i <= patIdxEnd; i++) {
+ if (patArr[i] == '*') {
+ patIdxTmp = i;
+ break;
+ }
+ }
+ if (patIdxTmp == patIdxStart + 1) {
+
+ // Two stars next to each other, skip the first one.
+ patIdxStart++;
+ continue;
+ }
+
+ // Find the pattern between padIdxStart & padIdxTmp in str between
+ // strIdxStart & strIdxEnd
+ int patLength = (patIdxTmp - patIdxStart - 1);
+ int strLength = (strIdxEnd - strIdxStart + 1);
+ int foundIdx = -1;
+
+ strLoop:
+ for (int i = 0; i <= strLength - patLength; i++) {
+ for (int j = 0; j < patLength; j++) {
+ ch = patArr[patIdxStart + j + 1];
+ if (isCaseSensitive
+ && (ch != strArr[strIdxStart + i + j])) {
+ continue strLoop;
+ }
+ if (!isCaseSensitive && (Character
+ .toUpperCase(ch) != Character
+ .toUpperCase(strArr[strIdxStart + i + j]))) {
+ continue strLoop;
+ }
+ }
+ foundIdx = strIdxStart + i;
+ break;
+ }
+ if (foundIdx == -1) {
+ return false;
+ }
+ patIdxStart = patIdxTmp;
+ strIdxStart = foundIdx + patLength;
+ }
+
+ // All characters in the string are used. Check if only '*'s are left
+ // in the pattern. If so, we succeeded. Otherwise failure.
+ for (int i = patIdxStart; i <= patIdxEnd; i++) {
+ if (patArr[i] != '*') {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Retrun proxy host
+ *
+ * @return String
+ */
+ public String getProxyHost() {
+ return proxyHost;
+ }
+
+ /**
+ * set proxy host
+ *
+ * @param proxyHost
+ */
+
+ public void setProxyHost(String proxyHost) {
+ this.proxyHost = proxyHost;
+ }
+
+ /**
+ * retrun proxy port
+ *
+ * @return String
+ */
+ public int getProxyPort() {
+ return proxyPort;
+ }
+
+ /**
+ * set proxy port
+ *
+ * @param proxyPort
+ */
+ public void setProxyPort(int proxyPort) {
+ this.proxyPort = proxyPort;
+ }
+
+ /**
+ * return proxy user. Proxy user can be user/domain or user
+ *
+ * @return String
+ */
+ public String getProxyUser() {
+ return proxyUser;
+ }
+
+ /**
+ * get proxy user
+ *
+ * @param proxyUser
+ */
+ public void setProxyUser(String proxyUser) {
+ this.proxyUser = proxyUser;
+ }
+
+ /**
+ * set password
+ *
+ * @return String
+ */
+ public String getProxyPassword() {
+ return proxyPassword;
+ }
+
+ /**
+ * get password
+ *
+ * @param proxyPassword
+ */
+ public void setProxyPassword(String proxyPassword) {
+ this.proxyPassword = proxyPassword;
+ }
+
+
+}