Some Eclipse Foundation services are deprecated, or will be soon. Please ensure you've read this important communication.
View | Details | Raw Unified | Return to bug 176493 | Differences between
and this patch

Collapse All | Expand All

(-)wsexplorer/wsdl/soap_envelope_xml.jsp (-7 / +13 lines)
Lines 1-28 Link Here
1
<%
1
<%
2
/*******************************************************************************
2
/*******************************************************************************
3
 * Copyright (c) 2001, 2004 IBM Corporation and others.
3
 * Copyright (c) 2001, 2007 IBM Corporation and others.
4
 * All rights reserved. This program and the accompanying materials
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
8
 * 
9
 * Contributors:
9
 * Contributors:
10
 *     IBM Corporation - initial API and implementation
10
 * IBM Corporation - initial API and implementation
11
 * yyyymmdd bug      Email and other contact information
12
 * -------- -------- -----------------------------------------------------------
13
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
11
 *******************************************************************************/
14
 *******************************************************************************/
12
%><%@ page contentType="text/xml; charset=UTF-8" import="org.eclipse.wst.ws.internal.explorer.platform.wsdl.perspective.*,
15
%><%@ page contentType="text/xml; charset=UTF-8" import="org.eclipse.wst.ws.internal.explorer.platform.wsdl.perspective.*,
13
                                                       org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.*" %><jsp:useBean id="controller" class="org.eclipse.wst.ws.internal.explorer.platform.perspective.Controller" scope="session"/><%
16
                                                         org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.*,
17
                                                         org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.WSDLOperationElement,
18
                                                         org.eclipse.wst.ws.internal.explorer.transport.*" %><jsp:useBean id="controller" class="org.eclipse.wst.ws.internal.explorer.platform.perspective.Controller" scope="session"/><%
14
int soapEnvelopeType = Integer.parseInt(request.getParameter(WSDLActionInputs.SOAP_ENVELOPE_TYPE));
19
int soapEnvelopeType = Integer.parseInt(request.getParameter(WSDLActionInputs.SOAP_ENVELOPE_TYPE));
15
WSDLPerspective wsdlPerspective = controller.getWSDLPerspective();
20
WSDLPerspective wsdlPerspective = controller.getWSDLPerspective();
16
SOAPMessageQueue soapMessageQueue;
21
WSDLOperationElement operElement = (WSDLOperationElement) wsdlPerspective.getOperationNode().getTreeElement();
22
ISOAPMessage soapMessage;
17
switch (soapEnvelopeType)
23
switch (soapEnvelopeType)
18
{
24
{
19
  case WSDLActionInputs.SOAP_ENVELOPE_TYPE_REQUEST:
25
  case WSDLActionInputs.SOAP_ENVELOPE_TYPE_REQUEST:
20
    soapMessageQueue = wsdlPerspective.getSOAPRequestQueue();
26
    soapMessage = (ISOAPMessage) operElement.getPropertyAsObject(WSDLModelConstants.PROP_SOAP_REQUEST);
21
    break;
27
    break;
22
  case WSDLActionInputs.SOAP_ENVELOPE_TYPE_RESPONSE:
28
  case WSDLActionInputs.SOAP_ENVELOPE_TYPE_RESPONSE:
23
  default:
29
  default:
24
    soapMessageQueue = wsdlPerspective.getSOAPResponseQueue();
30
    soapMessage = (ISOAPMessage) operElement.getPropertyAsObject(WSDLModelConstants.PROP_SOAP_RESPONSE);
25
    break;
31
    break;
26
}
32
}
27
String messages = soapMessageQueue.getMessagesFromList();
33
String messages = soapMessage.toXML();
28
%><%=messages%>
34
%><%=messages%>
(-)wsexplorer-src/org/eclipse/wst/ws/internal/explorer/platform/util/XMLUtils.java (-145 lines)
Removed Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2004, 2005 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.wst.ws.internal.explorer.platform.util;
12
13
import java.io.ByteArrayInputStream;
14
import java.io.ByteArrayOutputStream;
15
import java.io.IOException;
16
import java.io.UnsupportedEncodingException;
17
import javax.xml.parsers.DocumentBuilder;
18
import javax.xml.parsers.DocumentBuilderFactory;
19
import javax.xml.parsers.ParserConfigurationException;
20
import javax.xml.transform.OutputKeys;
21
import javax.xml.transform.Transformer;
22
import javax.xml.transform.TransformerFactory;
23
import javax.xml.transform.dom.DOMSource;
24
import javax.xml.transform.stream.StreamResult;
25
import org.w3c.dom.Document;
26
import org.w3c.dom.DocumentFragment;
27
import org.w3c.dom.Element;
28
import org.xml.sax.SAXException;
29
30
public final class XMLUtils
31
{
32
  /**
33
   * Serialize an XML Element into a String.
34
   * @param e Element to be serialized.
35
   * @param omitXMLDeclaration boolean representing whether or not to omit the XML declaration.
36
   * @return String representation of the XML document fragment.
37
   */
38
  public static final String serialize(Element e,boolean omitXMLDeclaration)
39
  {
40
    if (e != null)
41
    {
42
      try
43
      {
44
		DOMSource domSource = new DOMSource(e);
45
		Transformer serializer = TransformerFactory.newInstance().newTransformer();
46
		serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, ((omitXMLDeclaration) ? "yes" : "no"));
47
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
48
		serializer.setOutputProperty(OutputKeys.ENCODING, HTMLUtils.UTF8_ENCODING);
49
		serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
50
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
51
		serializer.transform(domSource, new	StreamResult(baos));
52
		baos.close();
53
		return new String(baos.toByteArray(), HTMLUtils.UTF8_ENCODING);
54
      }
55
      catch (Throwable t)
56
      {
57
      }
58
    }
59
    return null;
60
  }
61
    
62
  /**
63
   * Serialize an XML Element into a String.
64
   * @param df DocumentFragment to be serialized.
65
   * @param omitXMLDeclaration boolean representing whether or not to omit the XML declaration.
66
   * @return String representation of the XML document fragment.
67
   */  
68
  public static final String serialize(DocumentFragment df,boolean omitXMLDeclaration)
69
  {
70
    if (df != null)
71
    {
72
      try
73
      {
74
		DOMSource domSource = new DOMSource(df);
75
		Transformer serializer = TransformerFactory.newInstance().newTransformer();
76
		serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, ((omitXMLDeclaration) ? "yes" : "no"));
77
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
78
		serializer.setOutputProperty(OutputKeys.ENCODING, HTMLUtils.UTF8_ENCODING);
79
		serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
80
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
81
		serializer.transform(domSource, new	StreamResult(baos));
82
		baos.close();
83
		return new String(baos.toByteArray(), HTMLUtils.UTF8_ENCODING);
84
      }
85
      catch (Throwable t)
86
      {
87
      }
88
    }
89
    return null;
90
  }
91
  
92
  /**
93
   * Create a new XML Document.
94
   * @param docBuilder DocumentBuilder. Setting this to null will create a new DocumentBuilder.
95
   * @return Document
96
   */
97
  public static final Document createNewDocument(DocumentBuilder docBuilder) throws ParserConfigurationException
98
  {
99
    if (docBuilder == null)
100
    {
101
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
102
      factory.setNamespaceAware(false);
103
      factory.setValidating(false);
104
      docBuilder = factory.newDocumentBuilder();
105
    }
106
    Document doc = docBuilder.newDocument();
107
    return doc;
108
  }
109
110
  /**
111
   * Convert the String representation of an Element into an Element
112
   * @param String representation of an Element.
113
   * @return Element
114
   */
115
  public static Element stringToElement(String s) throws ParserConfigurationException, SAXException, UnsupportedEncodingException, IOException {
116
    return stringToElement(s, false);
117
  }
118
119
  /**
120
   * Convert the String representation of an Element into an Element
121
   * @param String representation of an Element.
122
   * @param boolean set whether the return Element should be namespace aware.
123
   * @return Element
124
   */
125
  public static Element stringToElement(String s, boolean namespaceAware) throws ParserConfigurationException, SAXException, UnsupportedEncodingException, IOException
126
  {
127
    return byteArrayToElement(s.getBytes(HTMLUtils.UTF8_ENCODING), namespaceAware);
128
  }
129
130
  /**
131
   * Convert the byte array representation of an Element into an Element
132
   * @param byte[] representation of an Element.
133
   * @param boolean set whether the return Element should be namespace aware.
134
   * @return Element
135
   */
136
  public static Element byteArrayToElement(byte[] b, boolean namespaceAware) throws ParserConfigurationException, SAXException, UnsupportedEncodingException, IOException
137
  {
138
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
139
    docBuilderFactory.setNamespaceAware(namespaceAware);
140
    docBuilderFactory.setValidating(false);
141
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
142
    Document doc = docBuilder.parse(new ByteArrayInputStream(b));
143
    return doc.getDocumentElement();
144
  }
145
}
(-)wsexplorer-src/org/eclipse/wst/ws/internal/explorer/platform/util/URLUtils.java (-101 lines)
Removed Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2005 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * 
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.wst.ws.internal.explorer.platform.util;
12
13
import java.io.UnsupportedEncodingException;
14
import java.net.URLDecoder;
15
import java.net.URLEncoder;
16
17
/**
18
 * This class contains utility methods for managing URLs
19
 * as used by the Web Services Explorer Web application.
20
 * @author cbrealey@ca.ibm.com
21
 */
22
public final class URLUtils
23
{
24
	/**
25
	 * Objects of this class should not be constructed.
26
	 */
27
	private URLUtils ()
28
	{
29
	}
30
31
	/**
32
	 * UTF-8
33
	 */
34
	public static final String UTF8 = "UTF-8";
35
36
	/**
37
	 * Equivalent to {@link #encode(String,String)}
38
	 * with second parameter set to the "UTF-8" encoding.
39
	 * @param s The string to encode.
40
	 * @return The encoded string.
41
	 */
42
	public static String encode(String s)
43
	{
44
		return encode(s,UTF8);
45
	}
46
	
47
	/**
48
	 * Equivalent to {@link URLEncoder#encode(String,String)},
49
	 * only throws an unchecked {@link RuntimeException} wrapped
50
	 * around an {@link UnsupportedEncodingException} instead of
51
	 * an {@link UnsupportedEncodingException}.
52
	 * @param s The string to encode.
53
	 * @param enc The encoding to use.
54
	 * @return The encoded string.
55
	 */
56
	public static String encode(String s, String enc)
57
	{
58
		try
59
		{
60
			return URLEncoder.encode(s,enc);
61
		}
62
		catch (UnsupportedEncodingException e)
63
		{
64
			// TODO: MSG_BROKEN_VM_DOES_NOT_SUPPORT_UTF-8
65
			throw new RuntimeException("%MSG_BROKEN_VM_DOES_NOT_SUPPORT_UTF-8",e);
66
		}
67
	}
68
	
69
	/**
70
	 * Equivalent to {@link #decode(String,String)}
71
	 * with second parameter set to the "UTF-8" encoding.
72
	 * @param s The string to decode.
73
	 * @return The decoded string.
74
	 */
75
	public static String decode(String s)
76
	{
77
		return decode(s,UTF8);
78
	}
79
	
80
	/**
81
	 * Equivalent to {@link URLEncoder#decode(String,String)},
82
	 * only throws an unchecked {@link RuntimeException} wrapped
83
	 * around an {@link UnsupportedEncodingException} instead of
84
	 * an {@link UnsupportedEncodingException}.
85
	 * @param s The string to decode.
86
	 * @param enc The encoding to use.
87
	 * @return The decoded string.
88
	 */
89
	public static String decode(String s, String enc)
90
	{
91
		try
92
		{
93
			return URLDecoder.decode(s,enc);
94
		}
95
		catch (UnsupportedEncodingException e)
96
		{
97
			// TODO: MSG_BROKEN_VM_DOES_NOT_SUPPORT_UTF-8
98
			throw new RuntimeException("%MSG_BROKEN_VM_DOES_NOT_SUPPORT_UTF-8",e);
99
		}
100
	}
101
}
(-)wsexplorer-src/org/eclipse/wst/ws/internal/explorer/platform/wsdl/actions/InvokeWSDLSOAPOperationSourceAction.java (-69 / +25 lines)
Lines 10-45 Link Here
10
 * yyyymmdd bug      Email and other contact information
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070305   117034 makandre@ca.ibm.com - Andrew Mak, Web Services Explorer should support SOAP Headers
12
 * 20070305   117034 makandre@ca.ibm.com - Andrew Mak, Web Services Explorer should support SOAP Headers
13
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
13
 *******************************************************************************/
14
 *******************************************************************************/
14
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.actions;
15
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.actions;
15
16
16
import java.io.OutputStream;
17
import java.io.OutputStream;
17
import java.io.PrintWriter;
18
import java.io.PrintWriter;
18
import java.util.Hashtable;
19
import java.util.Hashtable;
19
import java.util.Vector;
20
20
import javax.xml.parsers.ParserConfigurationException;
21
import org.eclipse.wst.ws.internal.explorer.platform.perspective.Controller;
21
import org.eclipse.wst.ws.internal.explorer.platform.perspective.Controller;
22
import org.eclipse.wst.ws.internal.explorer.platform.util.MultipartFormDataException;
22
import org.eclipse.wst.ws.internal.explorer.platform.util.MultipartFormDataException;
23
import org.eclipse.wst.ws.internal.explorer.platform.util.MultipartFormDataParser;
23
import org.eclipse.wst.ws.internal.explorer.platform.util.MultipartFormDataParser;
24
import org.eclipse.wst.ws.internal.explorer.platform.util.XMLUtils;
25
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.FragmentConstants;
24
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.FragmentConstants;
26
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.WSDLActionInputs;
25
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.WSDLActionInputs;
27
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.WSDLModelConstants;
26
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.WSDLModelConstants;
28
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.WSDLBindingElement;
29
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.WSDLElement;
30
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.WSDLOperationElement;
27
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.WSDLOperationElement;
31
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.WSDLServiceElement;
28
import org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage;
32
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.util.SoapHelper;
33
import org.w3c.dom.Element;
34
import org.w3c.dom.NodeList;
35
29
36
public class InvokeWSDLSOAPOperationSourceAction extends InvokeWSDLSOAPOperationAction
30
public class InvokeWSDLSOAPOperationSourceAction extends InvokeWSDLSOAPOperationAction
37
{
31
{
38
  private boolean newFileSelected_;
32
  private boolean newFileSelected_;
39
  private boolean saveAsSelected_;
33
  private boolean saveAsSelected_;
40
  private boolean isHeader_;
34
  private boolean isHeader_;
41
  private static final String DUMMY_WRAPPER_START_TAG = "<dummyWrapper>";
42
  private static final String DUMMY_WRAPPER_END_TAG = "</dummyWrapper>";
43
  
35
  
44
  public InvokeWSDLSOAPOperationSourceAction(Controller controller)
36
  public InvokeWSDLSOAPOperationSourceAction(Controller controller)
45
  {
37
  {
Lines 120-185 Link Here
120
    return false;
112
    return false;
121
    */
113
    */
122
  }
114
  }
115
  
116
  /* (non-Javadoc)
117
   * @see org.eclipse.wst.ws.internal.explorer.platform.wsdl.actions.InvokeWSDLSOAPOperationAction#getSOAPRequestMessage(org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.WSDLOperationElement)
118
   */
119
  protected ISOAPMessage getSOAPRequestMessage(WSDLOperationElement operElement) {	  
120
	  return (ISOAPMessage) operElement.getPropertyAsObject(WSDLModelConstants.PROP_SOAP_REQUEST_TMP);
121
  } 
123
122
124
  protected Vector getHeaderEntries(Hashtable soapEnvelopeNamespaceTable, WSDLOperationElement operElement) throws ParserConfigurationException, Exception {
123
  /* (non-Javadoc)
125
	
124
   * @see org.eclipse.wst.ws.internal.explorer.platform.wsdl.actions.InvokeWSDLSOAPOperationAction#setHeaderContent(java.util.Hashtable, org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.WSDLOperationElement, org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage)
126
	  Vector headerEntries = new Vector();
127
      String[] nsDeclarations = (String[])operElement.getPropertyAsObject(WSDLModelConstants.PROP_SOURCE_CONTENT_NAMESPACE);
128
   	  for (int i = 0; i < nsDeclarations.length; i++)
129
	  {
130
	    String[] prefix_ns = SoapHelper.decodeNamespaceDeclaration(nsDeclarations[i]);
131
	    if (!soapEnvelopeNamespaceTable.contains(prefix_ns[1]))
132
	      soapEnvelopeNamespaceTable.put(prefix_ns[1], prefix_ns[0]);
133
	  }
134
	  StringBuffer sourceContent = new StringBuffer(operElement.getPropertyAsString(WSDLModelConstants.PROP_SOURCE_CONTENT_HEADER));
135
	  sourceContent.insert(0,DUMMY_WRAPPER_START_TAG).append(DUMMY_WRAPPER_END_TAG);
136
	  Element dummyWrapperElement = XMLUtils.stringToElement(sourceContent.toString());          
137
	  NodeList nl = dummyWrapperElement.getChildNodes();
138
	  for (int i = 0; i < nl.getLength(); i++)
139
	  {
140
	    if (nl.item(i) instanceof Element)
141
	      headerEntries.add(nl.item(i));
142
	  }
143
	  
144
	  return headerEntries;
145
  }
146
147
  /**
148
   * Generate a Vector of the elements inside the Soap Body.
149
   * @param soapEnvelopeNamespaceTable - Hashtable containing a map of the namespace URIs to prefixes.
150
   * @param operElement - WSDLOperationElement encapsulating the WSDL operation.
151
   */
125
   */
152
  protected Vector getBodyEntries(Hashtable soapEnvelopeNamespaceTable,WSDLOperationElement operElement,WSDLBindingElement bindingElement,WSDLServiceElement serviceElement) throws ParserConfigurationException,Exception
126
  protected void setHeaderContent(Hashtable soapEnvelopeNamespaceTable, WSDLOperationElement operElement, ISOAPMessage soapMessage) {	
153
  {
127
   	String headerContent = operElement.getPropertyAsString(WSDLModelConstants.PROP_SOURCE_CONTENT_HEADER);
154
    Vector bodyEntries = new Vector();
128
    operElement.getSOAPTransportProvider().newTransport().newDeserializer()
155
    String[] nsDeclarations = (String[])operElement.getPropertyAsObject(WSDLModelConstants.PROP_SOURCE_CONTENT_NAMESPACE);
129
    	.deserialize(ISOAPMessage.HEADER_CONTENT, headerContent, soapMessage);
156
    for (int i = 0; i < nsDeclarations.length; i++)
130
  }
157
    {
131
  
158
      String[] prefix_ns = SoapHelper.decodeNamespaceDeclaration(nsDeclarations[i]);
132
  /* (non-Javadoc)
159
      if (!soapEnvelopeNamespaceTable.contains(prefix_ns[1]))
133
   * @see org.eclipse.wst.ws.internal.explorer.platform.wsdl.actions.InvokeWSDLSOAPOperationAction#setBodyContent(java.util.Hashtable, org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.WSDLOperationElement, org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage)
160
        soapEnvelopeNamespaceTable.put(prefix_ns[1], prefix_ns[0]);
134
   */ 
161
    }
135
  protected void setBodyContent(Hashtable soapEnvelopeNamespaceTable, WSDLOperationElement operElement, ISOAPMessage soapMessage) {
162
    StringBuffer sourceContent = new StringBuffer(operElement.getPropertyAsString(WSDLModelConstants.PROP_SOURCE_CONTENT));
136
    String bodyContent = operElement.getPropertyAsString(WSDLModelConstants.PROP_SOURCE_CONTENT);    
163
    sourceContent.insert(0,DUMMY_WRAPPER_START_TAG).append(DUMMY_WRAPPER_END_TAG);
137
    operElement.getSOAPTransportProvider().newTransport().newDeserializer()
164
    Element dummyWrapperElement = XMLUtils.stringToElement(sourceContent.toString());          
138
    	.deserialize(ISOAPMessage.BODY_CONTENT, bodyContent, soapMessage);        
165
    NodeList nl = dummyWrapperElement.getChildNodes();
166
    for (int i = 0; i < nl.getLength(); i++)
167
    {
168
      if (nl.item(i) instanceof Element)
169
        bodyEntries.add(nl.item(i));
170
    }
171
    if (!operElement.isDocumentStyle())
172
    {
173
      try
174
      {
175
        addRPCWrapper(bodyEntries,(WSDLElement)serviceElement.getParentElement(),operElement,soapEnvelopeNamespaceTable);
176
      }
177
      catch (ParserConfigurationException e)
178
      {
179
        throw e;
180
      }
181
    }
182
    return bodyEntries;
183
  }
139
  }
184
140
185
  public final boolean wasNewFileSelected()
141
  public final boolean wasNewFileSelected()
(-)wsexplorer-src/org/eclipse/wst/ws/internal/explorer/platform/wsdl/actions/SynchronizeFragmentViewsAction.java (-64 / +53 lines)
Lines 10-37 Link Here
10
 * yyyymmdd bug      Email and other contact information
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070305   117034 makandre@ca.ibm.com - Andrew Mak, Web Services Explorer should support SOAP Headers
12
 * 20070305   117034 makandre@ca.ibm.com - Andrew Mak, Web Services Explorer should support SOAP Headers
13
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
13
 *******************************************************************************/
14
 *******************************************************************************/
14
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.actions;
15
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.actions;
15
16
16
import java.util.Hashtable;
17
import java.util.Iterator;
17
import java.util.Iterator;
18
import java.util.Vector;
18
import java.util.Map;
19
19
import javax.wsdl.Part;
20
import javax.wsdl.Part;
21
20
import org.eclipse.wst.ws.internal.explorer.platform.perspective.Controller;
22
import org.eclipse.wst.ws.internal.explorer.platform.perspective.Controller;
21
import org.eclipse.wst.ws.internal.explorer.platform.perspective.Node;
23
import org.eclipse.wst.ws.internal.explorer.platform.perspective.Node;
22
import org.eclipse.wst.ws.internal.explorer.platform.util.MultipartFormDataException;
24
import org.eclipse.wst.ws.internal.explorer.platform.util.MultipartFormDataException;
23
import org.eclipse.wst.ws.internal.explorer.platform.util.MultipartFormDataParser;
25
import org.eclipse.wst.ws.internal.explorer.platform.util.MultipartFormDataParser;
24
import org.eclipse.wst.ws.internal.explorer.platform.util.XMLUtils;
25
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.FragmentConstants;
26
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.FragmentConstants;
26
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.WSDLModelConstants;
27
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.WSDLModelConstants;
27
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.WSDLOperationElement;
28
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.WSDLOperationElement;
28
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.fragment.IXSDFragment;
29
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.fragment.IXSDFragment;
29
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.fragment.impl.SOAPHeaderWrapperFragment;
30
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.fragment.impl.SOAPHeaderWrapperFragment;
30
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.perspective.InvokeWSDLOperationTool;
31
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.perspective.InvokeWSDLOperationTool;
31
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.util.SoapHelper;
32
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.util.SOAPMessageUtils;
33
import org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage;
32
import org.eclipse.wst.wsdl.binding.soap.SOAPHeader;
34
import org.eclipse.wst.wsdl.binding.soap.SOAPHeader;
33
import org.w3c.dom.Element;
35
import org.w3c.dom.Element;
34
import org.w3c.dom.NodeList;
35
36
36
public class SynchronizeFragmentViewsAction extends WSDLPropertiesFormAction
37
public class SynchronizeFragmentViewsAction extends WSDLPropertiesFormAction
37
{
38
{
Lines 52-65 Link Here
52
    if (viewID.equals(FragmentConstants.FRAGMENT_VIEW_SWITCH_FORM_TO_SOURCE))
53
    if (viewID.equals(FragmentConstants.FRAGMENT_VIEW_SWITCH_FORM_TO_SOURCE))
53
    {
54
    {
54
      invokeWSDLOperationTool.setFragmentViewID(FragmentConstants.FRAGMENT_VIEW_SWITCH_FORM_TO_SOURCE);
55
      invokeWSDLOperationTool.setFragmentViewID(FragmentConstants.FRAGMENT_VIEW_SWITCH_FORM_TO_SOURCE);
56
      operElement.setPropertyAsObject(WSDLModelConstants.PROP_SOURCE_CONTENT_NAMESPACE, null);
57
      
55
      return processFormViewParsedResultsHeader(parser, operElement) &		// need to process both header and body 
58
      return processFormViewParsedResultsHeader(parser, operElement) &		// need to process both header and body 
56
             processFormViewParsedResults(parser, operElement);
59
             processFormViewParsedResults(parser, operElement);
57
    }
60
    }
58
    else
61
    else
59
    {
62
    {
60
      invokeWSDLOperationTool.setFragmentViewID(FragmentConstants.FRAGMENT_VIEW_SWITCH_SOURCE_TO_FORM);
63
      invokeWSDLOperationTool.setFragmentViewID(FragmentConstants.FRAGMENT_VIEW_SWITCH_SOURCE_TO_FORM);
61
      return processSourceViewParsedResultsHeader(parser, operElement) &	// need to process both header and body
64
      String[] nsDeclarations = parser.getParameterValues(FragmentConstants.SOURCE_CONTENT_NAMESPACE);    
62
      		 processSourceViewParsedResults(parser, operElement);
65
      if (nsDeclarations != null)
66
        operElement.setPropertyAsObject(WSDLModelConstants.PROP_SOURCE_CONTENT_NAMESPACE,nsDeclarations);
67
      
68
      ISOAPMessage soapMessage = (ISOAPMessage) operElement.getPropertyAsObject(WSDLModelConstants.PROP_SOAP_REQUEST_TMP);
69
      boolean rc = processSourceViewParsedResultsHeader(parser, operElement, soapMessage) &	// need to process both header and body
70
		 		   processSourceViewParsedResults(parser, operElement, soapMessage); 
71
      operElement.setPropertyAsObject(WSDLModelConstants.PROP_SOAP_REQUEST_TMP, null);
72
      
73
      return rc;
63
    }
74
    }
64
  }
75
  }
65
76
Lines 84-90 Link Here
84
  private boolean processFormViewParsedResults(MultipartFormDataParser parser, WSDLOperationElement operElement) throws MultipartFormDataException
95
  private boolean processFormViewParsedResults(MultipartFormDataParser parser, WSDLOperationElement operElement) throws MultipartFormDataException
85
  {
96
  {
86
    operElement.setPropertyAsObject(WSDLModelConstants.PROP_SOURCE_CONTENT, null);
97
    operElement.setPropertyAsObject(WSDLModelConstants.PROP_SOURCE_CONTENT, null);
87
    operElement.setPropertyAsObject(WSDLModelConstants.PROP_SOURCE_CONTENT_NAMESPACE, null);
88
    boolean resultsValid = true;
98
    boolean resultsValid = true;
89
	
99
	
90
    Iterator it = operElement.getOrderedBodyParts().iterator();    
100
    Iterator it = operElement.getOrderedBodyParts().iterator();    
Lines 99-151 Link Here
99
      operElement.setPropertyAsString(WSDLModelConstants.PROP_SOURCE_CONTENT,null);
109
      operElement.setPropertyAsString(WSDLModelConstants.PROP_SOURCE_CONTENT,null);
100
    return resultsValid;
110
    return resultsValid;
101
  }
111
  }
102
112
  
103
  private boolean processSourceViewParsedResultsHeader(MultipartFormDataParser parser, WSDLOperationElement operElement) throws MultipartFormDataException
113
  private boolean processSourceViewParsedResultsHeader(MultipartFormDataParser parser, WSDLOperationElement operElement, ISOAPMessage soapMessage) 
104
  { 
114
  	throws MultipartFormDataException {
115
	  
105
    String sourceContent = parser.getParameter(FragmentConstants.SOURCE_CONTENT_HEADER);
116
    String sourceContent = parser.getParameter(FragmentConstants.SOURCE_CONTENT_HEADER);
106
    if (sourceContent != null)
117
    if (sourceContent != null)
107
      operElement.setPropertyAsString(WSDLModelConstants.PROP_SOURCE_CONTENT_HEADER, sourceContent);    
118
      operElement.setPropertyAsString(WSDLModelConstants.PROP_SOURCE_CONTENT_HEADER, sourceContent);    
108
    String[] nsDeclarations = parser.getParameterValues(FragmentConstants.SOURCE_CONTENT_NAMESPACE);    
119
           
109
    if (nsDeclarations != null)
110
      operElement.setPropertyAsObject(WSDLModelConstants.PROP_SOURCE_CONTENT_NAMESPACE,nsDeclarations);
111
    
112
    Iterator it = operElement.getSOAPHeaders().iterator();
120
    Iterator it = operElement.getSOAPHeaders().iterator();
113
    if (!it.hasNext())
121
    if (!it.hasNext())
114
      return true;
122
      return true;
115
              
116
    Hashtable namespaceTable = new Hashtable();
117
    
123
    
118
    if (nsDeclarations != null) {
119
      for (int i = 0; i < nsDeclarations.length; i++)
120
      {
121
        String[] prefix_ns = SoapHelper.decodeNamespaceDeclaration(nsDeclarations[i]);
122
        if (!namespaceTable.contains(prefix_ns[1]))
123
          namespaceTable.put(prefix_ns[1], prefix_ns[0]);
124
      }
125
    }
126
    
127
    sourceContent = addRootElement(sourceContent);
128
    try
124
    try
129
    {
125
    {
130
      Element sourceElements = XMLUtils.stringToElement(sourceContent);
126
      operElement.getSOAPTransportProvider().newTransport().newDeserializer()
131
      NodeList nl = sourceElements.getChildNodes();
127
      	.deserialize(ISOAPMessage.HEADER_CONTENT, sourceContent, soapMessage);  
132
  
128
    	
133
      Hashtable elements = new Hashtable();
129
      Element[] instanceDocuments = soapMessage.getHeaderContent();
134
      
130
      Map namespaceTable = soapMessage.getNamespaceTable();
135
      // work backwards so that if there are multiple nodes with the same name
136
      // the topmost one takes precedence
137
      for (int i = nl.getLength() - 1; i >= 0; i--) {
138
    	  org.w3c.dom.Node node = nl.item(i);
139
          if (node != null && node instanceof Element)
140
        	  elements.put(node.getNodeName(), node);
141
      }      
142
      
131
      
143
      boolean sourceElementsValid = true;
132
      boolean sourceElementsValid = true;
144
      while (it.hasNext())
133
      int start = 0;
134
      while (it.hasNext() && start < instanceDocuments.length)
145
      {
135
      {
146
        SOAPHeader soapHeader = (SOAPHeader)it.next();
136
        SOAPHeader soapHeader = (SOAPHeader)it.next();
147
        SOAPHeaderWrapperFragment frag = (SOAPHeaderWrapperFragment) operElement.getHeaderFragment(soapHeader);
137
        SOAPHeaderWrapperFragment frag = (SOAPHeaderWrapperFragment) operElement.getHeaderFragment(soapHeader);
148
        if (!frag.setParameterValuesFromInstanceDocuments(elements, namespaceTable))
138
        
139
        int pos = SOAPMessageUtils.findFirstMatchingElement(
140
        		soapHeader.getEPart(),
141
				instanceDocuments,
142
				namespaceTable,
143
				frag.getName(),
144
				start);
145
			
146
		if (pos == -1)
147
			continue;
148
			
149
		Element element = instanceDocuments[pos];
150
		start = pos + 1;			
151
        
152
        if (!frag.setParameterValuesFromInstanceDocument(element, namespaceTable))
149
          sourceElementsValid = false;
153
          sourceElementsValid = false;
150
      }
154
      }
151
      return sourceElementsValid;
155
      return sourceElementsValid;
Lines 156-183 Link Here
156
    }    
160
    }    
157
  }
161
  }
158
  
162
  
159
  private boolean processSourceViewParsedResults(MultipartFormDataParser parser, WSDLOperationElement operElement) throws MultipartFormDataException
163
  private boolean processSourceViewParsedResults(MultipartFormDataParser parser, WSDLOperationElement operElement, ISOAPMessage soapMessage)
160
  {
164
  	throws MultipartFormDataException {
165
	  
161
    String sourceContent = parser.getParameter(FragmentConstants.SOURCE_CONTENT);
166
    String sourceContent = parser.getParameter(FragmentConstants.SOURCE_CONTENT);
162
    if (sourceContent != null)
167
    if (sourceContent != null)
163
      operElement.setPropertyAsString(WSDLModelConstants.PROP_SOURCE_CONTENT, sourceContent);
168
      operElement.setPropertyAsString(WSDLModelConstants.PROP_SOURCE_CONTENT, sourceContent);
164
    
169
    
165
    Iterator it = operElement.getOrderedBodyParts().iterator();    
170
    Iterator it = operElement.getOrderedBodyParts().iterator();    
166
    
171
    
167
    sourceContent = addRootElement(sourceContent);
168
    try
172
    try
169
    {
173
    {
170
      Element sourceElements = XMLUtils.stringToElement(sourceContent);
174
      operElement.getSOAPTransportProvider().newTransport().newDeserializer()
171
      NodeList nl = sourceElements.getChildNodes();
175
      	.deserialize(ISOAPMessage.BODY_CONTENT, sourceContent, soapMessage);      	
172
      Vector elementsVector = new Vector();
176
    	
173
      for (int i = 0; i < nl.getLength(); i++)
177
      Element[] instanceDocuments = soapMessage.getBodyContent();
174
      {
178
      
175
        org.w3c.dom.Node node = nl.item(i);
176
        if (node != null && node instanceof Element)
177
          elementsVector.add(node);
178
      }
179
      Element[] instanceDocuments = new Element[elementsVector.size()];
180
      elementsVector.copyInto(instanceDocuments);
181
      boolean sourceElementsValid = true;
179
      boolean sourceElementsValid = true;
182
      while (it.hasNext())
180
      while (it.hasNext())
183
      {
181
      {
Lines 194-208 Link Here
194
    }
192
    }
195
  }
193
  }
196
194
197
  private String addRootElement(String element)
198
  {
199
    StringBuffer sb = new StringBuffer();
200
    sb.append(FragmentConstants.ROOT_ELEMENT_START_TAG);
201
    sb.append(element);
202
    sb.append(FragmentConstants.ROOT_ELEMENT_END_TAG);
203
    return sb.toString();
204
  }
205
206
  public boolean run() {
195
  public boolean run() {
207
    return true;
196
    return true;
208
  }
197
  }
(-)wsexplorer-src/org/eclipse/wst/ws/internal/explorer/platform/wsdl/actions/InvokeWSDLSOAPOperationAction.java (-228 / +77 lines)
Lines 10-57 Link Here
10
 * yyyymmdd bug      Email and other contact information
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070305   117034 makandre@ca.ibm.com - Andrew Mak, Web Services Explorer should support SOAP Headers
12
 * 20070305   117034 makandre@ca.ibm.com - Andrew Mak, Web Services Explorer should support SOAP Headers
13
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
13
 *******************************************************************************/
14
 *******************************************************************************/
14
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.actions;
15
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.actions;
15
16
16
import java.io.BufferedReader;
17
import java.io.IOException;
17
import java.io.IOException;
18
import java.util.Hashtable;
18
import java.util.Hashtable;
19
import java.util.Iterator;
19
20
import java.util.List;
21
import java.util.Vector;
22
import javax.servlet.http.HttpServletResponse;
20
import javax.servlet.http.HttpServletResponse;
23
import javax.wsdl.BindingInput;
24
import javax.wsdl.BindingOperation;
25
import javax.wsdl.Definition;
26
import javax.wsdl.Part;
27
import javax.wsdl.extensions.ExtensibilityElement;
28
import javax.wsdl.extensions.soap.SOAPBody;
29
import javax.xml.parsers.DocumentBuilder;
30
import javax.xml.parsers.DocumentBuilderFactory;
31
import javax.xml.parsers.ParserConfigurationException;
21
import javax.xml.parsers.ParserConfigurationException;
32
import org.apache.axis.Constants;
22
33
import org.eclipse.wst.ws.internal.explorer.platform.perspective.Controller;
23
import org.eclipse.wst.ws.internal.explorer.platform.perspective.Controller;
34
import org.eclipse.wst.ws.internal.explorer.platform.perspective.MessageQueue;
24
import org.eclipse.wst.ws.internal.explorer.platform.perspective.MessageQueue;
35
import org.eclipse.wst.ws.internal.explorer.platform.util.MultipartFormDataException;
25
import org.eclipse.wst.ws.internal.explorer.platform.util.MultipartFormDataException;
36
import org.eclipse.wst.ws.internal.explorer.platform.util.MultipartFormDataParser;
26
import org.eclipse.wst.ws.internal.explorer.platform.util.MultipartFormDataParser;
37
import org.eclipse.wst.ws.internal.explorer.platform.util.XMLUtils;
38
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.WSDLActionInputs;
27
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.WSDLActionInputs;
28
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.WSDLModelConstants;
39
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.Endpoint;
29
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.Endpoint;
40
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.WSDLBindingElement;
30
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.WSDLBindingElement;
41
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.WSDLElement;
42
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.WSDLOperationElement;
31
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.WSDLOperationElement;
43
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.WSDLServiceElement;
44
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.fragment.IXSDFragment;
45
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.perspective.InvokeWSDLOperationTool;
32
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.perspective.InvokeWSDLOperationTool;
46
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.perspective.SOAPMessageQueue;
47
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.perspective.WSDLPerspective;
33
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.perspective.WSDLPerspective;
48
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport.HTTPException;
34
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.util.SOAPMessageUtils;
49
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport.HTTPTransport;
35
import org.eclipse.wst.ws.internal.explorer.transport.HTTPTransportException;
50
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.util.SoapHelper;
36
import org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage;
51
import org.eclipse.wst.ws.internal.parser.discovery.NetUtils;
37
import org.eclipse.wst.ws.internal.explorer.transport.ISOAPTransportProvider;
52
import org.eclipse.wst.wsdl.binding.soap.SOAPHeader;
38
import org.eclipse.wst.ws.internal.explorer.transport.TransportException;
53
import org.w3c.dom.Document;
54
import org.w3c.dom.Element;
55
39
56
public abstract class InvokeWSDLSOAPOperationAction extends WSDLPropertiesFormAction
40
public abstract class InvokeWSDLSOAPOperationAction extends WSDLPropertiesFormAction
57
{
41
{
Lines 69-250 Link Here
69
    return true;
53
    return true;
70
  }
54
  }
71
55
72
  protected final void addRPCWrapper(Vector bodyEntries,WSDLElement wsdlElement,WSDLOperationElement operElement,Hashtable soapEnvelopeNamespaceTable) throws ParserConfigurationException
73
  {
74
    // Must be RPC style.
75
    String encodingNamespaceURI = null;
76
    /*
77
     * WS-I: In a rpc-literal SOAP binding, the serialized child element of the 
78
     * soap:Body element consists of a wrapper element, whose namespace is the value 
79
     * of the namespace attribute of the soapbind:body element and whose local name is 
80
     * either the name of the operation or the name of the operation suffixed 
81
     * with "Response". The namespace attribute is required, as opposed to being 
82
     * optional, to ensure that the children of the soap:Body element are namespace-
83
     * qualified.
84
     */
85
    BindingOperation bindingOperation = operElement.getBindingOperation();
86
    if (bindingOperation != null)
87
    {
88
      BindingInput bindingInput = bindingOperation.getBindingInput();
89
      if (bindingInput != null)
90
      {
91
        List extElements = bindingInput.getExtensibilityElements();
92
        for (Iterator it = extElements.iterator(); it.hasNext();)
93
        {
94
          ExtensibilityElement extElement = (ExtensibilityElement)it.next();
95
          if (extElement instanceof SOAPBody)
96
          {
97
            encodingNamespaceURI = ((SOAPBody)extElement).getNamespaceURI();
98
            break;
99
          }
100
        }
101
      }
102
    }
103
    // If the namespace of the soapbind:body element is not set, get it from the operation element
104
    if (encodingNamespaceURI == null)
105
      encodingNamespaceURI = operElement.getEncodingNamespace();
106
    // If the namespace of the operation element is not set, get it from the definition element
107
    if (encodingNamespaceURI == null)
108
    {
109
      Definition definition = wsdlElement.getDefinition();
110
      encodingNamespaceURI = definition.getTargetNamespace();
111
    }
112
    // Generate an RPC style wrapper element.
113
    Document doc = XMLUtils.createNewDocument(null);
114
    String encodingStyle = (operElement.isUseLiteral() ? null : operElement.getEncodingStyle());
115
    Element wrapperElement = SoapHelper.createRPCWrapperElement(doc,soapEnvelopeNamespaceTable,encodingNamespaceURI,operElement.getOperation().getName(),encodingStyle);
116
    for (int i=0;i<bodyEntries.size();i++)
117
      wrapperElement.appendChild(doc.importNode((Element)bodyEntries.elementAt(i),true));
118
    bodyEntries.removeAllElements();
119
    bodyEntries.addElement(wrapperElement);
120
  }
121
122
  /**
56
  /**
123
   * Generate a Vector of the elements inside the Soap Header.
57
   * Returns an ISOAPMessage to use for the current SOAP operation invocation.
124
   * @param soapEnvelopeNamespaceTable - Hashtable containing a map of the namespace URIs to prefixes.
58
   * 
125
   * @param operElement - WSDLOperationElement encapsulating the WSDL operation.
59
   * @param operElement The operation element from the WSDL model.
60
   * 
61
   * @return An ISOAPMessage, or null if a message cannot be constructed.
126
   */
62
   */
127
  protected Vector getHeaderEntries(Hashtable soapEnvelopeNamespaceTable,WSDLOperationElement operElement) throws ParserConfigurationException,Exception
63
  protected ISOAPMessage getSOAPRequestMessage(WSDLOperationElement operElement) {
128
  {
64
	  ISOAPTransportProvider provider = operElement.getSOAPTransportProvider();
129
    Vector headerEntries = new Vector();
65
	  if (provider == null)
130
    
66
		  return null;	  
131
    Iterator it = operElement.getSOAPHeaders().iterator();
67
	  return provider.newTransport().newMessage(operElement.getMessageContext());
132
    while (it.hasNext())
133
    {
134
      SOAPHeader soapHeader = (SOAPHeader) it.next();
135
      
136
      StringBuffer encodingStyle = null;
137
      boolean isUseLiteral = "literal".equals(soapHeader.getUse());      
138
      
139
      if (!isUseLiteral) {
140
	      Iterator encodingStyles = soapHeader.getEncodingStyles().iterator();
141
	      encodingStyle = new StringBuffer();
142
	      while (encodingStyles.hasNext()) {
143
	    	  Object next = encodingStyles.next();
144
	    	  if (Constants.URI_SOAP11_ENC.equals(next))
145
	    		  continue;
146
	    	  encodingStyle.append(" ").append(next);
147
	      }	              
148
      }
149
      
150
      IXSDFragment frag = (IXSDFragment)operElement.getHeaderFragment(soapHeader);
151
      Element[] instanceDocuments = frag.genInstanceDocumentsFromParameterValues(!isUseLiteral,soapEnvelopeNamespaceTable, XMLUtils.createNewDocument(null));
152
      for (int j=0;j<instanceDocuments.length;j++)
153
      {
154
        if (instanceDocuments[j] == null)
155
          continue;
156
        if (encodingStyle != null && encodingStyle.length() > 0)
157
          instanceDocuments[j].setAttribute("soapenv:encodingStyle",encodingStyle.substring(1));
158
        headerEntries.addElement(instanceDocuments[j]);
159
      }
160
    }
161
	
162
    return headerEntries;
163
  }
68
  }
164
  
69
  
165
  /**
70
  /**
166
   * Generate a Vector of the elements inside the Soap Body.
71
   * Populate the given ISOAPMessage's header using the inputs from WSE
167
   * @param soapEnvelopeNamespaceTable - Hashtable containing a map of the namespace URIs to prefixes.
72
   * 
168
   * @param operElement - WSDLOperationElement encapsulating the WSDL operation.
73
   * @param soapEnvelopeNamespaceTable Hashtable containing a map of the namespace URIs to prefixes.
74
   * @param operElement WSDLOperationElement encapsulating the WSDL operation.
75
   * @param soapMessage The ISOAPMessage to populate 
169
   */
76
   */
170
  protected Vector getBodyEntries(Hashtable soapEnvelopeNamespaceTable,WSDLOperationElement operElement,WSDLBindingElement bindingElement,WSDLServiceElement serviceElement) throws ParserConfigurationException,Exception
77
  protected void setHeaderContent(Hashtable soapEnvelopeNamespaceTable, WSDLOperationElement operElement, ISOAPMessage soapMessage)
171
  {
78
    throws ParserConfigurationException {
172
    Vector bodyEntries = new Vector();
79
    SOAPMessageUtils.setHeaderContentFromModel(soapEnvelopeNamespaceTable, operElement, soapMessage);
173
    boolean isUseLiteral = operElement.isUseLiteral();
174
    String encodingStyle = operElement.getEncodingStyle();
175
    boolean addEncodingStyle = (!isUseLiteral && !Constants.URI_SOAP11_ENC.equals(encodingStyle));
176
    Iterator it = operElement.getOrderedBodyParts().iterator();
177
    while (it.hasNext())
178
    {
179
      Part part = (Part)it.next();
180
      IXSDFragment frag = (IXSDFragment)operElement.getFragment(part);
181
      Element[] instanceDocuments = frag.genInstanceDocumentsFromParameterValues(!isUseLiteral,soapEnvelopeNamespaceTable, XMLUtils.createNewDocument(null));
182
      for (int j=0;j<instanceDocuments.length;j++)
183
      {
184
        if (instanceDocuments[j] == null)
185
          continue;
186
        if (addEncodingStyle)
187
          instanceDocuments[j].setAttribute("soapenv:encodingStyle",encodingStyle);
188
        bodyEntries.addElement(instanceDocuments[j]);
189
      }
190
    }
191
192
    if (!operElement.isDocumentStyle())
193
    {
194
      try
195
      {
196
        addRPCWrapper(bodyEntries,(WSDLElement)serviceElement.getParentElement(),operElement,soapEnvelopeNamespaceTable);
197
      }
198
      catch (ParserConfigurationException e)
199
      {
200
        throw e;
201
      }
202
    }
203
    return bodyEntries;
204
  }
205
206
  protected Element getSOAPEnvelope(Hashtable soapEnvelopeNamespaceTable, Vector bodyEntries) throws ParserConfigurationException
207
  {
208
	return getSOAPEnvelope(soapEnvelopeNamespaceTable, null, bodyEntries);
209
  }
210
  
211
  protected Element getSOAPEnvelope(Hashtable soapEnvelopeNamespaceTable, Vector headerEntries, Vector bodyEntries) throws ParserConfigurationException
212
  {
213
    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
214
    Document doc = XMLUtils.createNewDocument(docBuilder);
215
    Element soapEnvelopeElement = SoapHelper.createSoapEnvelopeElement(doc,soapEnvelopeNamespaceTable);
216
    
217
    if (headerEntries != null && !headerEntries.isEmpty()) {
218
    	Element soapHeaderElement = SoapHelper.createSoapHeaderElement(doc);
219
        for (int i=0;i<headerEntries.size();i++)
220
          soapHeaderElement.appendChild(doc.importNode((Element)headerEntries.elementAt(i),true));
221
        soapEnvelopeElement.appendChild(soapHeaderElement);        
222
    }
223
    
224
    Element soapBodyElement = SoapHelper.createSoapBodyElement(doc);
225
    for (int i=0;i<bodyEntries.size();i++)
226
      soapBodyElement.appendChild(doc.importNode((Element)bodyEntries.elementAt(i),true));
227
    soapEnvelopeElement.appendChild(soapBodyElement);
228
    return soapEnvelopeElement;
229
  }
230
231
  private final void recordSoapRequest(SOAPMessageQueue soapRequestQueue,Hashtable soapEnvelopeNamespaceTable,Element soapEnvelope) throws ParserConfigurationException,IOException
232
  {
233
    soapRequestQueue.clear();
234
    soapRequestQueue.addMessage(XMLUtils.serialize(soapEnvelope,false));
235
  }
80
  }
236
81
237
  private final void recordSOAPResponse(SOAPMessageQueue soapResponseQueue,BufferedReader responseReader) throws IOException
82
  /**
238
  {
83
   * Populate the given ISOAPMessage's body using the inputs from WSE
239
    soapResponseQueue.clear();
84
   * 
240
    if (responseReader != null)
85
   * @param soapEnvelopeNamespaceTable Hashtable containing a map of the namespace URIs to prefixes.
241
    {
86
   * @param operElement WSDLOperationElement encapsulating the WSDL operation.
242
      String line = null;
87
   * @param soapMessage The ISOAPMessage to populate 
243
      while ((line = responseReader.readLine()) != null)
88
   */  
244
        soapResponseQueue.addMessage(line);
89
  protected void setBodyContent(Hashtable soapEnvelopeNamespaceTable, WSDLOperationElement operElement, ISOAPMessage soapMessage) 
245
      responseReader.close();
90
    throws ParserConfigurationException {
246
    }
91
	SOAPMessageUtils.setBodyContentFromModel(soapEnvelopeNamespaceTable, operElement, soapMessage);
247
  }
92
  }        
248
93
249
  public boolean run()
94
  public boolean run()
250
  {
95
  {
Lines 253-259 Link Here
253
    MessageQueue messageQueue = wsdlPerspective.getMessageQueue();
98
    MessageQueue messageQueue = wsdlPerspective.getMessageQueue();
254
    WSDLOperationElement operElement = (WSDLOperationElement)getSelectedNavigatorNode().getTreeElement();
99
    WSDLOperationElement operElement = (WSDLOperationElement)getSelectedNavigatorNode().getTreeElement();
255
    WSDLBindingElement bindingElement = (WSDLBindingElement)operElement.getParentElement();
100
    WSDLBindingElement bindingElement = (WSDLBindingElement)operElement.getParentElement();
256
    WSDLServiceElement serviceElement = (WSDLServiceElement)bindingElement.getParentElement();
257
    operElement.setPropertyAsObject(WSDLActionInputs.SOAP_RESPONSE_CACHED, new Boolean(false));
101
    operElement.setPropertyAsObject(WSDLActionInputs.SOAP_RESPONSE_CACHED, new Boolean(false));
258
    try
102
    try
259
    {
103
    {
Lines 263-309 Link Here
263
      //    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
107
      //    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
264
      //    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
108
      //    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
265
      // ...
109
      // ...
266
      Hashtable soapEnvelopeNamespaceTable = new Hashtable();
267
      SoapHelper.addDefaultSoapEnvelopeNamespaces(soapEnvelopeNamespaceTable);
268
      Vector headerEntries = getHeaderEntries(soapEnvelopeNamespaceTable, operElement);
269
      Vector bodyEntries = getBodyEntries(soapEnvelopeNamespaceTable,operElement,bindingElement,serviceElement);
270
      Element soapEnvelope = getSOAPEnvelope(soapEnvelopeNamespaceTable, headerEntries, bodyEntries);
271
      recordSoapRequest(wsdlPerspective.getSOAPRequestQueue(),soapEnvelopeNamespaceTable,soapEnvelope);
272
110
273
      // Execute the SOAP operation.
111
	  ISOAPMessage soapMessage = getSOAPRequestMessage(operElement);
112
	  if (soapMessage == null)
113
		  throw new TransportException(wsdlPerspective.getMessage("MSG_ERROR_NO_SUITABLE_TRANSPORT"));
114
	  
115
	  Hashtable namespaceTable = new Hashtable(soapMessage.getNamespaceTable());	  
116
	  setHeaderContent(namespaceTable, operElement, soapMessage);
117
	  setBodyContent(namespaceTable, operElement, soapMessage);      
118
	  soapMessage.setNamespaceTable(namespaceTable);
119
120
	  // store the request
121
	  operElement.setPropertyAsObject(WSDLModelConstants.PROP_SOAP_REQUEST, soapMessage);  
122
	  
123
	  // Execute the SOAP operation.
274
      if (soapAddressLocation != null)
124
      if (soapAddressLocation != null)
275
      {
125
      {    	
276
        // Send the message and record the SOAP Response Envelope.
126
    	soapMessage.setProperty(ISOAPMessage.PROP_SOAP_ACTION, operElement.getSoapAction());
277
        HTTPTransport transport = createTransport(bindingElement, soapAddressLocation);
127
    	String[] authParams = retrieveAuthParams(bindingElement, soapAddressLocation);
278
        transport.send(NetUtils.createURL(soapAddressLocation),operElement.getSoapAction(),XMLUtils.serialize(soapEnvelope, true));
128
    	
279
        recordSOAPResponse(wsdlPerspective.getSOAPResponseQueue(),transport.receive());
129
    	// invoke!
130
    	ISOAPMessage soapResponse = operElement.getSOAPTransportProvider().newTransport()
131
    		.send(soapAddressLocation, authParams[0], authParams[1], soapMessage);
132
    	
133
    	// store the response
134
    	operElement.setPropertyAsObject(WSDLModelConstants.PROP_SOAP_RESPONSE, soapResponse);
135
    	
280
        wsdlPerspective.setOperationNode(getSelectedNavigatorNode());
136
        wsdlPerspective.setOperationNode(getSelectedNavigatorNode());
281
        return true;
137
        return true;
282
      }
138
      }
283
      throw new IOException(wsdlPerspective.getMessage("MSG_ERROR_UNABLE_TO_CONNECT",soapAddressLocation));
139
      throw new IOException(wsdlPerspective.getMessage("MSG_ERROR_UNABLE_TO_CONNECT",soapAddressLocation));
284
    }
140
    }
285
    catch (ParserConfigurationException e)
141
    catch (HTTPTransportException e) {
286
    {
142
      throwHTTPTransportException(bindingElement, soapAddressLocation, e);
287
      handleUnexpectedException(wsdlPerspective,messageQueue,"ParserConfigurationException",e);
288
    }
289
    catch (IOException e)
290
    {
291
      handleUnexpectedException(wsdlPerspective,messageQueue,"IOException",e);
292
    }
143
    }
293
    catch (HTTPException httpe)
144
    catch (Exception e) {
294
    {
145
      Throwable t = e;
295
      throwHTTPException(bindingElement, soapAddressLocation, httpe);
146
      if (e instanceof TransportException && e.getCause() != null)
296
    }
147
    	t = e.getCause();
297
    catch (Exception e)
148
      handleUnexpectedException(wsdlPerspective, messageQueue, t.getClass().getSimpleName(), t);
298
    {
299
      handleUnexpectedException(wsdlPerspective,messageQueue,"Exception",e);
300
    }
149
    }
301
    return false;
150
    return false;
302
  }
151
  }
303
  
152
  
304
  private void throwHTTPException(WSDLBindingElement bindingElement, String endpointString, HTTPException httpException) throws HTTPException
153
  private void throwHTTPTransportException(WSDLBindingElement bindingElement, String endpointString, HTTPTransportException httpTransportException) throws HTTPTransportException
305
  {
154
  {
306
    if (httpException.getStatusCode() == HttpServletResponse.SC_UNAUTHORIZED)
155
    if (httpTransportException.getStatusCode() == HttpServletResponse.SC_UNAUTHORIZED)
307
    {
156
    {
308
      Endpoint endpoint = bindingElement.getEndpoint(endpointString);
157
      Endpoint endpoint = bindingElement.getEndpoint(endpointString);
309
      if (endpoint != null)
158
      if (endpoint != null)
Lines 313-324 Link Here
313
        endpoint.setHttpBasicAuthPassword(null);
162
        endpoint.setHttpBasicAuthPassword(null);
314
      }
163
      }
315
    }
164
    }
316
    throw httpException;
165
    throw httpTransportException;
317
  }
166
  }
318
  
167
  
319
  private HTTPTransport createTransport(WSDLBindingElement bindingElement, String endpointString)
168
  private String[] retrieveAuthParams(WSDLBindingElement bindingElement, String endpointString)
320
  {
169
  {
321
    HTTPTransport transport = new HTTPTransport();
170
	String[] authParams = new String[] { null, null };
322
    Endpoint endpoint = bindingElement.getEndpoint(endpointString);
171
    Endpoint endpoint = bindingElement.getEndpoint(endpointString);
323
    if (endpoint != null)
172
    if (endpoint != null)
324
    {
173
    {
Lines 335-345 Link Here
335
        }
184
        }
336
        if (httpBasicAuthUsername != null && httpBasicAuthPassword != null)
185
        if (httpBasicAuthUsername != null && httpBasicAuthPassword != null)
337
        {
186
        {
338
          transport.setHttpBasicAuthUsername(httpBasicAuthUsername);
187
          authParams[0] = httpBasicAuthUsername;
339
          transport.setHttpBasicAuthPassword(httpBasicAuthPassword);
188
          authParams[1] = httpBasicAuthPassword;
340
        }
189
        }
341
      }
190
      }
342
    }
191
    }
343
    return transport;
192
    return authParams;
344
  }
193
  }
345
}
194
}
(-)plugin.xml (-1 / +10 lines)
Lines 2-7 Link Here
2
<?eclipse version="3.0"?>
2
<?eclipse version="3.0"?>
3
3
4
<plugin>
4
<plugin>
5
   <extension-point id="wseTransportProvider" name="%XP_WSE_TRANSPORT_PROVIDER" schema="schema/wseTransportProvider.exsd"/>
5
6
6
    
7
    
7
<!-- ================================================================= -->
8
<!-- ================================================================= -->
Lines 43-47 Link Here
43
         </action>
44
         </action>
44
      </objectContribution>
45
      </objectContribution>
45
   </extension>
46
   </extension>
46
47
   <extension
48
         point="org.eclipse.wst.ws.explorer.wseTransportProvider">
49
      <soapTransportProvider
50
            class="org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport.SOAPTransportProvider"
51
            id="org.eclipse.wst.ws.explorer.soapTransportProvider"
52
            name="%SOAP_TRANSPORT_PROVIDER"
53
            namespaceURI="http://schemas.xmlsoap.org/wsdl/soap/"
54
            transportURI="http://schemas.xmlsoap.org/soap/http"/>
55
   </extension>
47
</plugin>
56
</plugin>
(-)build.properties (-1 / +2 lines)
Lines 22-28 Link Here
22
               wsexplorer.war,\
22
               wsexplorer.war,\
23
               META-INF/,\
23
               META-INF/,\
24
               about.html,\
24
               about.html,\
25
               wsexplorer-properties.jar
25
               wsexplorer-properties.jar,\
26
               schema/
26
27
27
28
28
custom = false
29
custom = false
(-)plugin.properties (-2 / +13 lines)
Lines 1-12 Link Here
1
###############################################################################
1
###############################################################################
2
# Copyright (c) 2001, 2005 IBM Corporation and others.
2
# Copyright (c) 2001, 2007 IBM Corporation and others.
3
# All rights reserved. This program and the accompanying materials
3
# All rights reserved. This program and the accompanying materials
4
# are made available under the terms of the Eclipse Public License v1.0
4
# are made available under the terms of the Eclipse Public License v1.0
5
# which accompanies this distribution, and is available at
5
# which accompanies this distribution, and is available at
6
# http://www.eclipse.org/legal/epl-v10.html
6
# http://www.eclipse.org/legal/epl-v10.html
7
#
7
#
8
# Contributors:
8
# Contributors:
9
#     IBM Corporation - initial API and implementation
9
# IBM Corporation - initial API and implementation
10
# yyyymmdd bug      Email and other contact information
11
# -------- -------- -----------------------------------------------------------
12
# 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
10
###############################################################################
13
###############################################################################
11
14
12
#
15
#
Lines 15-20 Link Here
15
PLUGIN_NAME=Web Services Explorer
18
PLUGIN_NAME=Web Services Explorer
16
PLUGIN_PROVIDER=Eclipse.org
19
PLUGIN_PROVIDER=Eclipse.org
17
20
21
XP_WSE_TRANSPORT_PROVIDER=Web Services Explorer Transport Provider
22
SOAP_TRANSPORT_PROVIDER=Default SOAP Transport Provider
23
18
#
24
#
19
# Messages for the client type extension
25
# Messages for the client type extension
20
#
26
#
Lines 33-35 Link Here
33
#
39
#
34
POPUP_TEST_WSDL=Test with Web Services Explorer
40
POPUP_TEST_WSDL=Test with Web Services Explorer
35
41
42
#
43
# SOAP transport messages
44
#
45
MSG_ERROR_UNSUPPORTED_BINDING={0} binding is unsupported.
46
MSG_ERROR_UNSUPPORTED_TRANSPORT={0} transport is unsupported.
(-)wsexplorer-src/org/eclipse/wst/ws/internal/explorer/platform/wsdl/transport/ChunkedInputStream.java (-192 lines)
Removed Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2001, 2005 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
12
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport;
13
14
import java.io.FilterInputStream;
15
import java.io.IOException;
16
import java.io.InputStream;
17
18
public class ChunkedInputStream extends FilterInputStream
19
{
20
  protected long chunkSize = 0l;
21
  protected volatile boolean closed = false;
22
  private static final int maxCharLong = (Long.toHexString(Long.MAX_VALUE)).toString().length();
23
24
  private ChunkedInputStream()
25
  {
26
    super(null);
27
  }
28
29
  public ChunkedInputStream(InputStream is)
30
  {
31
    super(is);
32
  }
33
34
  public int read() throws IOException
35
  {
36
    byte[] d = new byte[1];
37
    int rc = read(d, 0, 1);
38
    return rc > 0 ? (d[0] & 0xFF) : rc;
39
  }
40
41
  public int read(byte[] b) throws IOException
42
  {
43
    return read(b, 0, b.length);
44
  }
45
46
  public synchronized int read(byte[] b, int off, int len) throws IOException
47
  {
48
    if (closed)
49
      return -1;
50
51
    int totalread = 0;
52
    int bytesread = 0;
53
    try
54
    {
55
      do
56
      {
57
        if (chunkSize < 1L)
58
        {
59
          if (0l == getChunked())
60
          {
61
            if (totalread == 0)
62
              return -1;
63
            else
64
              return totalread;
65
          }
66
        }
67
        bytesread = in.read(b, off + totalread, Math.min(len - totalread, (int) Math.min(chunkSize, Integer.MAX_VALUE)));
68
        if (bytesread > 0)
69
        {
70
          totalread += bytesread;
71
          chunkSize -= bytesread;
72
        }
73
      }
74
      while (len - totalread > 0 && bytesread > -1);
75
    }
76
    catch (IOException e)
77
    {
78
      closed = true;
79
      throw e;
80
    }
81
    return totalread;
82
  }
83
84
  public long skip(final long n) throws IOException
85
  {
86
    if (closed)
87
      return 0;
88
    long skipped = 0l;
89
    byte[] b = new byte[1024];
90
    int bread = -1;
91
    do
92
    {
93
      bread = read(b, 0, b.length);
94
      if (bread > 0)
95
        skipped += bread;
96
    }
97
    while (bread != -1 && skipped < n);
98
    return skipped;
99
  }
100
101
  public int available() throws IOException
102
  {
103
    if (closed)
104
      return 0;
105
    int rc = (int) Math.min(chunkSize, Integer.MAX_VALUE);
106
    return Math.min(rc, in.available());
107
  }
108
109
  protected long getChunked() throws IOException
110
  {
111
    //StringBuffer buf= new StringBuffer(1024);
112
    byte[] buf = new byte[maxCharLong + 2];
113
    int bufsz = 0;
114
    chunkSize = -1L;
115
    int c = -1;
116
    do
117
    {
118
      c = in.read();
119
      if (c > -1)
120
      {
121
        if (c != '\r' && c != '\n' && c != ' ' && c != '\t')
122
        {
123
          buf[bufsz++] = ((byte) c);
124
        }
125
      }
126
    }
127
    while (c > -1 && (c != '\n' || bufsz == 0) && bufsz < buf.length);
128
    if (c < 0)
129
    {
130
      closed = true;
131
    }
132
    String sbuf = new String(buf, 0, bufsz);
133
    if (bufsz > maxCharLong)
134
    {
135
      closed = true;
136
      throw new IOException("Chunked input stream failed to receive valid chunk size:" + sbuf);
137
    }
138
    try
139
    {
140
      chunkSize = Long.parseLong(sbuf, 16);
141
    }
142
    catch (NumberFormatException ne)
143
    {
144
      closed = true;
145
      throw new IOException("'" + sbuf + "' " + ne.getMessage());
146
    }
147
    if (chunkSize < 1L)
148
      closed = true;
149
    if (chunkSize != 0L && c < 0)
150
    {
151
      //If chunk size is zero try and be tolerant that there maybe no cr or lf
152
      // at the end.
153
      throw new IOException("HTTP Chunked stream closed in middle of chunk.");
154
    }
155
    if (chunkSize < 0L)
156
      throw new IOException("HTTP Chunk size received " + chunkSize + " is less than zero.");
157
    return chunkSize;
158
  }
159
160
  public void close() throws IOException
161
  {
162
    synchronized (this)
163
    {
164
      if (closed)
165
        return;
166
      closed = true;
167
    }
168
    byte[] b = new byte[1024];
169
    int bread = -1;
170
    do
171
    {
172
      bread = read(b, 0, b.length);
173
    }
174
    while (bread != -1);
175
  }
176
177
  /*
178
   * public void mark(int readlimit)
179
   * {
180
   * }
181
   */
182
183
  public void reset() throws IOException
184
  {
185
    throw new IOException("Don't support marked streams");
186
  }
187
188
  public boolean markSupported()
189
  {
190
    return false;
191
  }
192
}
(-)wsexplorer-src/org/eclipse/wst/ws/internal/explorer/platform/wsdl/transport/HTTPException.java (-56 lines)
Removed Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2004, 2005 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport;
12
13
import java.util.Map;
14
15
public class HTTPException extends RuntimeException
16
{
17
  /**
18
	 * Comment for <code>serialVersionUID</code>
19
	 */
20
	private static final long serialVersionUID = 3256438105900134961L;
21
private int statusCode;
22
  private String statusMessage;
23
  private Map headers;
24
  
25
  public HTTPException(int statusCode, String statusMessage, Map headers)
26
  {
27
    super(statusMessage);
28
    this.statusCode = statusCode;
29
    this.statusMessage = statusMessage;
30
    this.headers = headers;
31
  }
32
  
33
  public int getStatusCode()
34
  {
35
    return statusCode;
36
  }
37
  
38
  public String getStatusMessage()
39
  {
40
    return statusMessage;
41
  }
42
  
43
  public Map getHeaders()
44
  {
45
    return headers;
46
  }
47
  
48
  public String getHeader(String key)
49
  {
50
    Object value = headers.get(key);
51
    if (value != null)
52
      return value.toString();
53
    else
54
      return null;
55
  }
56
}
(-)wsexplorer-src/org/eclipse/wst/ws/internal/explorer/platform/wsdl/transport/HTTPTransport.java (-616 lines)
Removed Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2004, 2006 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * 
8
 * Contributors:
9
 * IBM Corporation - initial API and implementation
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
12
 * 20060131   125777 jesper@selskabet.org - Jesper S Moller
13
 * 20060222   118019 andyzhai@ca.ibm.com - Andy Zhai
14
 * 20060222   128564 jesper@selskabet.org - Jesper S Moller
15
 * 20060823    99034 makandre@ca.ibm.com - Andrew Mak, WSE support for basic-authenticating firewalls
16
 *******************************************************************************/
17
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport;
18
19
import java.io.BufferedReader;
20
import java.io.ByteArrayInputStream;
21
import java.io.ByteArrayOutputStream;
22
import java.io.IOException;
23
import java.io.InputStream;
24
import java.io.InputStreamReader;
25
import java.io.OutputStream;
26
import java.net.Socket;
27
import java.net.SocketTimeoutException;
28
import java.net.URL;
29
import java.net.UnknownHostException;
30
import java.util.Hashtable;
31
import javax.net.ssl.SSLSocketFactory;
32
import org.eclipse.wst.ws.internal.explorer.platform.util.XMLUtils;
33
import org.w3c.dom.Element;
34
import sun.misc.BASE64Encoder;
35
36
public class HTTPTransport
37
{
38
  private final String SYS_PROP_HTTPS_PROXY_HOST = "https.proxyHost";
39
  private final String SYS_PROP_HTTPS_PROXY_PORT = "https.proxyPort";
40
  private final String SYS_PROP_HTTPS_NON_PROXY_HOSTS = "https.nonProxyHosts";
41
  private final String SYS_PROP_HTTP_PROXY_HOST = "http.proxyHost";
42
  private final String SYS_PROP_HTTP_PROXY_PORT = "http.proxyPort";
43
  private final String SYS_PROP_HTTP_PROXY_USER_NAME = "http.proxyUserName";
44
  private final String SYS_PROP_HTTP_PROXY_PASSWORD = "http.proxyPassword";
45
  private final String SYS_PROP_HTTP_NON_PROXY_HOSTS = "http.nonProxyHosts";
46
  
47
  private final String HTTP_METHOD = "POST";
48
  private final String HTTP_CONNECT = "CONNECT";
49
  private final String HTTP_VERSION_1_0 = "HTTP/1.0";
50
  private final String HTTP_VERSION = "HTTP/1.1";
51
  private final String HTTP_HEADER_SOAP_ACTION = "SOAPAction";
52
  public static final String HTTP_HEADER_AUTH = "Authorization";
53
  public static final String HTTP_HEADER_WWW_AUTH = "WWW-Authenticate";
54
  private final String HTTP_HEADER_PROXY_AUTH = "Proxy-authorization";
55
  private final String HTTP_HEADER_COOKIE = "Cookie";
56
  private final String HTTP_HEADER_COOKIE2 = "Cookie2";
57
  private final String HTTP_HEADER_HOST = "Host";
58
  private final String HTTP_HEADER_CONTENT_TYPE = "Content-Type";
59
  public static final String HTTP_HEADER_CONTENT_LENGTH = "Content-Length";
60
  private final String HTTP_HEADER_ACCEPT = "Accept";
61
  private final String HTTP_HEADER_USER_AGENT = "User-Agent";
62
  private final String HTTP_HEADER_CACHE_CONTROL = "Cache-Control";
63
  private final String HTTP_HEADER_PRAGMA = "Pragma";
64
  private final String HTTP_HEADER_TRANSFER_ENCODEING = "Transfer-Encoding";
65
  private final String HTTP_HEADER_CONNECTION = "Connection";
66
  
67
  private final int HTTP_CODE_CONTINUE = 100;
68
  private final int HTTP_CODE_OK = 200;
69
  private final int HTTP_CODE_EXCEPTION = 300;
70
71
  private final String IBM_WEB_SERVICES_EXPLORER = "IBM Web Services Explorer";
72
  private final String TEXT_XML = "text/xml";
73
  private final String CONTENT_TYPE_VALUE = "text/xml; charset=utf-8";
74
  private final String ACCEPT_VALUE = "application/soap+xml, application/dime, multipart/related, text/*";
75
  public static final String BASIC = "Basic";
76
  private final String NO_CACHE = "no-cache";
77
  private final String CHUNKED = "chunked";
78
  private final String CLOSE = "close";
79
  private final String HTTPS = "https";
80
  private final char QUOTE = '\"';
81
  public static final char COLON = ':';
82
  private final char SPACE = ' ';
83
  private final char TAB = '\t';
84
  private final char R = '\r';
85
  private final char N = '\n';
86
  private final char ROOT = '/';
87
  private final String NEW_LINE = "\r\n";
88
  private final String EMPTY_STRING = "";
89
90
  private final int DEFAULT_HTTP_PORT = 80;
91
  private final int DEFAULT_HTTPS_PORT = 443;
92
  private final String DEFAULT_SOAP_ENCODING = "UTF-8";
93
  private final String DEFAULT_HTTP_HEADER_ENCODING = "iso-8859-1";
94
  private final boolean DEFAULT_CASE_SENSITIVE_FOR_HOST_NAME = false;
95
96
  private String httpBasicAuthUsername;
97
  private String httpBasicAuthPassword;
98
  private boolean maintainSession = false;
99
  private String cookie;
100
  private String cookie2;
101
  private HTTPResponse httpResponse;
102
103
  public String getHttpBasicAuthUsername()
104
  {
105
    return httpBasicAuthUsername;
106
  }
107
  
108
  public void setHttpBasicAuthUsername(String httpBasicAuthUsername)
109
  {
110
    this.httpBasicAuthUsername = httpBasicAuthUsername;
111
  }
112
  
113
  public String getHttpBasicAuthPassword()
114
  {
115
    return httpBasicAuthPassword;
116
  }
117
  
118
  public void setHttpBasicAuthPassword(String httpBasicAuthPassword)
119
  {
120
    this.httpBasicAuthPassword = httpBasicAuthPassword;
121
  }
122
123
  private String getMethod(URL url)
124
  {
125
    StringBuffer sb = new StringBuffer(HTTP_METHOD);
126
    sb.append(SPACE);
127
    String protocol = url.getProtocol();
128
    String httpProxyHost = System.getProperty(SYS_PROP_HTTP_PROXY_HOST);
129
    String httpsProxyHost = System.getProperty(SYS_PROP_HTTPS_PROXY_HOST);
130
    if (protocol.equalsIgnoreCase("http") && httpProxyHost != null && httpProxyHost.length() > 0)
131
    {
132
      sb.append(url.toString());
133
    }
134
    else if (protocol.equalsIgnoreCase("https") && httpsProxyHost != null && httpsProxyHost.length() > 0)
135
    {
136
      sb.append(url.toString());
137
    }
138
    else
139
    {
140
      String file = url.getFile();
141
      if (file != null && file.length() > 0)
142
        sb.append(file);
143
      else
144
        sb.append(ROOT);
145
    }
146
    sb.append(SPACE);
147
    sb.append(HTTP_VERSION);
148
    sb.append(NEW_LINE);
149
    return sb.toString();
150
  }
151
152
  private String getHost(URL url)
153
  {
154
    StringBuffer sb = new StringBuffer(HTTP_HEADER_HOST);
155
    sb.append(COLON);
156
    sb.append(SPACE);
157
    sb.append(url.getHost());
158
    sb.append(COLON);
159
    int port = url.getPort();
160
    if (port > 0)
161
      sb.append(String.valueOf(port));
162
    else if (url.getProtocol().equalsIgnoreCase(HTTPS))
163
      sb.append(DEFAULT_HTTPS_PORT);
164
    else
165
      sb.append(DEFAULT_HTTP_PORT);
166
    sb.append(NEW_LINE);
167
    return sb.toString();
168
  }
169
  
170
  private String getContentType()
171
  {
172
    return getHTTPHeader(HTTP_HEADER_CONTENT_TYPE, CONTENT_TYPE_VALUE);
173
  }
174
  
175
  private String getContentLength(byte[] payloadAsBytes)
176
  {
177
    return getHTTPHeader(HTTP_HEADER_CONTENT_LENGTH, String.valueOf(payloadAsBytes.length));
178
  }
179
180
  private String getSOAPAction(String soapAction)
181
  {
182
    StringBuffer sb = new StringBuffer(HTTP_HEADER_SOAP_ACTION);
183
    sb.append(COLON);
184
    sb.append(SPACE);
185
    sb.append(QUOTE);
186
    if (soapAction != null)
187
      sb.append(soapAction);
188
    sb.append(QUOTE);
189
    sb.append(NEW_LINE);
190
    return sb.toString();
191
  }
192
  
193
  private String getCookie()
194
  {
195
    if (maintainSession)
196
      return getHTTPHeader(HTTP_HEADER_COOKIE, cookie);
197
    else
198
      return EMPTY_STRING;
199
  }
200
  
201
  private String getCookie2()
202
  {
203
    if (maintainSession)
204
      return getHTTPHeader(HTTP_HEADER_COOKIE2, cookie2);
205
    else
206
      return EMPTY_STRING;
207
  }
208
  
209
  private String getWWWAuthentication()
210
  {
211
    if (httpBasicAuthUsername != null && httpBasicAuthPassword != null)
212
    {
213
      StringBuffer sb = new StringBuffer(httpBasicAuthUsername);
214
      sb.append(COLON);
215
      sb.append(httpBasicAuthPassword);
216
      BASE64Encoder encoder = new BASE64Encoder();
217
      String encodedUserNamePassword = encoder.encode(sb.toString().getBytes());
218
      sb.setLength(0);
219
      sb.append(HTTP_HEADER_AUTH);
220
      sb.append(COLON);
221
      sb.append(SPACE);
222
      sb.append(BASIC);
223
      sb.append(SPACE);
224
      sb.append(encodedUserNamePassword);
225
      sb.append(NEW_LINE);
226
      return sb.toString();
227
    }
228
    else
229
      return EMPTY_STRING;
230
  }
231
  
232
  private String getProxyAuthentication()
233
  {
234
    String proxyUserName = System.getProperty(SYS_PROP_HTTP_PROXY_USER_NAME);
235
    String proxyPassword = System.getProperty(SYS_PROP_HTTP_PROXY_PASSWORD);
236
    if (proxyUserName != null && proxyPassword != null)
237
    {
238
      StringBuffer sb = new StringBuffer(proxyUserName);
239
      sb.append(COLON);
240
      sb.append(proxyPassword);
241
      BASE64Encoder encoder = new BASE64Encoder();
242
      String encodedUserNamePassword = encoder.encode(sb.toString().getBytes());
243
      sb.setLength(0);
244
      sb.append(HTTP_HEADER_PROXY_AUTH);
245
      sb.append(COLON);
246
      sb.append(SPACE);
247
      sb.append(BASIC);
248
      sb.append(SPACE);
249
      sb.append(encodedUserNamePassword);
250
      sb.append(NEW_LINE);
251
      return sb.toString();
252
    }
253
    else
254
      return EMPTY_STRING;
255
  }
256
  
257
  private String getAccept()
258
  {
259
    return getHTTPHeader(HTTP_HEADER_ACCEPT, ACCEPT_VALUE);
260
  }
261
  
262
  private String getUserAgent()
263
  {
264
    return getHTTPHeader(HTTP_HEADER_USER_AGENT, IBM_WEB_SERVICES_EXPLORER);
265
  }
266
  
267
  private String getCacheControl()
268
  {
269
    return getHTTPHeader(HTTP_HEADER_CACHE_CONTROL, NO_CACHE);
270
  }
271
  
272
  private String getPragma()
273
  {
274
    return getHTTPHeader(HTTP_HEADER_PRAGMA, NO_CACHE);
275
  }
276
  
277
  private String getConnection()
278
  {
279
    return getHTTPHeader(HTTP_HEADER_CONNECTION, CLOSE);
280
  }
281
  
282
  private String getHTTPHeader(String key, String value)
283
  {
284
    if (value != null)
285
    {
286
      StringBuffer sb = new StringBuffer(key);
287
      sb.append(COLON);
288
      sb.append(SPACE);
289
      sb.append(value);
290
      sb.append(NEW_LINE);
291
      return sb.toString();
292
    }
293
    else
294
      return EMPTY_STRING;
295
  }
296
297
  public void send(URL url, String soapAction, String payload) throws UnknownHostException, IOException
298
  {
299
    byte[] payloadAsUTF8 = payload.getBytes(DEFAULT_SOAP_ENCODING);
300
       
301
    StringBuffer httpHeader = new StringBuffer();
302
    httpHeader.append(getMethod(url));
303
    httpHeader.append(getHost(url));
304
    httpHeader.append(getContentType());
305
    httpHeader.append(getContentLength(payloadAsUTF8));
306
    httpHeader.append(getAccept());
307
    httpHeader.append(getUserAgent());
308
    httpHeader.append(getCacheControl());
309
    httpHeader.append(getPragma());
310
    httpHeader.append(getSOAPAction(soapAction));
311
    httpHeader.append(getWWWAuthentication());
312
    httpHeader.append(getProxyAuthentication());
313
    httpHeader.append(getCookie());
314
    httpHeader.append(getCookie2());
315
    httpHeader.append(getConnection());
316
    httpHeader.append(NEW_LINE); // new line between the HTTP header and the payload
317
    Socket socket = buildSocket(url);
318
    InputStream is = socket.getInputStream();
319
    OutputStream os = socket.getOutputStream();
320
    os.write(httpHeader.toString().getBytes(DEFAULT_HTTP_HEADER_ENCODING));
321
    os.write(payloadAsUTF8);
322
    os.flush();
323
    httpResponse = new HTTPResponse();
324
    readHTTPResponseHeader(is, httpResponse);
325
    int code = httpResponse.getStatusCode();
326
    if (code == HTTP_CODE_CONTINUE)
327
    {
328
      httpResponse.reset();
329
      readHTTPResponseHeader(is, httpResponse);
330
    }
331
    readHTTPResponsePayload(is, httpResponse);
332
    os.close();
333
    is.close();
334
    socket.close();
335
    code = httpResponse.getStatusCode();
336
    String contentType = httpResponse.getHeader(HTTP_HEADER_CONTENT_TYPE.toLowerCase());
337
    if (code >= HTTP_CODE_EXCEPTION && (contentType == null || contentType.toLowerCase().indexOf(TEXT_XML.toLowerCase()) == -1))
338
      throw new HTTPException(code, httpResponse.getStatusMessage(), httpResponse.getHeaders());
339
  }
340
341
  private void readHTTPResponseHeader(InputStream is, HTTPResponse resp) throws IOException
342
  {
343
    byte b = 0;
344
    int len = 0;
345
    int colonIndex = -1;
346
    String key;
347
    String value;
348
    boolean readTooMuch = false;
349
    ByteArrayOutputStream baos;
350
    for (baos = new ByteArrayOutputStream(4096);;)
351
    {
352
      if (!readTooMuch)
353
        b = (byte)is.read();
354
      if (b == -1)
355
        break;
356
      readTooMuch = false;
357
      if ((b != R) && (b != N))
358
      {
359
        if ((b == COLON) && (colonIndex == -1))
360
          colonIndex = len;
361
        len++;
362
        baos.write(b);
363
      }
364
      else if (b == R)
365
        continue;
366
      else // b == N
367
      {
368
        if (len == 0)
369
          break;
370
        b = (byte)is.read();
371
        readTooMuch = true;
372
        // A space or tab at the begining of a line means the header continues.
373
        if ((b == SPACE) || (b == TAB))
374
          continue;
375
        baos.close();
376
        byte[] bArray = baos.toByteArray();
377
        baos.reset();
378
        if (colonIndex != -1)
379
        {
380
          key = new String(bArray, 0, colonIndex, DEFAULT_HTTP_HEADER_ENCODING);
381
          value = new String(bArray, colonIndex + 1, len - 1 - colonIndex, DEFAULT_HTTP_HEADER_ENCODING);
382
          colonIndex = -1;
383
        }
384
        else
385
        {
386
          key = new String(bArray, 0, len, DEFAULT_HTTP_HEADER_ENCODING);
387
          value = EMPTY_STRING;
388
        }
389
        if (!resp.isStatusSet())
390
        {
391
          // Reader status code
392
          int start = key.indexOf(SPACE) + 1;
393
          String s = key.substring(start).trim();
394
          int end = s.indexOf(SPACE);
395
          if (end != -1)
396
            s = s.substring(0, end);
397
          try
398
          {
399
            resp.setStatusCode(Integer.parseInt(s));
400
          }
401
          catch (NumberFormatException nfe)
402
          {
403
            resp.setStatusCode(-1);
404
          }
405
          resp.setStatusMessage(key.substring(start + end + 1));
406
        }
407
        else
408
          resp.addHeader(key.toLowerCase().trim(), value.trim());
409
        len = 0;
410
      }
411
    }
412
    baos.close();
413
  }
414
415
  private void readHTTPResponsePayload(InputStream is, HTTPResponse resp) throws IOException
416
  {
417
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
418
    try
419
    {
420
      byte b = (byte)is.read();
421
      while (b != -1)
422
      {
423
        baos.write(b);
424
        b = (byte)is.read();
425
      }
426
    }
427
    catch (SocketTimeoutException ste)
428
    {
429
    }
430
    baos.close();
431
    resp.setPayload(baos.toByteArray());
432
  }
433
434
  public BufferedReader receive()
435
  {
436
    if (httpResponse != null)
437
    {
438
      try
439
      {
440
        byte[] payload = httpResponse.getPayload();
441
        Element soapEnvelope = null;
442
        if (CHUNKED.equalsIgnoreCase(httpResponse.getHeader(HTTP_HEADER_TRANSFER_ENCODEING.toLowerCase())))
443
        {
444
          ByteArrayInputStream bais = new ByteArrayInputStream(payload);
445
          ChunkedInputStream cis = new ChunkedInputStream(bais);
446
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
447
          byte b;
448
          while ((b = (byte)cis.read()) != -1)
449
            baos.write(b);
450
          baos.close();
451
          cis.close();
452
          bais.close();
453
          soapEnvelope = XMLUtils.byteArrayToElement(baos.toByteArray(), false);
454
        }
455
        else
456
        {
457
          soapEnvelope = XMLUtils.byteArrayToElement(payload, false);
458
        }
459
        // remove XML namespace declaration
460
        if (soapEnvelope != null)
461
          return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(XMLUtils.serialize(soapEnvelope, true).getBytes(DEFAULT_SOAP_ENCODING)), DEFAULT_SOAP_ENCODING));
462
      }
463
      catch (Throwable t)
464
      {
465
      }
466
    }
467
    return null;
468
  }
469
470
  public Hashtable getHeaders()
471
  {
472
    Hashtable headers = new Hashtable();
473
    if (httpResponse != null)
474
      headers.putAll(httpResponse.getHeaders());
475
    return headers;
476
  }
477
478
  /**
479
   * Builds the first line of a connection request to the proxy server
480
   * 
481
   * @param url The URL that we want to ultimately connect to.
482
   * @return A string of the form "CONNECT &lt;hostname&gt;:&lt;port&gt; HTTP/1.0".
483
   */
484
  private StringBuffer getConnectMethod(URL url) {
485
	
486
	  StringBuffer sb = new StringBuffer(HTTP_CONNECT);
487
	  sb.append(SPACE);	  
488
	  sb.append(url.getHost());
489
	  sb.append(COLON);
490
	  sb.append(url.getPort());
491
	  sb.append(SPACE);
492
	  sb.append(HTTP_VERSION_1_0);
493
	  sb.append(NEW_LINE);
494
	  return sb;
495
  }
496
  
497
  /**
498
   * Construct a socket to the proxy server which be used to tunnel through.
499
   * 
500
   * @param url The URL that we want to ultimately connect to.
501
   * @param proxyHost The proxy host.
502
   * @param proxyPort The proxy port.
503
   * @return A connected socket to the proxy server. 
504
   * @throws IOException 
505
   */
506
  private Socket buildTunnelSocket(URL url, String proxyHost, int proxyPort) throws IOException {
507
508
	  StringBuffer httpHeader = new StringBuffer();
509
	  httpHeader.append(getConnectMethod(url));
510
	  httpHeader.append(getProxyAuthentication());       
511
	  httpHeader.append(NEW_LINE);
512
    
513
	  Socket tunnel = new Socket(proxyHost, proxyPort);
514
    
515
	  InputStream  is = tunnel.getInputStream();
516
	  OutputStream os = tunnel.getOutputStream();
517
    
518
	  os.write(httpHeader.toString().getBytes(DEFAULT_HTTP_HEADER_ENCODING));        
519
	  os.flush();
520
    
521
	  HTTPResponse httpResponse = new HTTPResponse();
522
	  readHTTPResponseHeader(is, httpResponse);
523
    
524
	  int code = httpResponse.getStatusCode();
525
526
	  // ensure we are successfully connected to the proxy
527
	  if (code != HTTP_CODE_OK)
528
		  throw new HTTPException(code, httpResponse.getStatusMessage(), httpResponse.getHeaders());
529
	  
530
	  return tunnel;
531
  }
532
  
533
  private Socket buildSocket(URL url) throws UnknownHostException, IOException
534
  {
535
    Socket s = null;
536
    String host = url.getHost();
537
    int port = url.getPort();
538
    String proxyHost = System.getProperty(SYS_PROP_HTTP_PROXY_HOST);
539
    int proxyPort = Integer.getInteger(SYS_PROP_HTTP_PROXY_PORT, DEFAULT_HTTP_PORT).intValue();
540
    
541
    String nonProxyHosts = System.getProperty(SYS_PROP_HTTP_NON_PROXY_HOSTS);
542
543
    //  String proxyUserName = System.getProperty(SYS_PROP_HTTP_PROXY_USER_NAME);
544
    //  String proxyPassword = System.getProperty(SYS_PROP_HTTP_PROXY_PASSWORD);
545
    if (url.getProtocol().equalsIgnoreCase(HTTPS))
546
    {
547
      proxyHost = System.getProperty(SYS_PROP_HTTPS_PROXY_HOST);
548
      proxyPort = Integer.getInteger(SYS_PROP_HTTPS_PROXY_PORT, DEFAULT_HTTPS_PORT).intValue();
549
      nonProxyHosts = System.getProperty(SYS_PROP_HTTPS_NON_PROXY_HOSTS);
550
551
      if (proxyHost != null && proxyHost.length() > 0 && !isHostInNonProxyHosts(host, nonProxyHosts, DEFAULT_CASE_SENSITIVE_FOR_HOST_NAME))
552
      {
553
        // SSL with proxy server
554
        Socket tunnel = buildTunnelSocket(url, proxyHost, proxyPort);       
555
        s = ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(tunnel, host, port, true);    	  
556
      }
557
      else
558
        s = SSLSocketFactory.getDefault().createSocket(host, (port > 0 ? port : DEFAULT_HTTPS_PORT));
559
      // Removing dependency on soap.jar
560
      //  s = SSLUtils.buildSSLSocket(host, (port > 0 ? port : DEFAULT_HTTPS_PORT), proxyHost, proxyPort);
561
      // TODO:
562
      // Build an SSL socket that supports proxyUser and proxyPassword,
563
      // as demonstrated in the following (original) line of code:
564
      //  s = SSLUtils.buildSSLSocket(host, (port > 0 ? port : DEFAULT_HTTPS_PORT), proxyHost, proxyPort, proxyUserName, proxyPassword);
565
    }
566
    else if (proxyHost != null && proxyHost.length() > 0 && !isHostInNonProxyHosts(host, nonProxyHosts, DEFAULT_CASE_SENSITIVE_FOR_HOST_NAME))
567
      s = new Socket(proxyHost, proxyPort);
568
    else
569
      s = new Socket(host, (port > 0 ? port : DEFAULT_HTTP_PORT));
570
    return s;
571
  }
572
  
573
  private boolean isHostInNonProxyHosts(String host, String nonProxyHosts, boolean caseSensitive)
574
  {
575
  	if (caseSensitive) return host.matches(createPatternFromString(nonProxyHosts));
576
  	else return host.toLowerCase().matches(createPatternFromString(nonProxyHosts.toLowerCase()));  
577
  }
578
  
579
  /*
580
   * This method is used to generate a valid regular expression for a 
581
   * normal java String used in the proxy mechanism. 
582
   * For example, the http.nonProxyHosts contains following String: 
583
   * "192.168.2.*|localhost|*.ibm.com" . It would be 
584
   * transformed into: "192\.168\.2\.\w*|localhost|\w*\.ibm\.com"
585
   * Thus, following host string would match above pattern:
586
   * 192.168.2.5 192.168.2. 192.168.2.666 192.168.2.w
587
   * localhost
588
   * torolab.ibm.com .ibm.com 123.ibm.com
589
   * 
590
   * Two transformations are done:
591
   * 1. replace all "." into "\." As in regular expression, '.' represents 
592
   *    any charater.  "\.' represents the real character '.'
593
   * 2. In order to get the real meaning of "*" used in property 
594
   *    http.nonProxyHosts, "\w*" is used to replace "*"
595
   *    "\w" represent a word character: [a-zA-Z_0-9]
596
   *    
597
   * Restriction:
598
   * The validity of address is not checked. 
599
   * (192.168.2.555 and 192.168.2.com are OK)
600
   * 
601
   * TODO check whether * occurs in address or hostname.
602
   * if it occuus in address representation, replace "*" with "\d*"
603
   * and check: value < 256 ?
604
   */
605
  private String createPatternFromString(String str) 
606
  {
607
    /* This is the same as following more understandable way:
608
	 * return str.replace(".", "\\.").replace("*", "\\w*");
609
	 * But, replace(CharSequence target, CharSequence replacement) can only be 
610
	 * supported after j2se 1.5, on the other hand, 
611
	 * replaceAll(String regex, String replacement) can be supported before 
612
	 * j2se 1.5.
613
	 */
614
    return str == null ? null : str.replaceAll("\\.", "\\.").replaceAll("\\*", "\\w*");
615
  }
616
}
(-)wsexplorer-src/org/eclipse/wst/ws/internal/explorer/platform/wsdl/transport/HTTPResponse.java (-91 lines)
Removed Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2004, 2005 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport;
12
13
import java.util.Hashtable;
14
import java.util.Map;
15
16
public class HTTPResponse
17
{
18
  private boolean statusSet;
19
  private int statusCode;
20
  private String statusMessage;
21
  private Hashtable headers;
22
  private byte[] payload;
23
24
  public HTTPResponse()
25
  {
26
    reset();
27
  }
28
29
  public void reset()
30
  {
31
    statusSet = false;
32
    statusCode = -1;
33
    statusMessage = null;
34
    if (headers != null)
35
      headers.clear();
36
    else
37
      headers = new Hashtable();
38
    payload = new byte[0];
39
  }
40
41
  public boolean isStatusSet()
42
  {
43
    return statusSet;
44
  }
45
46
  public int getStatusCode()
47
  {
48
    return statusCode;
49
  }
50
51
  public void setStatusCode(int statusCode)
52
  {
53
    statusSet = true;
54
    this.statusCode = statusCode;
55
  }
56
57
  public String getStatusMessage()
58
  {
59
    return statusMessage;
60
  }
61
62
  public void setStatusMessage(String statusMessage)
63
  {
64
    this.statusMessage = statusMessage;
65
  }
66
67
  public void addHeader(String key, String value)
68
  {
69
    headers.put(key, value);
70
  }
71
72
  public String getHeader(String key)
73
  {
74
    return (String) headers.get(key);
75
  }
76
77
  public Map getHeaders()
78
  {
79
    return headers;
80
  }
81
82
  public byte[] getPayload()
83
  {
84
    return payload;
85
  }
86
87
  public void setPayload(byte[] payload)
88
  {
89
    this.payload = payload;
90
  }
91
}
(-)wsexplorer-properties/wsdl.properties (-1 / +7 lines)
Lines 6-12 Link Here
6
# http://www.eclipse.org/legal/epl-v10.html
6
# http://www.eclipse.org/legal/epl-v10.html
7
#
7
#
8
# Contributors:
8
# Contributors:
9
#     IBM Corporation - initial API and implementation
9
# IBM Corporation - initial API and implementation
10
# yyyymmdd bug      Email and other contact information
11
# -------- -------- -----------------------------------------------------------
12
# 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
10
###############################################################################
13
###############################################################################
11
14
12
title=WSDL
15
title=WSDL
Lines 160-162 Link Here
160
MSG_ERROR_MIN_OCCURS_VIOLATION=IWAB0391E Minimum occurance is reached.
163
MSG_ERROR_MIN_OCCURS_VIOLATION=IWAB0391E Minimum occurance is reached.
161
MSG_ERROR_CANNOT_MOVE_FIRST_ELEMENT_UP=IWAB0392E Selected element is already the first in the group.
164
MSG_ERROR_CANNOT_MOVE_FIRST_ELEMENT_UP=IWAB0392E Selected element is already the first in the group.
162
MSG_ERROR_CANNOT_MOVE_LAST_ELEMENT_DOWN=IWAB0393E Selected element is already the last in the group.
165
MSG_ERROR_CANNOT_MOVE_LAST_ELEMENT_DOWN=IWAB0393E Selected element is already the last in the group.
166
167
# SOAP transport messages
168
MSG_ERROR_NO_SUITABLE_TRANSPORT=Failed to invoke operation, a suitable transport extension was not found.
(-)wsexplorer/uddi/forms/authentication_table.jsp (-1 / +1 lines)
Lines 79-85 Link Here
79
      <td><input type="text" id="<%=tableContainerId+"_input_user_id"%>" name="<%=UDDIActionInputs.QUERY_INPUT_ADVANCED_USERID%>" value="<%=HTMLUtils.charactersToHTMLEntitiesStrict(username)%>" class="textenter"></td>
79
      <td><input type="text" id="<%=tableContainerId+"_input_user_id"%>" name="<%=UDDIActionInputs.QUERY_INPUT_ADVANCED_USERID%>" value="<%=HTMLUtils.charactersToHTMLEntitiesStrict(username)%>" class="textenter"></td>
80
    </tr>
80
    </tr>
81
    <tr>
81
    <tr>
82
      <td class="labels" height=30 valign="bottom"><label for="<%=tableContainerId+"_input_password"%>"><%=uddiPerspective.getMessage("FORM_LABEL_PASSWORD")%></td></label>
82
      <td class="labels" height=30 valign="bottom"><label for="<%=tableContainerId+"_input_password"%>"><%=uddiPerspective.getMessage("FORM_LABEL_PASSWORD")%></label></td>
83
    </tr>
83
    </tr>
84
    <tr>
84
    <tr>
85
      <td><input type="password" id="<%=tableContainerId+"_input_password"%>" name="<%=UDDIActionInputs.QUERY_INPUT_ADVANCED_PASSWORD%>" value="<%=HTMLUtils.charactersToHTMLEntitiesStrict(password)%>" class="textenter"></td>
85
      <td><input type="password" id="<%=tableContainerId+"_input_password"%>" name="<%=UDDIActionInputs.QUERY_INPUT_ADVANCED_PASSWORD%>" value="<%=HTMLUtils.charactersToHTMLEntitiesStrict(password)%>" class="textenter"></td>
(-)META-INF/MANIFEST.MF (-1 / +2 lines)
Lines 11-17 Link Here
11
Export-Package: org.eclipse.wst.ws.internal.explorer;x-internal:=true,
11
Export-Package: org.eclipse.wst.ws.internal.explorer;x-internal:=true,
12
 org.eclipse.wst.ws.internal.explorer.favorites;x-internal:=true,
12
 org.eclipse.wst.ws.internal.explorer.favorites;x-internal:=true,
13
 org.eclipse.wst.ws.internal.explorer.plugin;x-internal:=true,
13
 org.eclipse.wst.ws.internal.explorer.plugin;x-internal:=true,
14
 org.eclipse.wst.ws.internal.explorer.popup;x-internal:=true
14
 org.eclipse.wst.ws.internal.explorer.popup;x-internal:=true,
15
 org.eclipse.wst.ws.internal.explorer.transport;x-internal:=true
15
Require-Bundle: org.eclipse.core.runtime;bundle-version="[3.2.0,4.0.0)",
16
Require-Bundle: org.eclipse.core.runtime;bundle-version="[3.2.0,4.0.0)",
16
 org.eclipse.core.resources;bundle-version="[3.2.0,3.4.0)",
17
 org.eclipse.core.resources;bundle-version="[3.2.0,3.4.0)",
17
 org.eclipse.help.appserver;bundle-version="[3.1.100,3.2.0)",
18
 org.eclipse.help.appserver;bundle-version="[3.1.100,3.2.0)",
(-)wsexplorer/wsdl/forms/WSDLServiceDetailsForm.jsp (-1 lines)
Lines 74-79 Link Here
74
<%
74
<%
75
   }
75
   }
76
%>
76
%>
77
</script>
78
</body>
77
</body>
79
</html>
78
</html>
(-)wsexplorer/wsdl/forms/FragmentsSoapView.jsp (-128 / +57 lines)
Lines 13-18 Link Here
13
 * 20060222   127443 jesper@selskabet.org - Jesper S Moller
13
 * 20060222   127443 jesper@selskabet.org - Jesper S Moller
14
 * 20060726   144824 mahutch@ca.ibm.com - Mark Hutchinson
14
 * 20060726   144824 mahutch@ca.ibm.com - Mark Hutchinson
15
 * 20070305   117034 makandre@ca.ibm.com - Andrew Mak, Web Services Explorer should support SOAP Headers
15
 * 20070305   117034 makandre@ca.ibm.com - Andrew Mak, Web Services Explorer should support SOAP Headers
16
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
16
 *******************************************************************************/
17
 *******************************************************************************/
17
%>
18
%>
18
<%@ page contentType="text/html; charset=UTF-8" import="org.eclipse.wst.ws.internal.explorer.platform.wsdl.perspective.*,
19
<%@ page contentType="text/html; charset=UTF-8" import="org.eclipse.wst.ws.internal.explorer.platform.wsdl.perspective.*,
Lines 22-27 Link Here
22
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.util.*,
23
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.util.*,
23
                                                        org.eclipse.wst.ws.internal.explorer.platform.constants.*,
24
                                                        org.eclipse.wst.ws.internal.explorer.platform.constants.*,
24
                                                        org.eclipse.wst.ws.internal.explorer.platform.util.*,
25
                                                        org.eclipse.wst.ws.internal.explorer.platform.util.*,
26
                                                        org.eclipse.wst.ws.internal.explorer.transport.*,
25
                                                        org.eclipse.wst.wsdl.binding.soap.SOAPHeader,
27
                                                        org.eclipse.wst.wsdl.binding.soap.SOAPHeader,
26
                                                        org.w3c.dom.*,
28
                                                        org.w3c.dom.*,
27
                                                        javax.wsdl.*,
29
                                                        javax.wsdl.*,
Lines 34-119 Link Here
34
<%
36
<%
35
   WSDLPerspective wsdlPerspective = controller.getWSDLPerspective();
37
   WSDLPerspective wsdlPerspective = controller.getWSDLPerspective();
36
   WSDLOperationElement operElement = (WSDLOperationElement)(wsdlPerspective.getNodeManager().getSelectedNode().getTreeElement());
38
   WSDLOperationElement operElement = (WSDLOperationElement)(wsdlPerspective.getNodeManager().getSelectedNode().getTreeElement());
37
   Operation oper = operElement.getOperation();
39
   ISOAPTransport soapTransport = operElement.getSOAPTransportProvider().newTransport();
38
   Hashtable soapEnvelopeNamespaceTable = new Hashtable();
40
   ISOAPMessage soapMessage = soapTransport.newMessage(operElement.getMessageContext());
39
   SoapHelper.addDefaultSoapEnvelopeNamespaces(soapEnvelopeNamespaceTable);
41
   operElement.setPropertyAsObject(WSDLModelConstants.PROP_SOAP_REQUEST_TMP, soapMessage);
40
   
42
   
41
   Iterator it = operElement.getSOAPHeaders().iterator();
43
   Hashtable soapEnvelopeNamespaceTable = new Hashtable(soapMessage.getNamespaceTable());      
42
   StringBuffer sourceContentHeader = new StringBuffer();
43
   String cachedSourceContent = operElement.getPropertyAsString(WSDLModelConstants.PROP_SOURCE_CONTENT_HEADER);
44
   if (cachedSourceContent != null)   
45
     sourceContentHeader.append(cachedSourceContent);        
46
   else
47
   {
48
     while (it.hasNext())
49
     {
50
       SOAPHeader soapHeader = (SOAPHeader)it.next();
51
       IXSDFragment frag = operElement.getHeaderFragment(soapHeader);
52
       Element[] instanceDocuments = frag.genInstanceDocumentsFromParameterValues(!operElement.isUseLiteral(), soapEnvelopeNamespaceTable, XMLUtils.createNewDocument(null));
53
       for (int i = 0; i < instanceDocuments.length; i++)
54
       {
55
    	 String serializedFragment = XMLUtils.serialize(instanceDocuments[i], true);
56
		 if (serializedFragment == null)
57
		 {
58
			 // On Some JRE's (Sun java 5) elements with an attribute with the xsi
59
			 // prefix do not serialize properly because the namespace can not
60
			 // be found so the string returned comes back as null. To workaround
61
			 // this problem try adding in the namespace declaration attribute
62
			 // and retry the serialization (bug 144824)			 
63
			 instanceDocuments[i].setAttribute("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance");
64
			 serializedFragment = XMLUtils.serialize(instanceDocuments[i], true);
65
		 }
66
    	 
67
    	 sourceContentHeader.append(serializedFragment);
68
         sourceContentHeader.append(HTMLUtils.LINE_SEPARATOR);
69
       }     
70
     }
71
   }
72
   
44
   
73
   it = operElement.getOrderedBodyParts().iterator();
45
   String cachedHeaderContent = operElement.getPropertyAsString(WSDLModelConstants.PROP_SOURCE_CONTENT_HEADER);
74
   StringBuffer sourceContent = new StringBuffer();
46
   String cachedBodyContent = operElement.getPropertyAsString(WSDLModelConstants.PROP_SOURCE_CONTENT);
75
   cachedSourceContent = operElement.getPropertyAsString(WSDLModelConstants.PROP_SOURCE_CONTENT);
47
   
76
   if (cachedSourceContent != null)
48
   // if either header or body has been cached, need to ensure namespace table is updated
77
   {
49
   // from the cached copy
78
     sourceContent.append(cachedSourceContent);
50
   if (cachedHeaderContent != null || cachedBodyContent != null) {
79
     String[] nsDeclarations = (String[])operElement.getPropertyAsObject(WSDLModelConstants.PROP_SOURCE_CONTENT_NAMESPACE);
51
	   if (SOAPMessageUtils.decodeNamespaceTable(soapEnvelopeNamespaceTable, operElement))
80
     if (nsDeclarations != null)
52
		   soapMessage.setNamespaceTable(soapEnvelopeNamespaceTable);
81
     {
82
       for (int i = 0; i < nsDeclarations.length; i++)
83
       {
84
         String[] prefix_ns = SoapHelper.decodeNamespaceDeclaration(nsDeclarations[i]);
85
         if (!soapEnvelopeNamespaceTable.contains(prefix_ns[1]))
86
           soapEnvelopeNamespaceTable.put(prefix_ns[1], prefix_ns[0]);
87
       }
88
     }
89
   }
53
   }
90
   else
54
	            
91
   {
55
   String headerContent;
92
     while (it.hasNext())
56
   String bodyContent;
93
     {
57
   
94
       Part part = (Part)it.next();
58
   if (cachedHeaderContent != null)
95
       IXSDFragment frag = operElement.getFragment(part);
59
       headerContent = cachedHeaderContent;
96
       Element[] instanceDocuments = frag.genInstanceDocumentsFromParameterValues(!operElement.isUseLiteral(), soapEnvelopeNamespaceTable, XMLUtils.createNewDocument(null));
60
   else {
97
       for (int i = 0; i < instanceDocuments.length; i++)
61
	   try {
98
       {
62
	       SOAPMessageUtils.setHeaderContentFromModel(soapEnvelopeNamespaceTable, operElement, soapMessage);
99
    	 String serializedFragment = XMLUtils.serialize(instanceDocuments[i], true);
63
	       
100
		 if (serializedFragment == null)
64
	       // ensure namespace table updated in message before serialize operation
101
		 {
65
	       soapMessage.setNamespaceTable(soapEnvelopeNamespaceTable);
102
			 // On Some JRE's (Sun java 5) elements with an attribute with the xsi
66
	       headerContent = soapTransport.newSerializer().serialize(ISOAPMessage.HEADER_CONTENT, soapMessage);
103
			 // prefix do not serialize properly because the namespace can not
67
	   }
104
			 // be found so the string returned comes back as null. To workaround
68
	   catch (Exception e) {
105
			 // this problem try adding in the namespace declaration attribute
69
		   headerContent = "";
106
			 // and retry the serialization (bug 144824)			 
70
	   }
107
			 instanceDocuments[i].setAttribute("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance");
108
			 serializedFragment = XMLUtils.serialize(instanceDocuments[i], true);
109
		 }
110
    	 
111
    	 sourceContent.append(serializedFragment);
112
         sourceContent.append(HTMLUtils.LINE_SEPARATOR);
113
       }     
114
     }
115
   }
71
   }
116
72
   
73
   if (cachedBodyContent != null)
74
	   bodyContent = cachedBodyContent;
75
   else {
76
	   try {
77
	       SOAPMessageUtils.setBodyContentFromModel(soapEnvelopeNamespaceTable, operElement, soapMessage);
78
	       
79
	       // ensure namespace table updated in message before serialize operation
80
	       soapMessage.setNamespaceTable(soapEnvelopeNamespaceTable);
81
	       bodyContent = soapTransport.newSerializer().serialize(ISOAPMessage.BODY_CONTENT, soapMessage);
82
	   }
83
	   catch (Exception e) {
84
		   bodyContent = "";
85
	   }
86
   }      
87
   
88
   // cache the namespace table
117
   Enumeration enm = soapEnvelopeNamespaceTable.keys();
89
   Enumeration enm = soapEnvelopeNamespaceTable.keys();
118
   while (enm.hasMoreElements())
90
   while (enm.hasMoreElements())
119
   {
91
   {
Lines 129-136 Link Here
129
  <tr>
101
  <tr>
130
    <td height=30 valign="bottom" class="labels">
102
    <td height=30 valign="bottom" class="labels">
131
<%
103
<%
132
    Document doc = XMLUtils.createNewDocument(null);
104
	Element soapEnvelopeElement = soapMessage.getEnvelope(false);
133
    Element soapEnvelopeElement = SoapHelper.createSoapEnvelopeElement(doc,soapEnvelopeNamespaceTable);
134
    StringBuffer header = new StringBuffer("<");
105
    StringBuffer header = new StringBuffer("<");
135
    header.append(soapEnvelopeElement.getTagName());
106
    header.append(soapEnvelopeElement.getTagName());
136
    NamedNodeMap attributes = soapEnvelopeElement.getAttributes();
107
    NamedNodeMap attributes = soapEnvelopeElement.getAttributes();
Lines 163-170 Link Here
163
</table>
134
</table>
164
<%
135
<%
165
    }
136
    }
166
137
    
167
    Element soapHeaderElement = SoapHelper.createSoapHeaderElement(doc);
138
    Element soapHeaderElement = soapMessage.getHeader(false);
168
    header.setLength(0);
139
    header.setLength(0);
169
    header.append('<').append(soapHeaderElement.getTagName());
140
    header.append('<').append(soapHeaderElement.getTagName());
170
    attributes = soapHeaderElement.getAttributes();
141
    attributes = soapHeaderElement.getAttributes();
Lines 226-232 Link Here
226
      <img width="16" height="16" src="<%=response.encodeURL(controller.getPathWithContext("images/space.gif"))%>">
197
      <img width="16" height="16" src="<%=response.encodeURL(controller.getPathWithContext("images/space.gif"))%>">
227
    </td>
198
    </td>
228
    <td width="100%">
199
    <td width="100%">
229
      <textarea id="soap_header_content" name="<%=FragmentConstants.SOURCE_CONTENT_HEADER%>" class="textareaenter"><%=HTMLUtils.charactersToHTMLEntitiesStrict(sourceContentHeader.toString())%></textarea>
200
      <textarea id="soap_header_content" name="<%=FragmentConstants.SOURCE_CONTENT_HEADER%>" class="textareaenter"><%=HTMLUtils.charactersToHTMLEntitiesStrict(headerContent)%></textarea>
230
    </td>
201
    </td>
231
  </tr>
202
  </tr>
232
</table>
203
</table>
Lines 245-251 Link Here
245
  </tr>
216
  </tr>
246
</table>
217
</table>
247
<%
218
<%
248
    Element soapBodyElement = SoapHelper.createSoapBodyElement(doc);
219
    Element soapBodyElement = soapMessage.getBody(false);
249
    header.setLength(0);
220
    header.setLength(0);
250
    header.append('<').append(soapBodyElement.getTagName());
221
    header.append('<').append(soapBodyElement.getTagName());
251
    attributes = soapBodyElement.getAttributes();
222
    attributes = soapBodyElement.getAttributes();
Lines 287-337 Link Here
287
258
288
    Element wrapperElement = null;
259
    Element wrapperElement = null;
289
    if (!operElement.isDocumentStyle())
260
    if (!operElement.isDocumentStyle())
290
    {
261
    {      
291
      // Must be RPC style.
262
      // Generate an RPC style wrapper element.      
292
      String encodingNamespaceURI = null;
263
      wrapperElement = (Element) soapBodyElement.getFirstChild();
293
      /*
294
       * WS-I: In a rpc-literal SOAP binding, the serialized child element of the 
295
       * soap:Body element consists of a wrapper element, whose namespace is the value 
296
       * of the namespace attribute of the soapbind:body element and whose local name is 
297
       * either the name of the operation or the name of the operation suffixed 
298
       * with "Response". The namespace attribute is required, as opposed to being 
299
       * optional, to ensure that the children of the soap:Body element are namespace-
300
       * qualified.
301
       */
302
      BindingOperation bindingOperation = operElement.getBindingOperation();
303
      if (bindingOperation != null)
304
      {
305
        BindingInput bindingInput = bindingOperation.getBindingInput();
306
        if (bindingInput != null)
307
        {
308
          List extElements = bindingInput.getExtensibilityElements();
309
          for (Iterator extElementsIt = extElements.iterator(); extElementsIt.hasNext();)
310
          {
311
            ExtensibilityElement extElement = (ExtensibilityElement)extElementsIt.next();
312
            if (extElement instanceof SOAPBody)
313
            {
314
              encodingNamespaceURI = ((SOAPBody)extElement).getNamespaceURI();
315
              break;
316
            }
317
          }
318
        }
319
      }
320
      // If the namespace of the soapbind:body element is not set, get it from the operation element
321
      if (encodingNamespaceURI == null)
322
        encodingNamespaceURI = operElement.getEncodingNamespace();
323
      // If the namespace of the operation element is not set, get it from the definition element
324
      if (encodingNamespaceURI == null)
325
      {
326
        WSDLBindingElement bindingElement = (WSDLBindingElement)operElement.getParentElement();
327
        WSDLServiceElement serviceElement = (WSDLServiceElement)bindingElement.getParentElement();
328
        WSDLElement wsdlElement = (WSDLElement)serviceElement.getParentElement();
329
        Definition definition = wsdlElement.getDefinition();
330
        encodingNamespaceURI = definition.getTargetNamespace();
331
      }
332
      // Generate an RPC style wrapper element.
333
      String encodingStyle = (operElement.isUseLiteral() ? null : operElement.getEncodingStyle());
334
      wrapperElement = SoapHelper.createRPCWrapperElement(doc,soapEnvelopeNamespaceTable,encodingNamespaceURI,oper.getName(),encodingStyle);
335
      header.setLength(0);
264
      header.setLength(0);
336
      header.append('<').append(wrapperElement.getTagName());
265
      header.append('<').append(wrapperElement.getTagName());
337
      attributes = wrapperElement.getAttributes();
266
      attributes = wrapperElement.getAttributes();
Lines 398-404 Link Here
398
      <img width=<%=sourceContentIndentationImageWidth%> height=16 src="<%=response.encodeURL(controller.getPathWithContext("images/space.gif"))%>">
327
      <img width=<%=sourceContentIndentationImageWidth%> height=16 src="<%=response.encodeURL(controller.getPathWithContext("images/space.gif"))%>">
399
    </td>
328
    </td>
400
    <td width="100%">
329
    <td width="100%">
401
      <textarea id="soap_body_content" name="<%=FragmentConstants.SOURCE_CONTENT%>" class="bigtextareaenter"><%=HTMLUtils.charactersToHTMLEntitiesStrict(sourceContent.toString())%></textarea>
330
      <textarea id="soap_body_content" name="<%=FragmentConstants.SOURCE_CONTENT%>" class="bigtextareaenter"><%=HTMLUtils.charactersToHTMLEntitiesStrict(bodyContent)%></textarea>
402
    </td>
331
    </td>
403
  </tr>
332
  </tr>
404
</table>
333
</table>
(-)wsexplorer/wsdl/forms/ReadOnlyFragmentsFormView.jsp (-157 / +45 lines)
Lines 11-16 Link Here
11
 * yyyymmdd bug      Email and other contact information
11
 * yyyymmdd bug      Email and other contact information
12
 * -------- -------- -----------------------------------------------------------
12
 * -------- -------- -----------------------------------------------------------
13
 * 20070305   117034 makandre@ca.ibm.com - Andrew Mak, Web Services Explorer should support SOAP Headers
13
 * 20070305   117034 makandre@ca.ibm.com - Andrew Mak, Web Services Explorer should support SOAP Headers
14
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
14
 *******************************************************************************/
15
 *******************************************************************************/
15
%>
16
%>
16
<%@ page contentType="text/html; charset=UTF-8" import="org.eclipse.wst.ws.internal.explorer.platform.wsdl.perspective.*,
17
<%@ page contentType="text/html; charset=UTF-8" import="org.eclipse.wst.ws.internal.explorer.platform.wsdl.perspective.*,
Lines 19-28 Link Here
19
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.xsd.*,
20
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.xsd.*,
20
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.fragment.*,
21
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.fragment.*,
21
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.fragment.impl.*,
22
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.fragment.impl.*,
23
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.util.*,
22
                                                        org.eclipse.wst.ws.internal.explorer.platform.constants.*,
24
                                                        org.eclipse.wst.ws.internal.explorer.platform.constants.*,
23
                                                        org.eclipse.wst.ws.internal.explorer.platform.perspective.Node,
25
                                                        org.eclipse.wst.ws.internal.explorer.platform.perspective.Node,
24
                                                        org.eclipse.wst.ws.internal.explorer.platform.perspective.*,
26
                                                        org.eclipse.wst.ws.internal.explorer.platform.perspective.*,
25
                                                        org.eclipse.wst.ws.internal.explorer.platform.util.*,
27
                                                        org.eclipse.wst.ws.internal.explorer.platform.util.*,
28
                                                        org.eclipse.wst.ws.internal.explorer.transport.*,
26
                                                        org.eclipse.wst.wsdl.binding.soap.SOAPHeader,
29
                                                        org.eclipse.wst.wsdl.binding.soap.SOAPHeader,
27
                                                        org.w3c.dom.*,
30
                                                        org.w3c.dom.*,
28
                                                        javax.wsdl.*,
31
                                                        javax.wsdl.*,
Lines 32-167 Link Here
32
<jsp:useBean id="controller" class="org.eclipse.wst.ws.internal.explorer.platform.perspective.Controller" scope="session"/>
35
<jsp:useBean id="controller" class="org.eclipse.wst.ws.internal.explorer.platform.perspective.Controller" scope="session"/>
33
<jsp:useBean id="fragID" class="java.lang.StringBuffer" scope="request"/>
36
<jsp:useBean id="fragID" class="java.lang.StringBuffer" scope="request"/>
34
<jsp:useBean id="nodeID" class="java.lang.StringBuffer" scope="request"/>
37
<jsp:useBean id="nodeID" class="java.lang.StringBuffer" scope="request"/>
35
36
<%!
37
private Element soapResponse_ = null;
38
private boolean hasSOAPHeaders = false;
39
40
private void checkSOAPHeaders() {
41
	
42
	NodeList nl = soapResponse_.getElementsByTagNameNS(FragmentConstants.URI_SOAP_ENV, FragmentConstants.QNAME_LOCAL_NAME_HEADER);    
43
	if (nl.getLength() == 0)
44
		return;
45
	
46
	Element soapHeader = (Element) nl.item(0);
47
	NodeList nodes = soapHeader.getChildNodes();
48
	
49
	for (int i = 0; i < nodes.getLength(); i++) {
50
	    if (nodes.item(i) instanceof Element) {
51
	    	hasSOAPHeaders = true;
52
	    	return;
53
	    }
54
	}
55
}
56
57
private Element[] parseSOAPResponse(SOAPMessageQueue soapMessageQueue, WSDLOperationElement operElement)
58
{
59
  String messages = soapMessageQueue.getMessagesFromList();
60
  try
61
  {
62
    soapResponse_ = XMLUtils.stringToElement(messages, true);
63
    checkSOAPHeaders();
64
    NodeList nl = soapResponse_.getElementsByTagNameNS(FragmentConstants.URI_SOAP_ENV, FragmentConstants.QNAME_LOCAL_NAME_BODY);
65
    if (nl.getLength() > 0)
66
    {
67
      Element soapBody = (Element)nl.item(0);
68
      NodeList soapFault = soapBody.getElementsByTagNameNS(FragmentConstants.URI_SOAP_ENV, FragmentConstants.QNAME_LOCAL_NAME_FAULT);
69
      if (soapFault.getLength() > 0)
70
        return new Element[0];
71
      NodeList instanceList;
72
      if (operElement.isDocumentStyle())
73
        instanceList = soapBody.getChildNodes();
74
      else
75
      {
76
        NodeList rpcWrapper = soapBody.getElementsByTagNameNS("*", operElement.getOperation().getOutput().getMessage().getQName().getLocalPart());
77
78
        /*
79
        * HACK - Some of the web services out on the internet do not
80
        * set their RPC wrapper properly.  It should be set to the output
81
        * message name of the selected operation.  The hack is to
82
        * assume the first element inside the body element is the
83
        * RPC wrapper.
84
        */
85
        if (rpcWrapper.getLength() <= 0)
86
          rpcWrapper = soapBody.getElementsByTagNameNS("*", "*");
87
88
        if (rpcWrapper.getLength() > 0)
89
          instanceList = rpcWrapper.item(0).getChildNodes();
90
        else
91
          return null;
92
      }
93
      return fixSOAPResponse(instanceList, operElement);
94
    }
95
  }
96
  catch (Throwable t) {
97
    t.printStackTrace();
98
  }
99
  return null;
100
}
101
102
/*
103
* HACK - The root element tag name of the instance document
104
* is ambiguous.  It lands on a very grey area between the SOAP
105
* spec and the WSDL spec.  The two specs do not explicitly define
106
* that the root element tag name must match the name of the
107
* WSDL part.  The hack is to treat elements with different tag names
108
* as instances of the WSDL part.
109
*/
110
private Element[] fixSOAPResponse(NodeList instanceList, WSDLOperationElement operElement)
111
{
112
  Vector instanceVector = new Vector();
113
  for (int i = 0; i < instanceList.getLength(); i++)
114
  {
115
    Object object = instanceList.item(i);
116
    if (object != null && (object instanceof Element))
117
      instanceVector.add(object);
118
  }
119
  Element[] instanceDocuments = new Element[instanceVector.size()];
120
  Operation oper = operElement.getOperation();
121
  Map partsMap = oper.getOutput().getMessage().getParts();
122
  if (partsMap.size() == 1)
123
  {
124
    Iterator it = partsMap.values().iterator();
125
    IXSDFragment frag = operElement.getFragment((Part)it.next(), false);
126
    for (int i = 0; i < instanceVector.size(); i++)
127
    {
128
      Element element = (Element)instanceVector.get(i);
129
      if (!element.getTagName().equals(frag.getName()))
130
      {
131
        Document doc = element.getOwnerDocument();
132
        NodeList children = element.getChildNodes();
133
        NamedNodeMap attributes = element.getAttributes();
134
        element = doc.createElement(frag.getName());
135
        for (int j = 0; j < children.getLength(); j++)
136
        {
137
          if (children.item(j) != null)
138
          {
139
            element.appendChild(children.item(j));
140
            // When you append a node from one element to another,
141
            // the original element will lose its reference to this node,
142
            // therefore, the size of the node list will decrease by 1.
143
            j--;
144
          }
145
        }
146
        for (int j = 0; j < attributes.getLength(); j++)
147
        {
148
          Object attr = attributes.item(j);
149
          if (attr != null && (attr instanceof Attr))
150
          {
151
            Attr attribute = (Attr)attr;
152
            element.setAttribute(attribute.getName(), attribute.getValue());
153
          }
154
        }
155
      }
156
      instanceDocuments[i] = element;
157
    }
158
  }
159
  else
160
    instanceVector.copyInto(instanceDocuments);
161
  return instanceDocuments;
162
}
163
%>
164
165
<%
38
<%
166
WSDLPerspective wsdlPerspective = controller.getWSDLPerspective();
39
WSDLPerspective wsdlPerspective = controller.getWSDLPerspective();
167
wsdlPerspective.setStatusContentType(WSDLPerspective.STATUS_CONTENT_RESULT_FORM);
40
wsdlPerspective.setStatusContentType(WSDLPerspective.STATUS_CONTENT_RESULT_FORM);
Lines 184-197 Link Here
184
}
57
}
185
else
58
else
186
{
59
{
60
  ISOAPMessage soapMessage = (ISOAPMessage) operElement.getPropertyAsObject(WSDLModelConstants.PROP_SOAP_RESPONSE);
61
  Element[] headerContent = soapMessage.getHeaderContent();;
62
  Element[] bodyContent   = soapMessage.getBodyContent();
63
  
187
  boolean cached = ((Boolean)operElement.getPropertyAsObject(WSDLActionInputs.SOAP_RESPONSE_CACHED)).booleanValue();
64
  boolean cached = ((Boolean)operElement.getPropertyAsObject(WSDLActionInputs.SOAP_RESPONSE_CACHED)).booleanValue();
188
  Element[] instanceDocuments = null;
65
189
  if (!cached)
66
  if (soapMessage.getBody(false) == null) // body is mandatory
190
  {
191
    SOAPMessageQueue soapMessageQueue = wsdlPerspective.getSOAPResponseQueue();
192
    instanceDocuments = parseSOAPResponse(soapMessageQueue, operElement);
193
  }
194
  if (!cached && !hasSOAPHeaders && instanceDocuments == null)
195
  {
67
  {
196
  %>
68
  %>
197
    <table width="95%" border=0 cellpadding=6 cellspacing=0>
69
    <table width="95%" border=0 cellpadding=6 cellspacing=0>
Lines 203-209 Link Here
203
    </table>
75
    </table>
204
  <%
76
  <%
205
  }
77
  }
206
  else if (!cached && !hasSOAPHeaders && instanceDocuments.length <= 0)
78
  else if ((headerContent == null || headerContent.length == 0) && 
79
		   (soapMessage.getFault() != null || bodyContent == null || bodyContent.length == 0))
207
  {
80
  {
208
  %>
81
  %>
209
    <table width="95%" border=0 cellpadding=6 cellspacing=0>
82
    <table width="95%" border=0 cellpadding=6 cellspacing=0>
Lines 237-267 Link Here
237
	
110
	
238
	<div id="<%=headerDivId%>" class="fragarea">
111
	<div id="<%=headerDivId%>" class="fragarea">
239
	<%
112
	<%
240
	if (cached || hasSOAPHeaders) {
113
	boolean hasSOAPHeaders = false;
241
		hasSOAPHeaders = false;
114
	if (headerContent != null && headerContent.length > 0) {		
115
		
242
		Iterator it = operElement.getSOAPHeaders(false).iterator();
116
		Iterator it = operElement.getSOAPHeaders(false).iterator();
243
		while (it.hasNext()) {
117
		int start = 0;
244
			SOAPHeader soapHeader = (SOAPHeader) it.next();			
118
		while (it.hasNext() && start < headerContent.length) {
245
			String ns = soapHeader.getEPart().getElementDeclaration().getTargetNamespace();			
119
			SOAPHeader soapHeader = (SOAPHeader) it.next();									
246
			IXSDFragment frag = operElement.getHeaderFragment(soapHeader, false);
120
			IXSDFragment fragment = operElement.getHeaderFragment(soapHeader, false);
247
			
121
			
248
			if (!cached) {
122
			if (!cached) {				
249
				NodeList nl = soapResponse_.getElementsByTagNameNS(ns, frag.getName());
123
				int pos = SOAPMessageUtils.findFirstMatchingElement(
250
				if (nl.getLength() == 0)
124
					soapHeader.getEPart(),
125
					headerContent,
126
					soapMessage.getNamespaceTable(),
127
					fragment.getName(),
128
					start);
129
				
130
				if (pos == -1)
251
					continue;
131
					continue;
252
				
132
				
253
				Element element = (Element) nl.item(0);				
133
				Element element = headerContent[pos];
254
				if (!frag.setParameterValuesFromInstanceDocuments(new Element[] { element }))
134
				start = pos + 1;
135
				
136
				if (!fragment.setParameterValuesFromInstanceDocuments(new Element[] { element }))
255
					continue;
137
					continue;
256
			}
138
			}
257
			else if (!frag.validateAllParameterValues())
139
			else if (!fragment.validateAllParameterValues())
258
				continue;
140
				continue;
259
			
141
			
260
			hasSOAPHeaders = true;				
142
			hasSOAPHeaders = true;				
261
			fragID.delete(0, fragID.length());
143
			fragID.delete(0, fragID.length());
262
			fragID.append(frag.getID());
144
			fragID.append(fragment.getID());
263
			%>
145
			%>
264
			<jsp:include page="<%=frag.getReadFragment()%>" flush="true"/>
146
			<jsp:include page="<%=fragment.getReadFragment()%>" flush="true"/>
265
			<%  
147
			<%  
266
		}		
148
		}		
267
	}
149
	}
Lines 294-301 Link Here
294
	
176
	
295
	<div id="<%=bodyDivId%>" class="fragarea">
177
	<div id="<%=bodyDivId%>" class="fragarea">
296
	<%	
178
	<%	
297
	if (cached || (instanceDocuments != null && instanceDocuments.length > 0)) {
179
	boolean hasSOAPBody = false;
298
			
180
	if (bodyContent != null && bodyContent.length > 0) {				
181
		
299
	    Map partsMap = oper.getOutput().getMessage().getParts();
182
	    Map partsMap = oper.getOutput().getMessage().getParts();
300
	    Iterator it = partsMap.values().iterator();
183
	    Iterator it = partsMap.values().iterator();
301
	    Hashtable uriReferences = null;
184
	    Hashtable uriReferences = null;
Lines 307-317 Link Here
307
	        if (!operElement.isUseLiteral() && (fragment instanceof ISOAPEncodingWrapperFragment))
190
	        if (!operElement.isUseLiteral() && (fragment instanceof ISOAPEncodingWrapperFragment))
308
	        {
191
	        {
309
	          if (uriReferences == null)
192
	          if (uriReferences == null)
310
	            uriReferences = SOAPEncodingWrapperFragment.parseURIReferences(soapResponse_, true);
193
	            uriReferences = SOAPEncodingWrapperFragment.parseURIReferences(soapMessage.getEnvelope(true), true);
311
	          ((ISOAPEncodingWrapperFragment)fragment).setURIReferences(uriReferences);
194
	          ((ISOAPEncodingWrapperFragment)fragment).setURIReferences(uriReferences);
312
	        }
195
	        }
313
	        fragment.setParameterValuesFromInstanceDocuments(instanceDocuments);
196
	        if (!fragment.setParameterValuesFromInstanceDocuments(bodyContent))
197
	        	continue;
314
	      }
198
	      }
199
	      else if (!fragment.validateAllParameterValues())
200
			continue;
201
			
202
		  hasSOAPBody = true;				
315
	      fragID.delete(0, fragID.length());
203
	      fragID.delete(0, fragID.length());
316
	      fragID.append(fragment.getID());
204
	      fragID.append(fragment.getID());
317
	      %>
205
	      %>
Lines 320-326 Link Here
320
	    }
208
	    }
321
	    operElement.setPropertyAsObject(WSDLActionInputs.SOAP_RESPONSE_CACHED, new Boolean(true));
209
	    operElement.setPropertyAsObject(WSDLActionInputs.SOAP_RESPONSE_CACHED, new Boolean(true));
322
	}
210
	}
323
	else {
211
	if (!hasSOAPBody) {
324
		%>
212
		%>
325
		<table width="95%" border=0 cellpadding=6 cellspacing=0>
213
		<table width="95%" border=0 cellpadding=6 cellspacing=0>
326
	      <tr>
214
	      <tr>
(-)wsexplorer/uddi/category_content.jsp (+1 lines)
Lines 74-79 Link Here
74
        <%=uddiPerspective.getMessage("MSG_INFO_NO_CATEGORY_DATA",categoryModel.getDisplayName())%>
74
        <%=uddiPerspective.getMessage("MSG_INFO_NO_CATEGORY_DATA",categoryModel.getDisplayName())%>
75
      </td>
75
      </td>
76
    </tr>
76
    </tr>
77
    <tr>
77
      <td height=10 valign="bottom">&nbsp;</td>
78
      <td height=10 valign="bottom">&nbsp;</td>
78
    </tr>
79
    </tr>
79
    <tr>
80
    <tr>
(-)wsexplorer/wsdl/actions/InvokeWSDLSOAPOperationSourceActionJSP.jsp (-5 / +8 lines)
Lines 1-23 Link Here
1
<%
1
<%
2
/*******************************************************************************
2
/*******************************************************************************
3
 * Copyright (c) 2001, 2004 IBM Corporation and others.
3
 * Copyright (c) 2001, 2007 IBM Corporation and others.
4
 * All rights reserved. This program and the accompanying materials
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
8
 * 
9
 * Contributors:
9
 * Contributors:
10
 *     IBM Corporation - initial API and implementation
10
 * IBM Corporation - initial API and implementation
11
 * yyyymmdd bug      Email and other contact information
12
 * -------- -------- -----------------------------------------------------------
13
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
11
 *******************************************************************************/
14
 *******************************************************************************/
12
%>
15
%>
13
<%@ page contentType="text/html; charset=UTF-8" import="org.eclipse.wst.ws.internal.explorer.platform.wsdl.perspective.*,
16
<%@ page contentType="text/html; charset=UTF-8" import="org.eclipse.wst.ws.internal.explorer.platform.wsdl.perspective.*,
14
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.*,
17
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.*,
15
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.actions.*,
18
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.actions.*,
16
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.WSDLActionInputs,
19
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.WSDLActionInputs,
17
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport.HTTPException,
18
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport.HTTPTransport,
20
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport.HTTPTransport,
19
                                                        org.eclipse.wst.ws.internal.explorer.platform.perspective.*,
21
                                                        org.eclipse.wst.ws.internal.explorer.platform.perspective.*,
20
                                                        org.eclipse.wst.ws.internal.explorer.platform.constants.*,
22
                                                        org.eclipse.wst.ws.internal.explorer.platform.constants.*,
23
                                                        org.eclipse.wst.ws.internal.explorer.transport.HTTPTransportException,
21
                                                        sun.misc.BASE64Decoder,
24
                                                        sun.misc.BASE64Decoder,
22
                                                        javax.servlet.http.HttpServletResponse,
25
                                                        javax.servlet.http.HttpServletResponse,
23
                                                        javax.wsdl.*"%>
26
                                                        javax.wsdl.*"%>
Lines 128-134 Link Here
128
        </html>
131
        </html>
129
<%
132
<%
130
      }
133
      }
131
      catch (HTTPException httpe)
134
      catch (HTTPTransportException httpe)
132
      {
135
      {
133
        int code = httpe.getStatusCode();
136
        int code = httpe.getStatusCode();
134
        if (code == HttpServletResponse.SC_UNAUTHORIZED)
137
        if (code == HttpServletResponse.SC_UNAUTHORIZED)
Lines 148-154 Link Here
148
          MessageQueue messageQueue = wsdlPerspective.getMessageQueue();
151
          MessageQueue messageQueue = wsdlPerspective.getMessageQueue();
149
          messageQueue.addMessage(controller.getMessage("MSG_ERROR_UNEXPECTED"));
152
          messageQueue.addMessage(controller.getMessage("MSG_ERROR_UNEXPECTED"));
150
          messageQueue.addMessage(String.valueOf(code));
153
          messageQueue.addMessage(String.valueOf(code));
151
          messageQueue.addMessage(httpe.getStatusMessage());
154
          messageQueue.addMessage(httpe.getMessage());
152
          %>
155
          %>
153
          <jsp:include page="/wsdl/scripts/wsdlpanes.jsp" flush="true"/>
156
          <jsp:include page="/wsdl/scripts/wsdlpanes.jsp" flush="true"/>
154
          <html>
157
          <html>
(-)wsexplorer/wsdl/actions/InvokeWSDLSOAPOperationFormActionJSP.jsp (-5 / +8 lines)
Lines 1-13 Link Here
1
<%
1
<%
2
/*******************************************************************************
2
/*******************************************************************************
3
 * Copyright (c) 2001, 2004 IBM Corporation and others.
3
 * Copyright (c) 2001, 2007 IBM Corporation and others.
4
 * All rights reserved. This program and the accompanying materials
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
8
 * 
9
 * Contributors:
9
 * Contributors:
10
 *     IBM Corporation - initial API and implementation
10
 * IBM Corporation - initial API and implementation
11
 * yyyymmdd bug      Email and other contact information
12
 * -------- -------- -----------------------------------------------------------
13
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
11
 *******************************************************************************/
14
 *******************************************************************************/
12
%>
15
%>
13
<%@ page contentType="text/html; charset=UTF-8" import="org.eclipse.wst.ws.internal.explorer.platform.wsdl.actions.*,
16
<%@ page contentType="text/html; charset=UTF-8" import="org.eclipse.wst.ws.internal.explorer.platform.wsdl.actions.*,
Lines 15-22 Link Here
15
                                                        org.eclipse.wst.ws.internal.explorer.platform.perspective.MessageQueue,
18
                                                        org.eclipse.wst.ws.internal.explorer.platform.perspective.MessageQueue,
16
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.WSDLActionInputs,
19
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.WSDLActionInputs,
17
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.perspective.WSDLPerspective,
20
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.perspective.WSDLPerspective,
18
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport.HTTPException,
19
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport.HTTPTransport,
21
                                                        org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport.HTTPTransport,
22
                                                        org.eclipse.wst.ws.internal.explorer.transport.HTTPTransportException,
20
                                                        sun.misc.BASE64Decoder,
23
                                                        sun.misc.BASE64Decoder,
21
                                                        javax.servlet.http.HttpServletResponse"%>
24
                                                        javax.servlet.http.HttpServletResponse"%>
22
25
Lines 96-102 Link Here
96
    </html>
99
    </html>
97
<%
100
<%
98
  }
101
  }
99
  catch (HTTPException httpe)
102
  catch (HTTPTransportException httpe)
100
  {
103
  {
101
    int code = httpe.getStatusCode();
104
    int code = httpe.getStatusCode();
102
    if (code == HttpServletResponse.SC_UNAUTHORIZED)
105
    if (code == HttpServletResponse.SC_UNAUTHORIZED)
Lines 116-122 Link Here
116
      MessageQueue messageQueue = wsdlPerspective.getMessageQueue();
119
      MessageQueue messageQueue = wsdlPerspective.getMessageQueue();
117
      messageQueue.addMessage(controller.getMessage("MSG_ERROR_UNEXPECTED"));
120
      messageQueue.addMessage(controller.getMessage("MSG_ERROR_UNEXPECTED"));
118
      messageQueue.addMessage(String.valueOf(code));
121
      messageQueue.addMessage(String.valueOf(code));
119
      messageQueue.addMessage(httpe.getStatusMessage());
122
      messageQueue.addMessage(httpe.getMessage());
120
      %>
123
      %>
121
        <jsp:include page="/wsdl/scripts/wsdlpanes.jsp" flush="true"/>
124
        <jsp:include page="/wsdl/scripts/wsdlpanes.jsp" flush="true"/>
122
        <html>
125
        <html>
(-)wsexplorer-src/org/eclipse/wst/ws/internal/explorer/platform/wsdl/fragment/impl/XSDFragment.java (-7 / +6 lines)
Lines 1-12 Link Here
1
/*******************************************************************************
1
/*******************************************************************************
2
 * Copyright (c) 2002, 2006 IBM Corporation and others.
2
 * Copyright (c) 2002, 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 * IBM Corporation - initial API and implementation
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
10
 *******************************************************************************/
13
 *******************************************************************************/
11
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.fragment.impl;
14
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.fragment.impl;
12
15
Lines 290-300 Link Here
290
          Node child = children.item(i);
293
          Node child = children.item(i);
291
          if (child != null)
294
          if (child != null)
292
          {
295
          {
293
            eCopy.appendChild(child);
296
        	  eCopy.appendChild(child.cloneNode(true));
294
            // When you append a node from one element to another,
295
            // the original element will lose its reference to this node,
296
            // therefore, the size of the node list will decrease by 1.
297
            i--;
298
          }
297
          }
299
        }
298
        }
300
        for (int j = 0; j < attributes.getLength(); j++)
299
        for (int j = 0; j < attributes.getLength(); j++)
(-)wsexplorer-src/org/eclipse/wst/ws/internal/explorer/platform/wsdl/fragment/impl/SOAPHeaderWrapperFragment.java (-10 / +7 lines)
Lines 10-15 Link Here
10
 * yyyymmdd bug      Email and other contact information
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070305   117034 makandre@ca.ibm.com - Andrew Mak, Web Services Explorer should support SOAP Headers
12
 * 20070305   117034 makandre@ca.ibm.com - Andrew Mak, Web Services Explorer should support SOAP Headers
13
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
13
 *******************************************************************************/
14
 *******************************************************************************/
14
15
15
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.fragment.impl;
16
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.fragment.impl;
Lines 17-22 Link Here
17
import java.net.URI;
18
import java.net.URI;
18
import java.net.URISyntaxException;
19
import java.net.URISyntaxException;
19
import java.util.Hashtable;
20
import java.util.Hashtable;
21
import java.util.Map;
20
import java.util.Vector;
22
import java.util.Vector;
21
23
22
import org.eclipse.wst.ws.internal.explorer.platform.util.MultipartFormDataException;
24
import org.eclipse.wst.ws.internal.explorer.platform.util.MultipartFormDataException;
Lines 187-209 Link Here
187
	}
189
	}
188
	
190
	
189
	/**
191
	/**
190
	 * Sets the values for this SOAP header given a hashtable of instance documents and a namespace table.
192
	 * Sets the values for this SOAP header given an instance document and a namespace table.
191
	 * 
193
	 * 
192
	 * @param instanceDocuments The hashtable of instance documents.  The key is the document's name with namespace prefix.
194
	 * @param instanceDocument The instance document.
193
	 * @param namespaceTable The namespace table.
195
	 * @param namespaceTable The namespace table.
194
	 * 
196
	 * 
195
	 * @return True if all values extracted from the instance document are valid.
197
	 * @return True if all values extracted from the instance document are valid.
196
	 */
198
	 */
197
	public boolean setParameterValuesFromInstanceDocuments(Hashtable instanceDocuments, Hashtable namespaceTable) {
199
	public boolean setParameterValuesFromInstanceDocument(Element instanceDocument, Map namespaceTable) {
198
		String tagName = ((XSDFragment) getXSDDelegationFragment()).getInstanceDocumentTagName(namespaceTable);
200
199
		Element instanceDocument = (Element) instanceDocuments.get(tagName);
200
		 
201
		if (instanceDocument == null)
202
			return false;
203
		 
204
		boolean valid = setParameterValuesFromInstanceDocuments(new Element[] { instanceDocument });		
201
		boolean valid = setParameterValuesFromInstanceDocuments(new Element[] { instanceDocument });		
205
		 
202
		 
206
		String prefix = getPrefixFromNamespaceURI(FragmentConstants.NS_URI_SOAP_ENV, namespaceTable) + FragmentConstants.COLON;
203
		String prefix = namespaceTable.get(FragmentConstants.NS_URI_SOAP_ENV) + FragmentConstants.COLON;
207
		 
204
		 
208
		String mustUnderstandValue = instanceDocument.getAttribute(prefix + MUST_UNDERSTAND);
205
		String mustUnderstandValue = instanceDocument.getAttribute(prefix + MUST_UNDERSTAND);
209
		if ("".equals(mustUnderstandValue))
206
		if ("".equals(mustUnderstandValue))
(-)wsexplorer/wsdl/fragment/XSDSimpleAtomicEnumFixWFragmentJSP.jsp (-2 / +1 lines)
Lines 42-48 Link Here
42
    <td class="labels" height=25 valign="bottom" align="left" nowrap>
42
    <td class="labels" height=25 valign="bottom" align="left" nowrap>
43
      <%=(xsdBuiltInType != null ? xsdBuiltInType.getName() : simpleType.getName())%>
43
      <%=(xsdBuiltInType != null ? xsdBuiltInType.getName() : simpleType.getName())%>
44
    </td>
44
    </td>
45
    <td>
46
      <% 
45
      <% 
47
      if(elementFragment != null && elementFragment.isNillable()){
46
      if(elementFragment != null && elementFragment.isNillable()){
48
        if(elementFragment.isNil()){
47
        if(elementFragment.isNil()){
Lines 57-63 Link Here
57
        }
56
        }
58
      }
57
      }
59
      %>
58
      %>
60
59
    <td>
61
<%
60
<%
62
   if (!frag.validateParameterValues(frag.getID()))
61
   if (!frag.validateParameterValues(frag.getID()))
63
   {
62
   {
(-)wsexplorer-src/org/eclipse/wst/ws/internal/explorer/platform/wsdl/datamodel/WSDLOperationElement.java (-5 / +47 lines)
Lines 10-15 Link Here
10
 * yyyymmdd bug      Email and other contact information
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070305   117034 makandre@ca.ibm.com - Andrew Mak, Web Services Explorer should support SOAP Headers
12
 * 20070305   117034 makandre@ca.ibm.com - Andrew Mak, Web Services Explorer should support SOAP Headers
13
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
13
 *******************************************************************************/
14
 *******************************************************************************/
14
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel;
15
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel;
15
16
Lines 21-26 Link Here
21
import javax.wsdl.Binding;
22
import javax.wsdl.Binding;
22
import javax.wsdl.BindingInput;
23
import javax.wsdl.BindingInput;
23
import javax.wsdl.BindingOperation;
24
import javax.wsdl.BindingOperation;
25
import javax.wsdl.Definition;
24
import javax.wsdl.Input;
26
import javax.wsdl.Input;
25
import javax.wsdl.Operation;
27
import javax.wsdl.Operation;
26
import javax.wsdl.Output;
28
import javax.wsdl.Output;
Lines 29-34 Link Here
29
import javax.wsdl.extensions.soap.SOAPBinding;
31
import javax.wsdl.extensions.soap.SOAPBinding;
30
import javax.wsdl.extensions.soap.SOAPBody;
32
import javax.wsdl.extensions.soap.SOAPBody;
31
import javax.wsdl.extensions.soap.SOAPOperation;
33
import javax.wsdl.extensions.soap.SOAPOperation;
34
import org.eclipse.wst.ws.internal.explorer.platform.perspective.TransportProviderRegistry;
32
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.BindingTypes;
35
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.BindingTypes;
33
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.FragmentConstants;
36
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.FragmentConstants;
34
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.fragment.IXSDFragment;
37
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.fragment.IXSDFragment;
Lines 36-41 Link Here
36
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.fragment.XSDToFragmentController;
39
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.fragment.XSDToFragmentController;
37
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.fragment.impl.SOAPHeaderWrapperFragment;
40
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.fragment.impl.SOAPHeaderWrapperFragment;
38
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.xsd.WSDLPartsToXSDTypeMapper;
41
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.xsd.WSDLPartsToXSDTypeMapper;
42
import org.eclipse.wst.ws.internal.explorer.transport.ISOAPTransportProvider;
43
import org.eclipse.wst.ws.internal.explorer.transport.MessageContext;
39
import org.eclipse.wst.wsdl.binding.soap.SOAPHeader;
44
import org.eclipse.wst.wsdl.binding.soap.SOAPHeader;
40
import org.eclipse.xsd.XSDNamedComponent;
45
import org.eclipse.xsd.XSDNamedComponent;
41
46
Lines 55-61 Link Here
55
  private String encodingStyle_;
60
  private String encodingStyle_;
56
  private String encodingNamespace_;
61
  private String encodingNamespace_;
57
62
58
  private Map headerCache = new Hashtable();
63
  private Map headerCache;
64
  
65
  private MessageContext messageContext = null;
66
  private ISOAPTransportProvider soapTransportProvider = null;  
59
  
67
  
60
  private final void gatherSoapInformation(WSDLBindingElement bindingElement,SOAPBinding soapBinding)
68
  private final void gatherSoapInformation(WSDLBindingElement bindingElement,SOAPBinding soapBinding)
61
  {
69
  {
Lines 116-121 Link Here
116
    setOperation(bindingElement,operation);
124
    setOperation(bindingElement,operation);
117
  }
125
  }
118
126
127
  private Definition getDefinition(WSDLBindingElement bindingElement) {
128
	  WSDLServiceElement serviceElement = (WSDLServiceElement) bindingElement.getParentElement();
129
      WSDLElement wsdlElement = (WSDLElement) serviceElement.getParentElement();
130
      return wsdlElement.getDefinition();
131
  }
132
  
133
  private void setMessageContext(WSDLBindingElement bindingElement) {
134
	  messageContext = new MessageContext();
135
	  messageContext.setDefinition(getDefinition(bindingElement));
136
	  messageContext.setBindingOperation(getBindingOperation(bindingElement));
137
	  messageContext.setBindingProtocol(bindingElement.getBindingExtensibilityElement());
138
	  messageContext.setDocumentStyle(isDocumentStyle_);
139
  }
140
  
141
  public MessageContext getMessageContext() {
142
	  return messageContext;
143
  }
144
  
145
  private void setSOAPTransportProvider(SOAPBinding soapBinding) {
146
	  	  
147
	  String namespaceURI = soapBinding.getElementType().getNamespaceURI();
148
	  String transportURI = soapBinding.getTransportURI();
149
	  	  
150
	  soapTransportProvider = TransportProviderRegistry.getInstance()
151
	  	.getSOAPTransportProvider(namespaceURI, transportURI);
152
  }
153
  
154
  public ISOAPTransportProvider getSOAPTransportProvider() {
155
	  return soapTransportProvider;
156
  }
157
  
119
  public void setOperation(WSDLBindingElement bindingElement,Operation operation) {
158
  public void setOperation(WSDLBindingElement bindingElement,Operation operation) {
120
    operation_ = operation;
159
    operation_ = operation;
121
    setDocumentation(operation.getDocumentationElement());
160
    setDocumentation(operation.getDocumentationElement());
Lines 127-132 Link Here
127
    {
166
    {
128
      case BindingTypes.SOAP:
167
      case BindingTypes.SOAP:
129
        gatherSoapInformation(bindingElement,(SOAPBinding)bindingExtensibilityElement);
168
        gatherSoapInformation(bindingElement,(SOAPBinding)bindingExtensibilityElement);
169
        setMessageContext(bindingElement);
170
        setSOAPTransportProvider((SOAPBinding) bindingExtensibilityElement);
171
        headerCache = new Hashtable();
130
      case BindingTypes.HTTP_GET:
172
      case BindingTypes.HTTP_GET:
131
      case BindingTypes.HTTP_POST:
173
      case BindingTypes.HTTP_POST:
132
      default:
174
      default:
Lines 255-261 Link Here
255
	else
297
	else
256
	  id.append(FragmentConstants.OUTPUT_ID).append(soapHeader.getMessage()).append(FragmentConstants.PART_TOKEN);
298
	  id.append(FragmentConstants.OUTPUT_ID).append(soapHeader.getMessage()).append(FragmentConstants.PART_TOKEN);
257
	
299
	
258
	return getFragment(part, id, isInput); // only wrap input header fragments
300
	return getFragment(part, id, true, isInput); // only wrap input header fragments
259
  }
301
  }
260
  
302
  
261
  public IXSDFragment getFragment(Part part) {
303
  public IXSDFragment getFragment(Part part) {
Lines 269-285 Link Here
269
    else
311
    else
270
      id.append(FragmentConstants.OUTPUT_ID);
312
      id.append(FragmentConstants.OUTPUT_ID);
271
313
272
	return getFragment(part, id, false);
314
	return getFragment(part, id, false, false);
273
  }
315
  }
274
  
316
  
275
  private IXSDFragment getFragment(Part part, StringBuffer id, boolean useSOAPHeaderWrapper) {
317
  private IXSDFragment getFragment(Part part, StringBuffer id, boolean isHeader, boolean useSOAPHeaderWrapper) {
276
    String partName = part.getName();
318
    String partName = part.getName();
277
    id.append(partName);
319
    id.append(partName);
278
    XSDToFragmentConfiguration config = new XSDToFragmentConfiguration();
320
    XSDToFragmentConfiguration config = new XSDToFragmentConfiguration();
279
    config.setIsWSDLPart(true);
321
    config.setIsWSDLPart(true);
280
    config.setWSDLPartName(partName);
322
    config.setWSDLPartName(partName);
281
    config.setXSDComponent(getSchema(part, id.toString()));
323
    config.setXSDComponent(getSchema(part, id.toString()));
282
    if (isDocumentStyle())
324
    if (isDocumentStyle() || isHeader)
283
      config.setStyle(FragmentConstants.STYLE_DOCUMENT);
325
      config.setStyle(FragmentConstants.STYLE_DOCUMENT);
284
    else
326
    else
285
      config.setStyle(FragmentConstants.STYLE_RPC);
327
      config.setStyle(FragmentConstants.STYLE_RPC);
(-)wsexplorer-src/org/eclipse/wst/ws/internal/explorer/platform/wsdl/util/SoapHelper.java (-138 lines)
Removed Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2002, 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * 
8
 * Contributors:
9
 * IBM Corporation - initial API and implementation
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070305   117034 makandre@ca.ibm.com - Andrew Mak, Web Services Explorer should support SOAP Headers
13
 *******************************************************************************/
14
15
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.util;
16
17
import java.util.Enumeration;
18
import java.util.Hashtable;
19
import org.apache.axis.Constants;
20
import org.eclipse.wst.ws.internal.explorer.platform.util.URLUtils;
21
import org.w3c.dom.Document;
22
import org.w3c.dom.Element;
23
24
public class SoapHelper
25
{
26
  private static Hashtable defaultSoapEnvelopeNamespaces_ = null;
27
  
28
  private static final void initDefaultSoapEnvelopeNamespaces()
29
  {
30
    defaultSoapEnvelopeNamespaces_ = new Hashtable();
31
    defaultSoapEnvelopeNamespaces_.put(Constants.URI_SOAP11_ENV,Constants.NS_PREFIX_SOAP_ENV);
32
    defaultSoapEnvelopeNamespaces_.put(Constants.URI_2001_SCHEMA_XSI,Constants.NS_PREFIX_SCHEMA_XSI);
33
    defaultSoapEnvelopeNamespaces_.put(Constants.URI_2001_SCHEMA_XSD,Constants.NS_PREFIX_SCHEMA_XSD);
34
  }
35
  
36
  public static final void addDefaultSoapEnvelopeNamespaces(Hashtable soapEnvelopeNamespaces)
37
  {
38
    if (defaultSoapEnvelopeNamespaces_ == null)
39
      initDefaultSoapEnvelopeNamespaces();
40
    Enumeration defaultSoapEnvelopeNamespaceURIs = defaultSoapEnvelopeNamespaces_.keys();
41
    while (defaultSoapEnvelopeNamespaceURIs.hasMoreElements())
42
    {
43
      String defaultSoapEnvelopeNamespaceURI = (String)defaultSoapEnvelopeNamespaceURIs.nextElement();
44
      soapEnvelopeNamespaces.put(defaultSoapEnvelopeNamespaceURI,(String)defaultSoapEnvelopeNamespaces_.get(defaultSoapEnvelopeNamespaceURI));
45
    }
46
  }
47
  
48
  public static final boolean isDefaultSoapEnvelopeNamespace(String namespaceURI,String namespacePrefix)
49
  {
50
    if (defaultSoapEnvelopeNamespaces_ == null)
51
      initDefaultSoapEnvelopeNamespaces();
52
    if (defaultSoapEnvelopeNamespaces_.get(namespaceURI) != null)
53
      return true;
54
    return false;
55
  }  
56
  
57
  public static final Element createSoapEnvelopeElement(Document doc,Hashtable soapEnvelopeNamespaceTable)
58
  {
59
    Element soapEnvelopeElement = doc.createElement("soapenv:Envelope");
60
    Enumeration e = soapEnvelopeNamespaceTable.keys();
61
    while (e.hasMoreElements())
62
    {
63
      String soapEnvelopeNamespaceURI = (String)e.nextElement();
64
      StringBuffer soapEnvelopeNamespaceAttr = new StringBuffer("xmlns:");
65
      soapEnvelopeNamespaceAttr.append((String)soapEnvelopeNamespaceTable.get(soapEnvelopeNamespaceURI));
66
      soapEnvelopeElement.setAttribute(soapEnvelopeNamespaceAttr.toString(),soapEnvelopeNamespaceURI);      
67
    }    
68
    return soapEnvelopeElement;
69
  }
70
  
71
  public static final Element createSoapHeaderElement(Document doc)
72
  {
73
    return doc.createElement("soapenv:Header");
74
  }
75
  
76
  public static final Element createSoapBodyElement(Document doc)
77
  {
78
    return doc.createElement("soapenv:Body");
79
  }
80
  
81
  public static final Element createRPCWrapperElement(Document doc,Hashtable soapEnvelopeNamespaceTable,String encodingNamespaceURI,String operationName, String encodingStyle)
82
  {
83
    int nsId = 0;
84
    StringBuffer wrapperElementName = new StringBuffer();
85
    String encodingNamespacePrefix = (String)soapEnvelopeNamespaceTable.get(encodingNamespaceURI);
86
    if (encodingNamespacePrefix != null)
87
      wrapperElementName.append(encodingNamespacePrefix);
88
    else
89
    {
90
      // Loop until we generate a unique prefix.
91
      do
92
      {
93
        wrapperElementName.setLength(0);
94
        wrapperElementName.append("ns").append(nsId);
95
        if (!soapEnvelopeNamespaceTable.containsValue(wrapperElementName.toString()))
96
          break;
97
        nsId++;
98
      } while (true);
99
    }    
100
    String wrapperElementNamePrefix = wrapperElementName.toString();
101
    wrapperElementName.append(':').append(operationName);
102
    Element wrapperElement = doc.createElement(wrapperElementName.toString());
103
    StringBuffer namespaceAttrName = new StringBuffer("xmlns:");
104
    namespaceAttrName.append(wrapperElementNamePrefix);
105
    wrapperElement.setAttribute(namespaceAttrName.toString(),encodingNamespaceURI);
106
    if (encodingStyle != null)
107
      wrapperElement.setAttribute("soapenv:encodingStyle",encodingStyle);
108
    return wrapperElement;
109
  }
110
111
  public static final String encodeNamespaceDeclaration(String prefix, String uri)
112
  {
113
    StringBuffer sb = new StringBuffer();
114
    sb.append(prefix);
115
    sb.append(" ");
116
    sb.append(uri);
117
    String result = URLUtils.encode(sb.toString());
118
    return result;
119
  }
120
121
  public static final String[] decodeNamespaceDeclaration(String s)
122
  {
123
    String sCopy = URLUtils.decode(s);
124
    int index = sCopy.indexOf(" ");
125
    String[] nsDecl = new String[2];
126
    if (index != -1)
127
    {
128
      nsDecl[0] = sCopy.substring(0, index);
129
      nsDecl[1] = sCopy.substring(index+1, sCopy.length());
130
    }
131
    else
132
    {
133
      nsDecl[0] = null;
134
      nsDecl[1] = sCopy;
135
    }
136
    return nsDecl;
137
  }
138
}
(-)wsexplorer/actions/WriteWSDLToWorkbenchActionJSP.jsp (-1 lines)
Lines 37-42 Link Here
37
<%
37
<%
38
   }
38
   }
39
%>
39
%>
40
</script>
41
</body>
40
</body>
42
</html> 
41
</html> 
(-)wsexplorer-src/org/eclipse/wst/ws/internal/explorer/platform/wsdl/constants/WSDLModelConstants.java (+6 lines)
Lines 10-15 Link Here
10
 * yyyymmdd bug      Email and other contact information
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070305   117034 makandre@ca.ibm.com - Andrew Mak, Web Services Explorer should support SOAP Headers
12
 * 20070305   117034 makandre@ca.ibm.com - Andrew Mak, Web Services Explorer should support SOAP Headers
13
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
13
 *******************************************************************************/
14
 *******************************************************************************/
14
15
15
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants;
16
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants;
Lines 29-32 Link Here
29
    public final static String PROP_SOURCE_CONTENT_HEADER = "propSourceContentHeader";
30
    public final static String PROP_SOURCE_CONTENT_HEADER = "propSourceContentHeader";
30
    public final static String PROP_SOURCE_CONTENT = "propSourceContent";
31
    public final static String PROP_SOURCE_CONTENT = "propSourceContent";
31
    public final static String PROP_SOURCE_CONTENT_NAMESPACE = "propSourceContentNS";
32
    public final static String PROP_SOURCE_CONTENT_NAMESPACE = "propSourceContentNS";
33
    
34
    // Transport
35
    public final static String PROP_SOAP_REQUEST_TMP = "propSOAPRequestTmp";
36
    public final static String PROP_SOAP_REQUEST = "propSOAPRequest";    
37
    public final static String PROP_SOAP_RESPONSE = "propSOAPResponse";
32
}
38
}
(-)src/org/eclipse/wst/ws/internal/explorer/platform/wsdl/transport/SOAPTransportProvider.java (+30 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 * IBM Corporation - initial API and implementation
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
13
 *******************************************************************************/
14
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport;
15
16
import org.eclipse.wst.ws.internal.explorer.transport.ISOAPTransport;
17
import org.eclipse.wst.ws.internal.explorer.transport.ISOAPTransportProvider;
18
19
/**
20
 * WSE's default implementation for ISOAPTransportProvider.
21
 */
22
public class SOAPTransportProvider implements ISOAPTransportProvider {	
23
	
24
	/* (non-Javadoc)
25
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPTransportProvider#newTransport()
26
	 */
27
	public ISOAPTransport newTransport() {
28
		return new SOAPTransport();		
29
	}
30
}
(-)src/org/eclipse/wst/ws/internal/explorer/platform/util/XMLUtils.java (+148 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2004, 2005 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.wst.ws.internal.explorer.platform.util;
12
13
import java.io.ByteArrayInputStream;
14
import java.io.ByteArrayOutputStream;
15
import java.io.IOException;
16
import java.io.UnsupportedEncodingException;
17
import javax.xml.parsers.DocumentBuilder;
18
import javax.xml.parsers.DocumentBuilderFactory;
19
import javax.xml.parsers.ParserConfigurationException;
20
import javax.xml.transform.OutputKeys;
21
import javax.xml.transform.Transformer;
22
import javax.xml.transform.TransformerFactory;
23
import javax.xml.transform.dom.DOMSource;
24
import javax.xml.transform.stream.StreamResult;
25
26
import org.w3c.dom.Document;
27
import org.w3c.dom.DocumentFragment;
28
import org.w3c.dom.Element;
29
import org.xml.sax.SAXException;
30
31
public final class XMLUtils
32
{
33
  public static final String UTF8_ENCODING = "UTF-8"; 
34
	
35
  /**
36
   * Serialize an XML Element into a String.
37
   * @param e Element to be serialized.
38
   * @param omitXMLDeclaration boolean representing whether or not to omit the XML declaration.
39
   * @return String representation of the XML document fragment.
40
   */
41
  public static final String serialize(Element e,boolean omitXMLDeclaration)
42
  {
43
    if (e != null)
44
    {
45
      try
46
      {
47
		DOMSource domSource = new DOMSource(e);
48
		Transformer serializer = TransformerFactory.newInstance().newTransformer();
49
		serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, ((omitXMLDeclaration) ? "yes" : "no"));
50
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
51
		serializer.setOutputProperty(OutputKeys.ENCODING, UTF8_ENCODING);
52
		serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
53
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
54
		serializer.transform(domSource, new	StreamResult(baos));
55
		baos.close();
56
		return new String(baos.toByteArray(), UTF8_ENCODING);
57
      }
58
      catch (Throwable t)
59
      {
60
      }
61
    }
62
    return null;
63
  }
64
    
65
  /**
66
   * Serialize an XML Element into a String.
67
   * @param df DocumentFragment to be serialized.
68
   * @param omitXMLDeclaration boolean representing whether or not to omit the XML declaration.
69
   * @return String representation of the XML document fragment.
70
   */  
71
  public static final String serialize(DocumentFragment df,boolean omitXMLDeclaration)
72
  {
73
    if (df != null)
74
    {
75
      try
76
      {
77
		DOMSource domSource = new DOMSource(df);
78
		Transformer serializer = TransformerFactory.newInstance().newTransformer();
79
		serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, ((omitXMLDeclaration) ? "yes" : "no"));
80
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
81
		serializer.setOutputProperty(OutputKeys.ENCODING, UTF8_ENCODING);
82
		serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
83
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
84
		serializer.transform(domSource, new	StreamResult(baos));
85
		baos.close();
86
		return new String(baos.toByteArray(), UTF8_ENCODING);
87
      }
88
      catch (Throwable t)
89
      {
90
      }
91
    }
92
    return null;
93
  }
94
  
95
  /**
96
   * Create a new XML Document.
97
   * @param docBuilder DocumentBuilder. Setting this to null will create a new DocumentBuilder.
98
   * @return Document
99
   */
100
  public static final Document createNewDocument(DocumentBuilder docBuilder) throws ParserConfigurationException
101
  {
102
    if (docBuilder == null)
103
    {
104
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
105
      factory.setNamespaceAware(false);
106
      factory.setValidating(false);
107
      docBuilder = factory.newDocumentBuilder();
108
    }
109
    Document doc = docBuilder.newDocument();
110
    return doc;
111
  }
112
113
  /**
114
   * Convert the String representation of an Element into an Element
115
   * @param String representation of an Element.
116
   * @return Element
117
   */
118
  public static Element stringToElement(String s) throws ParserConfigurationException, SAXException, UnsupportedEncodingException, IOException {
119
    return stringToElement(s, false);
120
  }
121
122
  /**
123
   * Convert the String representation of an Element into an Element
124
   * @param String representation of an Element.
125
   * @param boolean set whether the return Element should be namespace aware.
126
   * @return Element
127
   */
128
  public static Element stringToElement(String s, boolean namespaceAware) throws ParserConfigurationException, SAXException, UnsupportedEncodingException, IOException
129
  {
130
    return byteArrayToElement(s.getBytes(UTF8_ENCODING), namespaceAware);
131
  }
132
133
  /**
134
   * Convert the byte array representation of an Element into an Element
135
   * @param byte[] representation of an Element.
136
   * @param boolean set whether the return Element should be namespace aware.
137
   * @return Element
138
   */
139
  public static Element byteArrayToElement(byte[] b, boolean namespaceAware) throws ParserConfigurationException, SAXException, UnsupportedEncodingException, IOException
140
  {
141
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
142
    docBuilderFactory.setNamespaceAware(namespaceAware);
143
    docBuilderFactory.setValidating(false);
144
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
145
    Document doc = docBuilder.parse(new ByteArrayInputStream(b));
146
    return doc.getDocumentElement();
147
  }
148
}
(-)src/org/eclipse/wst/ws/internal/explorer/platform/wsdl/transport/SOAPMessageProcessor.java (+497 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 * IBM Corporation - initial API and implementation
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
13
 *******************************************************************************/
14
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport;
15
16
import java.io.IOException;
17
import java.util.Hashtable;
18
import java.util.Iterator;
19
import java.util.List;
20
import java.util.Map;
21
import java.util.Vector;
22
23
import javax.wsdl.Operation;
24
import javax.wsdl.Part;
25
import javax.wsdl.extensions.ExtensibilityElement;
26
import javax.wsdl.extensions.soap.SOAPBody;
27
import javax.xml.parsers.ParserConfigurationException;
28
29
import org.apache.axis.Constants;
30
import org.eclipse.wst.ws.internal.explorer.platform.util.XMLUtils;
31
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.util.SoapHelper;
32
import org.eclipse.wst.ws.internal.explorer.transport.IDeserializer;
33
import org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage;
34
import org.eclipse.wst.ws.internal.explorer.transport.ISerializer;
35
import org.eclipse.wst.ws.internal.explorer.transport.MessageContext;
36
import org.eclipse.wst.ws.internal.explorer.transport.TransportException;
37
import org.w3c.dom.Attr;
38
import org.w3c.dom.Document;
39
import org.w3c.dom.Element;
40
import org.w3c.dom.NamedNodeMap;
41
import org.w3c.dom.Node;
42
import org.w3c.dom.NodeList;
43
import org.xml.sax.SAXException;
44
45
/**
46
 * This class provides implementation for WSE default SOAP transport's ISerializer and IDeserializer.
47
 */
48
public class SOAPMessageProcessor implements ISerializer, IDeserializer {
49
	
50
	private static final String LITERAL = "literal";
51
	private static final String DEFAULT_SOAP_ENCODING = "UTF-8";	
52
	private static final String LINE_SEPARATOR = System.getProperties().getProperty("line.separator");
53
	
54
	/*
55
	 * Constructor.
56
	 */
57
	SOAPMessageProcessor() {}
58
	
59
	/*
60
	 * Join the encodingStyles into a space separated string
61
	 */
62
	private String joinEncodingStyles(List list) {
63
		
64
		if (list.isEmpty())
65
			return null;
66
		
67
		StringBuffer sb = new StringBuffer();
68
		
69
		Iterator iter = list.iterator();
70
		while (iter.hasNext())
71
			sb.append(" ").append(iter.next());
72
		
73
		return sb.substring(1).toString();
74
	}
75
	
76
	/*
77
	 * Retrieves the encoding information from the binding for the selected operation.
78
	 * This method is called only for RPC style bindings.  Two pieces of information are returned:  
79
	 * If the use is encoded, this method returns the encoding namespace in element [0] and the 
80
	 * encoding style(s) in element [1].  If the use is literal, then both values will be null.
81
	 */
82
	private String[] getEncodingInfo(MessageContext context) {
83
		
84
		String[] info = new String[] { null, null };
85
		
86
		Iterator iter = context.getBindingOperation().getBindingInput()
87
			.getExtensibilityElements().iterator();
88
				
89
		// look for the soapbind:body extensilibity element
90
		while (iter.hasNext()) {
91
			ExtensibilityElement e = (ExtensibilityElement) iter.next();			
92
			if (!(e instanceof SOAPBody))
93
				continue;
94
			
95
			SOAPBody soapBody = (SOAPBody) e;
96
			
97
			// use="encoded"
98
			if (!LITERAL.equals(soapBody.getUse())) {
99
				info[0] = soapBody.getNamespaceURI();
100
				info[1] = joinEncodingStyles(soapBody.getEncodingStyles());
101
			}
102
					
103
			break;
104
		}
105
		
106
		// namespace not specified on the soapbind:body element, use the definition's
107
		if (info[0] == null)
108
			info[0] = context.getDefinition().getTargetNamespace();
109
		
110
		return info;
111
	}
112
	
113
	/*
114
     * WS-I: In a rpc-literal SOAP binding, the serialized child element of the 
115
     * soap:Body element consists of a wrapper element, whose namespace is the value 
116
     * of the namespace attribute of the soapbind:body element and whose local name is 
117
     * either the name of the operation or the name of the operation suffixed 
118
     * with "Response". The namespace attribute is required, as opposed to being 
119
     * optional, to ensure that the children of the soap:Body element are namespace-
120
     * qualified.
121
     */
122
	private Element createRPCWrapper(Document document, MessageContext context, Hashtable namespaceTable) {
123
		
124
		String encodingNamespaceURI = getEncodingInfo(context)[0];
125
		
126
		return SoapHelper.createRPCWrapperElement(
127
				document, 
128
				namespaceTable, 
129
				encodingNamespaceURI, 
130
				context.getBindingOperation().getOperation().getName(),
131
				null);
132
	}
133
	
134
	/*
135
	 * Initializes the contents of new ISOAPMessage.
136
	 */
137
	void initMessage(ISOAPMessage message) throws TransportException {
138
	
139
		try {
140
			Document document = XMLUtils.createNewDocument(null);
141
			
142
			Hashtable namespaceTable = new Hashtable();
143
			SoapHelper.addDefaultSoapEnvelopeNamespaces(namespaceTable);
144
			
145
			message.setEnvelope(SoapHelper.createSoapEnvelopeElement(document, namespaceTable));
146
			message.setHeader(SoapHelper.createSoapHeaderElement(document));
147
			
148
			Element body = SoapHelper.createSoapBodyElement(document);
149
			if (!message.getMessageContext().isDocumentStyle()) {
150
				Element rpcWrapper = createRPCWrapper(document, message.getMessageContext(), namespaceTable);
151
				body.appendChild(rpcWrapper);
152
			}			
153
			message.setBody(body);			
154
			
155
			message.setNamespaceTable(namespaceTable);
156
		}
157
		catch (ParserConfigurationException e) {
158
			throw new TransportException(e);
159
		}		
160
	}
161
	
162
	/*
163
	 * Returns the first element with the given local name from the soap envelope namespace
164
	 * This method can be used on elements that are not namespace aware, but we have to give
165
	 * it a namespace table to look up prefixes.
166
	 */
167
	private Element getSOAPElement(Element root, String localName, Map namespaceTable) {
168
		String prefix = (String) namespaceTable.get(Constants.URI_SOAP11_ENV);
169
		if (prefix == null)
170
			return null;
171
		
172
		NodeList list = root.getElementsByTagName(prefix + ":" + localName);
173
		if (list.getLength() == 0)
174
			return null;
175
		
176
		return (Element) list.item(0);
177
	}
178
	
179
	/*
180
	 * Returns the first element with the given local name from the soap envelope namespace.
181
	 * This version assume the elements are namespace aware.
182
	 */
183
	private Element getSOAPElementNS(Element root, String localName) {
184
		NodeList list = root.getElementsByTagNameNS(Constants.URI_SOAP11_ENV, localName);
185
		if (list.getLength() == 0)
186
			return null;		
187
	
188
		return (Element) list.item(0);
189
	}
190
	
191
	/*
192
	 * Convert a NodeList to a vector of elements, nodes which are not elements are skipped.
193
	 */
194
	private Vector toElementVector(NodeList nodes) {
195
		
196
		Vector vector = new Vector();
197
		
198
		for (int i = 0; i < nodes.getLength(); i++) {
199
			Node node = nodes.item(i);
200
			if (node instanceof Element)
201
		    	vector.add(node);		    
202
		}
203
		
204
		return vector;	
205
	}
206
	
207
	/*
208
	 * Convert a NodeList to an array of elements, nodes which are not elements are skipped.
209
	 */
210
	private Element[] toElementArray(NodeList nodes) {
211
		Vector vector = toElementVector(nodes);
212
		Element[] elements = new Element[vector.size()];
213
		vector.copyInto(elements);
214
		return elements;
215
	}
216
	
217
	// Serialize ////////////////////////////////////////////////////////////////////////////////////////////////////////////	
218
	
219
	/*
220
	 * adds the encoding style attribute to the each element in the given array.
221
	 * noop if encodingStyle is null
222
	 */
223
	private void addEncodingStyle(Element[] elements, String encodingStyle) {
224
				
225
		// encodingStyle is non-null only if use="encoded"
226
		if (elements == null || encodingStyle == null)
227
			return;
228
		
229
		for (int i=0; i < elements.length; i++) {
230
	        if (elements[i] == null)
231
	        	continue;
232
	    	elements[i].setAttribute(
233
	    			Constants.NS_PREFIX_SOAP_ENV + ":" + Constants.ATTR_ENCODING_STYLE, encodingStyle);			
234
		}
235
	}
236
	
237
	/*
238
	 * Serialize an array of elements
239
	 */
240
	private String serializeElements(Element[] elements) {
241
	
242
		StringBuffer buffer = new StringBuffer();
243
		
244
		for (int i = 0; i < elements.length; i++) {
245
					
246
			String serializedFragment = XMLUtils.serialize(elements[i], true);
247
			if (serializedFragment == null) {
248
				// On Some JRE's (Sun java 5) elements with an attribute with the xsi
249
				// prefix do not serialize properly because the namespace can not
250
				// be found so the string returned comes back as null. To workaround
251
				// this problem try adding in the namespace declaration attribute
252
				// and retry the serialization (bug 144824)			 
253
				elements[i].setAttribute("xmlns:xsi", Constants.URI_2001_SCHEMA_XSI);
254
				serializedFragment = XMLUtils.serialize(elements[i], true);
255
			}
256
			
257
			buffer.append(serializedFragment);
258
			buffer.append(LINE_SEPARATOR);
259
		}
260
		
261
		return buffer.toString();
262
	}
263
264
	/*
265
	 * Determines if the given message is a request message using RPC style
266
	 */
267
	private boolean isRPCRequest(ISOAPMessage message) {
268
		return 
269
			!message.getMessageContext().isDocumentStyle() &&							// rpc style
270
			!Boolean.TRUE.equals(message.getProperty(SOAPTransport.PROP_READ_ONLY));	// not read-only
271
	}
272
	
273
	/* (non-Javadoc)
274
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISerializer#serialize(int, org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage)
275
	 */
276
	public String serialize(int part, ISOAPMessage message) throws TransportException {
277
278
		switch (part) {
279
			case ISOAPMessage.ENVELOPE:
280
				Element envelope = message.getEnvelope(true);
281
				
282
				if (isRPCRequest(message)) {					
283
					Element body = getSOAPElementNS(envelope, Constants.ELEM_BODY);
284
					if (body == null)
285
						body = getSOAPElement(envelope, Constants.ELEM_BODY, message.getNamespaceTable());
286
					
287
					if (body != null) {
288
						Element[] bodyContent = toElementArray(body.getFirstChild().getChildNodes());
289
						addEncodingStyle(bodyContent, getEncodingInfo(message.getMessageContext())[1]);
290
					}
291
				}
292
				
293
				String xml = XMLUtils.serialize(envelope, true);
294
				if (xml == null)
295
					xml = new String((byte[]) message.getProperty(SOAPTransport.PROP_RAW_BYTES));
296
				
297
				return xml;
298
				
299
			case ISOAPMessage.HEADER_CONTENT:
300
				return serializeElements(message.getHeaderContent());
301
				
302
			case ISOAPMessage.BODY_CONTENT:				
303
				Element[] bodyContent = message.getBodyContent();
304
				
305
				if (isRPCRequest(message))
306
					addEncodingStyle(bodyContent, getEncodingInfo(message.getMessageContext())[1]);
307
				
308
				return serializeElements(bodyContent);
309
		}
310
		
311
		return "";
312
	}
313
	
314
	// Deserialize //////////////////////////////////////////////////////////////////////////////////////////////////////////		
315
		
316
	/*
317
	 * Retrieve the soap header from the envelope and populate the given message
318
	 */
319
	private void processHeader(Element envelope, ISOAPMessage message) {
320
		
321
		Element header = getSOAPElementNS(envelope, Constants.ELEM_HEADER);
322
		if (header == null)
323
			return;
324
		
325
		message.setHeader(header);
326
		message.setHeaderContent(toElementArray(header.getChildNodes()));
327
	}
328
	
329
	/*
330
	 * HACK - The root element tag name of the instance document
331
	 * is ambiguous.  It lands on a very grey area between the SOAP
332
	 * spec and the WSDL spec.  The two specs do not explicitly define
333
	 * that the root element tag name must match the name of the
334
	 * WSDL part.  The hack is to treat elements with different tag names
335
	 * as instances of the WSDL part.
336
	 */
337
	private Element[] fixSOAPResponse(NodeList instanceList, MessageContext context) {
338
		
339
		Vector instanceVector = toElementVector(instanceList);		
340
		Element[] instanceDocuments = new Element[instanceVector.size()];
341
		
342
		Operation oper = context.getBindingOperation().getOperation();		
343
		Map partsMap = oper.getOutput().getMessage().getParts();
344
		
345
		if (partsMap.size() == 1) {
346
			Iterator it = partsMap.values().iterator();
347
			Part part = (Part) it.next();
348
			
349
			String fragName;
350
			if (part.getElementName() != null)
351
				fragName = part.getElementName().getLocalPart();
352
			else
353
				fragName = part.getName();
354
		    
355
		    for (int i = 0; i < instanceVector.size(); i++) {
356
		    	Element element = (Element) instanceVector.get(i);
357
		    	
358
		    	if (!element.getTagName().equals(fragName)) {
359
		    		Document doc = element.getOwnerDocument();
360
		    		NodeList children = element.getChildNodes();
361
		    		NamedNodeMap attributes = element.getAttributes();
362
		    		element = doc.createElement(fragName);
363
		    		
364
		    		for (int j = 0; j < children.getLength(); j++) {
365
		    			if (children.item(j) != null) {
366
		    				element.appendChild(children.item(j));
367
				            // When you append a node from one element to another,
368
				            // the original element will lose its reference to this node,
369
				            // therefore, the size of the node list will decrease by 1.
370
				            j--;
371
		    			}
372
		    		}
373
		    		
374
		    		for (int j = 0; j < attributes.getLength(); j++) {
375
		    			Object attr = attributes.item(j);
376
		    			if (attr != null && (attr instanceof Attr)) {
377
		    				Attr attribute = (Attr)attr;
378
		    				element.setAttribute(attribute.getName(), attribute.getValue());
379
		    			}
380
		    		}
381
		    	}
382
		    	instanceDocuments[i] = element;
383
		    }
384
		}
385
		else
386
			instanceVector.copyInto(instanceDocuments);
387
		
388
		return instanceDocuments;
389
	}
390
	
391
	/*
392
	 * Retrieve the soap header from the envelope and populate the given message
393
	 */
394
	private void processBody(Element envelope, ISOAPMessage message) {
395
		
396
		Element body = getSOAPElementNS(envelope, Constants.ELEM_BODY);
397
		if (body == null)
398
			return;				
399
		
400
		message.setBody(body);
401
		
402
		// check for soap fault
403
		Element fault = getSOAPElementNS(body, Constants.ELEM_FAULT);
404
	    if (fault != null) {
405
	    	message.setFault(fault);
406
	    	return;
407
	    }
408
	        	        
409
	    NodeList instanceList;
410
	    
411
	    if (message.getMessageContext().isDocumentStyle())
412
	    	instanceList = body.getChildNodes();
413
	    else {
414
	        NodeList rpcWrapper = body.getElementsByTagNameNS("*", 
415
	        		message.getMessageContext().getBindingOperation().getOperation().getOutput().getMessage().getQName().getLocalPart());
416
417
	        /*
418
	        * HACK - Some of the web services out on the internet do not
419
	        * set their RPC wrapper properly.  It should be set to the output
420
	        * message name of the selected operation.  The hack is to
421
	        * assume the first element inside the body element is the
422
	        * RPC wrapper.
423
	        */
424
	        if (rpcWrapper.getLength() <= 0)
425
	        	rpcWrapper = body.getElementsByTagNameNS("*", "*");
426
427
	        if (rpcWrapper.getLength() > 0)
428
	        	instanceList = rpcWrapper.item(0).getChildNodes();
429
	        else
430
	        	return;
431
	    }
432
	    
433
	    message.setBodyContent(fixSOAPResponse(instanceList, message.getMessageContext()));
434
	}
435
	
436
	/*
437
	 * Deserialize the byte array into the given soap message.  The part parameters tells
438
	 * the method whether the input is the whole envelop or just the contents of the
439
	 * header or body. 
440
	 */
441
	void deserialize(int part, byte[] xml, ISOAPMessage message) throws		
442
		ParserConfigurationException,
443
		SAXException,
444
		IOException {
445
		
446
		Element root = XMLUtils.byteArrayToElement(xml, true);		
447
		
448
		switch (part) {
449
			case ISOAPMessage.ENVELOPE:				 
450
				message.setEnvelope(root);
451
				processHeader(root, message);
452
				processBody(root, message);
453
				break;
454
			case ISOAPMessage.HEADER_CONTENT:
455
				message.setHeaderContent(toElementArray(root.getChildNodes()));
456
				break;
457
			case ISOAPMessage.BODY_CONTENT:
458
				message.setBodyContent(toElementArray(root.getChildNodes()));
459
				break;
460
		}
461
	}
462
	
463
	/*
464
	 * Tack on a root element the string which represents a series of elements.
465
	 * This is needed to deserialize the string.
466
	 */
467
	private String addRootElement(String xml, Map namespaceTable) {
468
		StringBuffer sb = new StringBuffer();
469
	    sb.append("<root");
470
	    
471
	    Iterator iter = namespaceTable.keySet().iterator();
472
	    while (iter.hasNext()) {
473
	    	Object uri = iter.next();
474
	    	Object prefix = namespaceTable.get(uri);
475
	    	sb.append(" ").append("xmlns:").append(prefix).append("=\"").append(uri).append("\"");
476
	    }	    
477
	    
478
	    sb.append(">").append(xml).append("</root>");
479
	    return sb.toString();
480
	}
481
	
482
	/* (non-Javadoc)
483
	 * @see org.eclipse.wst.ws.internal.explorer.transport.IDeserializer#deserialize(int, java.lang.String, org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage)
484
	 */
485
	public void deserialize(int part, String xml, ISOAPMessage message) throws TransportException {
486
		
487
		if (part != ISOAPMessage.ENVELOPE)
488
			xml = addRootElement(xml, message.getNamespaceTable());
489
		
490
		try {
491
			deserialize(part, xml.getBytes(DEFAULT_SOAP_ENCODING), message);
492
		}
493
		catch (Exception e) {
494
			throw new TransportException(e);
495
		}
496
	}
497
}
(-)src/org/eclipse/wst/ws/internal/explorer/transport/TransportException.java (+51 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 * IBM Corporation - initial API and implementation
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
13
 *******************************************************************************/
14
package org.eclipse.wst.ws.internal.explorer.transport;
15
16
/**
17
 * An general purpose exception to indicate a problem has occurred when
18
 * invoking a web service.
19
 */
20
public class TransportException extends RuntimeException {
21
22
	private static final long serialVersionUID = -1502247230726021403L;
23
24
	/**
25
	 * Constructor.
26
	 * 
27
	 * @param message A message about the problem that occurred.
28
	 */
29
	public TransportException(String message) {
30
		super(message);
31
	}
32
	
33
	/**
34
	 * Constructor that accepts a message and a cause.
35
	 * 
36
	 * @param message A message about the problem that occurred.
37
	 * @param cause The cause for this exception.
38
	 */
39
	public TransportException(String message, Throwable cause) {
40
		super(message, cause);
41
	}
42
	
43
	/**
44
	 * Constructor that accepts a cause.
45
	 * 
46
	 * @param cause The cause for this exception.
47
	 */
48
	public TransportException(Throwable cause) {
49
		super(cause);
50
	}
51
}
(-)src/org/eclipse/wst/ws/internal/explorer/transport/ISOAPTransportProvider.java (+30 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 * IBM Corporation - initial API and implementation
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
13
 *******************************************************************************/
14
package org.eclipse.wst.ws.internal.explorer.transport;
15
16
/**
17
 * ISOAPTransportProvider is a factory for creating ISOAPTransport objects.
18
 * Anyone who wishes to extend the org.eclipse.wst.ws.explorer.wseTransportProvider
19
 * extension-point must provide an implementation for this interface. 
20
 */
21
public interface ISOAPTransportProvider {
22
23
	/**
24
	 * Method for obtaining a new ISOAPTransport from this provider.
25
	 * This method should never return null.
26
	 * 
27
	 * @return A new ISOAPTransport object.
28
	 */
29
	public ISOAPTransport newTransport();
30
}
(-)wsexplorer-src/org/eclipse/wst/ws/internal/explorer/platform/wsdl/util/SOAPMessageUtils.java (+172 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 * IBM Corporation - initial API and implementation
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
13
 *******************************************************************************/
14
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.util;
15
16
import java.util.Hashtable;
17
import java.util.Iterator;
18
import java.util.Map;
19
import java.util.Vector;
20
21
import javax.wsdl.Part;
22
import javax.xml.parsers.ParserConfigurationException;
23
24
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.constants.WSDLModelConstants;
25
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.datamodel.WSDLOperationElement;
26
import org.eclipse.wst.ws.internal.explorer.platform.wsdl.fragment.IXSDFragment;
27
import org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage;
28
import org.eclipse.wst.wsdl.binding.soap.SOAPHeader;
29
import org.w3c.dom.Element;
30
31
/**
32
 * This class has some common routines used by the Web Services explorer to work with ISOAPMessages.
33
 */
34
public class SOAPMessageUtils {
35
	
36
	/**
37
	 * Decodes namespace declarations that have been encoded by WSE into the operation element of the WSDL model.
38
	 * The decoded declarations will be added to the given namespace table.
39
	 *  
40
	 * @param soapEnvelopeNamespaceTable The namespace table to populate.
41
	 * @param operElement The operation element with the encoded namespace declarations.
42
	 * @return True if new namespace declarations are found and added to the namespace table, false otherwise.
43
	 */
44
	public static boolean decodeNamespaceTable(Hashtable soapEnvelopeNamespaceTable, WSDLOperationElement operElement) {
45
			
46
		boolean updated = false;
47
48
		String[] nsDeclarations = (String[]) operElement.getPropertyAsObject(WSDLModelConstants.PROP_SOURCE_CONTENT_NAMESPACE);
49
		if (nsDeclarations == null)
50
			return false;
51
52
		// each namespace declaration is decoded into 2 parts: the prefix 
53
		// in element [0] and the namespace uri in element [1].
54
		for (int i = 0; i < nsDeclarations.length; i++) {
55
			String[] prefix_ns = SoapHelper.decodeNamespaceDeclaration(nsDeclarations[i]);
56
			
57
			// check if the namespace uri is already a key in the namespace table
58
			// if it is, don't add it
59
			if (!soapEnvelopeNamespaceTable.containsKey(prefix_ns[1])) {
60
			    soapEnvelopeNamespaceTable.put(prefix_ns[1], prefix_ns[0]);
61
			    updated = true;
62
			}
63
		}
64
		
65
		return updated;
66
	}
67
68
	/**
69
	 * Populate the header content of the given ISOAPMessage using the values from WSE's fragment model
70
	 * 
71
	 * @param soapEnvelopeNamespaceTable A namespace table to use during this operation.
72
	 * @param operElement Access WSE's fragments via this operation element. 
73
	 * @param soapMessage The ISOAPMessage to populate.
74
	 * @throws ParserConfigurationException
75
	 */
76
	public static void setHeaderContentFromModel(Hashtable soapEnvelopeNamespaceTable, WSDLOperationElement operElement, ISOAPMessage soapMessage)
77
		throws ParserConfigurationException {
78
	    
79
		Vector headerEntries = new Vector();
80
	    
81
	    Iterator it = operElement.getSOAPHeaders().iterator();
82
	    while (it.hasNext()) {
83
	    	SOAPHeader soapHeader = (SOAPHeader) it.next();
84
	    	boolean isUseLiteral = "literal".equals(soapHeader.getUse());           
85
	    	IXSDFragment frag = (IXSDFragment) operElement.getHeaderFragment(soapHeader);
86
	    	Element[] instanceDocuments = frag.genInstanceDocumentsFromParameterValues(
87
	    			!isUseLiteral, soapEnvelopeNamespaceTable, soapMessage.getEnvelope(false).getOwnerDocument());
88
	    	for (int i = 0; i < instanceDocuments.length; i++) {
89
	    		if (instanceDocuments[i] == null)
90
	    			continue;
91
	    		headerEntries.addElement(instanceDocuments[i]);
92
	    	}
93
	    }
94
95
	    Element[] headerContent = new Element[headerEntries.size()];
96
	    headerEntries.copyInto(headerContent);
97
	    
98
	    soapMessage.setHeaderContent(headerContent);
99
	}
100
101
	/**
102
	 * Populate the body content of the given ISOAPMessage using the values from WSE's fragment model
103
	 * 
104
	 * @param soapEnvelopeNamespaceTable A namespace table to use during this operation.
105
	 * @param operElement Access WSE's fragments via this operation element. 
106
	 * @param soapMessage The ISOAPMessage to populate.
107
	 * @throws ParserConfigurationException
108
	 */
109
	public static void setBodyContentFromModel(Hashtable soapEnvelopeNamespaceTable, WSDLOperationElement operElement, ISOAPMessage soapMessage)
110
		throws ParserConfigurationException {
111
		
112
	    Vector bodyEntries = new Vector();
113
	    boolean isUseLiteral = operElement.isUseLiteral();
114
115
	    Iterator it = operElement.getOrderedBodyParts().iterator();
116
	    while (it.hasNext()) {
117
	    	Part part = (Part)it.next();
118
	    	IXSDFragment frag = (IXSDFragment) operElement.getFragment(part);
119
	    	Element[] instanceDocuments = frag.genInstanceDocumentsFromParameterValues(
120
	    			 !isUseLiteral, soapEnvelopeNamespaceTable, soapMessage.getEnvelope(false).getOwnerDocument());
121
	    	for (int i = 0; i < instanceDocuments.length; i++) {
122
	    		if (instanceDocuments[i] == null)
123
	    			continue;
124
	    		bodyEntries.addElement(instanceDocuments[i]);
125
	    	}
126
	    }
127
128
	    Element[] bodyContent = new Element[bodyEntries.size()];
129
	    bodyEntries.copyInto(bodyContent);
130
	    
131
	    soapMessage.setBodyContent(bodyContent);
132
	}
133
	
134
	/**
135
	 * Given an array of elements, this method will return the index of the first element that matches
136
	 * the given Part.  A match is determined by comparing the fully qualified names of the Part and Elements.
137
	 * 
138
	 * @param part The Part 
139
	 * @param elements The array of Elements
140
	 * @param namespaceTable A namespace table for looking up namespace prefixes.
141
	 * @param fragName Name of the Part's fragment (essentially the Part's local name).
142
	 * @param start The index to begin the search.
143
	 * @return The index of the first matching element, or -1 if no match is found.
144
	 */
145
	public static int findFirstMatchingElement(Part part, Element[] elements, Map namespaceTable, String fragName, int start) {
146
		
147
		String namespaceURI = null;
148
		String prefix = null;
149
		
150
		// try to get the prefix
151
		if (part.getElementName() != null) {
152
			namespaceURI = part.getElementName().getNamespaceURI();
153
			prefix = (String) namespaceTable.get(namespaceURI);					
154
		}
155
		
156
		for (int i = start; i < elements.length; i++) {			
157
			Element element = elements[i];
158
			String name = element.getTagName();
159
			
160
			// try to get prefix again, the namespace declaration can be directly on the element
161
			if (prefix == null && namespaceURI != null)
162
				prefix = element.lookupPrefix(namespaceURI);
163
			
164
			if (prefix == null && name.equals(fragName))
165
				return i;
166
			else if (prefix != null && name.equals(prefix + ":" + fragName))
167
				return i;
168
		}
169
				
170
		return -1;
171
	}
172
}
(-)src/org/eclipse/wst/ws/internal/explorer/transport/MessageContext.java (+107 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 * IBM Corporation - initial API and implementation
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
13
 *******************************************************************************/
14
package org.eclipse.wst.ws.internal.explorer.transport;
15
16
import javax.wsdl.BindingOperation;
17
import javax.wsdl.Definition;
18
import javax.wsdl.extensions.ExtensibilityElement;
19
20
/**
21
 * A MessageContext object holds information about the message that is to be
22
 * sent on a web service invocation.  This information is passed to the
23
 * ISOAPTransport so that it can construct an appropriate ISOAPMessage to
24
 * handle the invocation.
25
 */
26
public class MessageContext {
27
	
28
	private Definition definition;
29
	private ExtensibilityElement bindingProtocol;
30
	private BindingOperation bindingOperation;	
31
	private boolean documentStyle;			
32
	
33
	/**
34
	 * Sets a reference to the WSDL definition.
35
	 * 
36
	 * @param definition The WSDL definition.
37
	 */
38
	public void setDefinition(Definition definition) {
39
		this.definition = definition;
40
	}
41
	
42
	/**
43
	 * Returns the WSDL definition.
44
	 * 
45
	 * @return The WSDL definition.
46
	 */
47
	public Definition getDefinition() {
48
		return definition;
49
	}
50
	
51
	/**
52
	 * Sets a reference to the binding extensibility element in the WSDL document.
53
	 * For a web service that uses the SOAP protocol, this will be an instance of
54
	 * javax.wsdl.extensions.soap.SOAPBinding
55
	 * 
56
	 * @param bindingProtocol The binding extensibility element.
57
	 */
58
	public void setBindingProtocol(ExtensibilityElement bindingProtocol) {
59
		this.bindingProtocol = bindingProtocol;		
60
	}
61
	
62
	/**
63
	 * Returns the binding extensibility element.
64
	 * 
65
	 * @return The binding extensibility element.
66
	 */
67
	public ExtensibilityElement getBindingProtocol() {
68
		return bindingProtocol;
69
	}
70
	
71
	/**
72
	 * Sets a reference to the binding operation element in the WSDL document.
73
	 * 
74
	 * @param bindingOperation The binding operation element.
75
	 */
76
	public void setBindingOperation(BindingOperation bindingOperation) {
77
		this.bindingOperation = bindingOperation;
78
	}
79
	
80
	/**
81
	 * Returns the binding operation element.
82
	 * 
83
	 * @return The binding operation element.
84
	 */
85
	public BindingOperation getBindingOperation() {
86
		return bindingOperation;
87
	}		
88
		
89
	/**
90
	 * Sets the flag on whether the message created from this MessageContext
91
	 * is document style or not.
92
	 * 
93
	 * @param documentStyle True for document style, false otherwise.
94
	 */
95
	public void setDocumentStyle(boolean documentStyle) {
96
		this.documentStyle = documentStyle;
97
	}
98
	
99
	/**
100
	 * Returns the document style property.
101
	 * 
102
	 * @return The document style property.
103
	 */
104
	public boolean isDocumentStyle() {
105
		return documentStyle;
106
	}
107
}
(-)src/org/eclipse/wst/ws/internal/explorer/platform/wsdl/transport/ChunkedInputStream.java (+192 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2001, 2005 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
12
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport;
13
14
import java.io.FilterInputStream;
15
import java.io.IOException;
16
import java.io.InputStream;
17
18
public class ChunkedInputStream extends FilterInputStream
19
{
20
  protected long chunkSize = 0l;
21
  protected volatile boolean closed = false;
22
  private static final int maxCharLong = (Long.toHexString(Long.MAX_VALUE)).toString().length();
23
24
  private ChunkedInputStream()
25
  {
26
    super(null);
27
  }
28
29
  public ChunkedInputStream(InputStream is)
30
  {
31
    super(is);
32
  }
33
34
  public int read() throws IOException
35
  {
36
    byte[] d = new byte[1];
37
    int rc = read(d, 0, 1);
38
    return rc > 0 ? (d[0] & 0xFF) : rc;
39
  }
40
41
  public int read(byte[] b) throws IOException
42
  {
43
    return read(b, 0, b.length);
44
  }
45
46
  public synchronized int read(byte[] b, int off, int len) throws IOException
47
  {
48
    if (closed)
49
      return -1;
50
51
    int totalread = 0;
52
    int bytesread = 0;
53
    try
54
    {
55
      do
56
      {
57
        if (chunkSize < 1L)
58
        {
59
          if (0l == getChunked())
60
          {
61
            if (totalread == 0)
62
              return -1;
63
            else
64
              return totalread;
65
          }
66
        }
67
        bytesread = in.read(b, off + totalread, Math.min(len - totalread, (int) Math.min(chunkSize, Integer.MAX_VALUE)));
68
        if (bytesread > 0)
69
        {
70
          totalread += bytesread;
71
          chunkSize -= bytesread;
72
        }
73
      }
74
      while (len - totalread > 0 && bytesread > -1);
75
    }
76
    catch (IOException e)
77
    {
78
      closed = true;
79
      throw e;
80
    }
81
    return totalread;
82
  }
83
84
  public long skip(final long n) throws IOException
85
  {
86
    if (closed)
87
      return 0;
88
    long skipped = 0l;
89
    byte[] b = new byte[1024];
90
    int bread = -1;
91
    do
92
    {
93
      bread = read(b, 0, b.length);
94
      if (bread > 0)
95
        skipped += bread;
96
    }
97
    while (bread != -1 && skipped < n);
98
    return skipped;
99
  }
100
101
  public int available() throws IOException
102
  {
103
    if (closed)
104
      return 0;
105
    int rc = (int) Math.min(chunkSize, Integer.MAX_VALUE);
106
    return Math.min(rc, in.available());
107
  }
108
109
  protected long getChunked() throws IOException
110
  {
111
    //StringBuffer buf= new StringBuffer(1024);
112
    byte[] buf = new byte[maxCharLong + 2];
113
    int bufsz = 0;
114
    chunkSize = -1L;
115
    int c = -1;
116
    do
117
    {
118
      c = in.read();
119
      if (c > -1)
120
      {
121
        if (c != '\r' && c != '\n' && c != ' ' && c != '\t')
122
        {
123
          buf[bufsz++] = ((byte) c);
124
        }
125
      }
126
    }
127
    while (c > -1 && (c != '\n' || bufsz == 0) && bufsz < buf.length);
128
    if (c < 0)
129
    {
130
      closed = true;
131
    }
132
    String sbuf = new String(buf, 0, bufsz);
133
    if (bufsz > maxCharLong)
134
    {
135
      closed = true;
136
      throw new IOException("Chunked input stream failed to receive valid chunk size:" + sbuf);
137
    }
138
    try
139
    {
140
      chunkSize = Long.parseLong(sbuf, 16);
141
    }
142
    catch (NumberFormatException ne)
143
    {
144
      closed = true;
145
      throw new IOException("'" + sbuf + "' " + ne.getMessage());
146
    }
147
    if (chunkSize < 1L)
148
      closed = true;
149
    if (chunkSize != 0L && c < 0)
150
    {
151
      //If chunk size is zero try and be tolerant that there maybe no cr or lf
152
      // at the end.
153
      throw new IOException("HTTP Chunked stream closed in middle of chunk.");
154
    }
155
    if (chunkSize < 0L)
156
      throw new IOException("HTTP Chunk size received " + chunkSize + " is less than zero.");
157
    return chunkSize;
158
  }
159
160
  public void close() throws IOException
161
  {
162
    synchronized (this)
163
    {
164
      if (closed)
165
        return;
166
      closed = true;
167
    }
168
    byte[] b = new byte[1024];
169
    int bread = -1;
170
    do
171
    {
172
      bread = read(b, 0, b.length);
173
    }
174
    while (bread != -1);
175
  }
176
177
  /*
178
   * public void mark(int readlimit)
179
   * {
180
   * }
181
   */
182
183
  public void reset() throws IOException
184
  {
185
    throw new IOException("Don't support marked streams");
186
  }
187
188
  public boolean markSupported()
189
  {
190
    return false;
191
  }
192
}
(-)src/org/eclipse/wst/ws/internal/explorer/platform/util/URLUtils.java (+101 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2005 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * 
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.wst.ws.internal.explorer.platform.util;
12
13
import java.io.UnsupportedEncodingException;
14
import java.net.URLDecoder;
15
import java.net.URLEncoder;
16
17
/**
18
 * This class contains utility methods for managing URLs
19
 * as used by the Web Services Explorer Web application.
20
 * @author cbrealey@ca.ibm.com
21
 */
22
public final class URLUtils
23
{
24
	/**
25
	 * Objects of this class should not be constructed.
26
	 */
27
	private URLUtils ()
28
	{
29
	}
30
31
	/**
32
	 * UTF-8
33
	 */
34
	public static final String UTF8 = "UTF-8";
35
36
	/**
37
	 * Equivalent to {@link #encode(String,String)}
38
	 * with second parameter set to the "UTF-8" encoding.
39
	 * @param s The string to encode.
40
	 * @return The encoded string.
41
	 */
42
	public static String encode(String s)
43
	{
44
		return encode(s,UTF8);
45
	}
46
	
47
	/**
48
	 * Equivalent to {@link URLEncoder#encode(String,String)},
49
	 * only throws an unchecked {@link RuntimeException} wrapped
50
	 * around an {@link UnsupportedEncodingException} instead of
51
	 * an {@link UnsupportedEncodingException}.
52
	 * @param s The string to encode.
53
	 * @param enc The encoding to use.
54
	 * @return The encoded string.
55
	 */
56
	public static String encode(String s, String enc)
57
	{
58
		try
59
		{
60
			return URLEncoder.encode(s,enc);
61
		}
62
		catch (UnsupportedEncodingException e)
63
		{
64
			// TODO: MSG_BROKEN_VM_DOES_NOT_SUPPORT_UTF-8
65
			throw new RuntimeException("%MSG_BROKEN_VM_DOES_NOT_SUPPORT_UTF-8",e);
66
		}
67
	}
68
	
69
	/**
70
	 * Equivalent to {@link #decode(String,String)}
71
	 * with second parameter set to the "UTF-8" encoding.
72
	 * @param s The string to decode.
73
	 * @return The decoded string.
74
	 */
75
	public static String decode(String s)
76
	{
77
		return decode(s,UTF8);
78
	}
79
	
80
	/**
81
	 * Equivalent to {@link URLEncoder#decode(String,String)},
82
	 * only throws an unchecked {@link RuntimeException} wrapped
83
	 * around an {@link UnsupportedEncodingException} instead of
84
	 * an {@link UnsupportedEncodingException}.
85
	 * @param s The string to decode.
86
	 * @param enc The encoding to use.
87
	 * @return The decoded string.
88
	 */
89
	public static String decode(String s, String enc)
90
	{
91
		try
92
		{
93
			return URLDecoder.decode(s,enc);
94
		}
95
		catch (UnsupportedEncodingException e)
96
		{
97
			// TODO: MSG_BROKEN_VM_DOES_NOT_SUPPORT_UTF-8
98
			throw new RuntimeException("%MSG_BROKEN_VM_DOES_NOT_SUPPORT_UTF-8",e);
99
		}
100
	}
101
}
(-)src/org/eclipse/wst/ws/internal/explorer/transport/HTTPTransportException.java (+65 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 * IBM Corporation - initial API and implementation
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
13
 *******************************************************************************/
14
package org.eclipse.wst.ws.internal.explorer.transport;
15
16
import java.util.Map;
17
18
/**
19
 * A type of TransportException that can be thrown when the transport protocol
20
 * is HTTP.  The status code of the HTTP response is captured in this
21
 * exception and passed up to the Web Services Explorer.
22
 */
23
public class HTTPTransportException extends TransportException {
24
25
	private static final long serialVersionUID = 8277180731798858877L;
26
	
27
	private int statusCode;
28
	private Map headers;
29
	
30
	/**
31
	 * Constructor.
32
	 * 
33
	 * @param statusCode The HTTP status code.
34
	 * @param message A message about the problem that occurred.
35
	 * @param headers A map of the HTTP headers.
36
	 */
37
	public HTTPTransportException(int statusCode, String message, Map headers) {
38
		super(message);
39
		this.statusCode = statusCode;
40
		this.headers = headers;
41
	}
42
	
43
	/**
44
	 * Returns the HTTP status code used to create this exception.
45
	 * 
46
	 * @return The HTTP status code.
47
	 */
48
	public int getStatusCode() {
49
		return statusCode;
50
	}
51
	
52
	/**
53
	 * Retrieve the HTTP header for the given key
54
	 * 
55
	 * @param key The key value.
56
	 * @return The HTTP header value for key, or null if there is no such header.
57
	 */
58
	public String getHeader(String key) {
59
	    Object value = headers.get(key);
60
	    if (value != null)
61
	    	return value.toString();
62
	    else
63
	    	return null;
64
	}
65
}
(-)src/org/eclipse/wst/ws/internal/explorer/transport/ISOAPMessage.java (+220 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 * IBM Corporation - initial API and implementation
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
13
 *******************************************************************************/
14
package org.eclipse.wst.ws.internal.explorer.transport;
15
16
import java.util.Map;
17
18
import org.w3c.dom.Element;
19
20
/**
21
 * The ISOAPMessage represents a SOAP message in a web service invocation made by the
22
 * Web Services Explorer's transport stack.
23
 * <br/>
24
 * <br/>
25
 * The setters of ISOAPMessage are called by Web Services Explorer to populate the
26
 * message before sending.  WSE does not guarantee that all message elements it sets
27
 * will have the same owner document.
28
 */
29
public interface ISOAPMessage {
30
31
	/**
32
	 * ISOAPMessage defines this property for storing the SOAP action value in
33
	 * a web service invocation.  This property will be set by Web Services Explorer
34
	 * prior to passing the message to {@link ISOAPTransport#send(String, String, String, ISOAPMessage)}
35
	 */
36
	String PROP_SOAP_ACTION = "prop_soap_action";
37
	
38
	/**
39
	 * This value is used when serializing and deserializing a message.  It indicates the operation
40
	 * is working with the entire SOAP envelope element. 
41
	 */
42
	int ENVELOPE = 0;
43
	
44
	/**
45
	 * This value is used when serializing and deserializing a message.  It indicates the operation
46
	 * is working with the elements inside the SOAP header element.
47
	 */
48
	int HEADER_CONTENT = 1;
49
	
50
	/**
51
	 * This value is used when serializing and deserializing a message.  It indicates the operation
52
	 * is working with the elements inside the SOAP body element.
53
	 */
54
	int BODY_CONTENT = 2;
55
56
	/**
57
	 * Returns the MessageContext associated with this message.  The MessageContext is created
58
	 * by the Web Services Explorer and passed to the transport stack during message creation.  
59
	 * Implementers of ISOAPMessage should store a reference to the MessageContext.
60
	 * 
61
	 * @return The MessageContext encasulating information about the web service operation. 
62
	 * @see ISOAPTransport#newMessage(MessageContext)
63
	 */
64
	public MessageContext getMessageContext();
65
66
	/**
67
	 * Sets a property in this ISOAPMessage.
68
	 * 
69
	 * @param key The key (name) of the property
70
	 * @param value The value of the property.
71
	 */
72
	public void setProperty(String key, Object value);
73
74
	/**
75
	 * Retrieves a property from this ISOAPMessage.
76
	 * 
77
	 * @param key The key (name) of the property to retrieve.
78
	 * @return The value assoicated with the given key, or null if there's no such property.
79
	 */
80
	public Object getProperty(String key);
81
82
	/**
83
	 * The namespace table holds the namespace declaraions that are on the envelope element
84
	 * of the SOAP message.  The table's keys are the namespace URIs and the values are the
85
	 * associated namespace prefixes.
86
	 * <br/>
87
	 * <br/>
88
	 * The effect of calling this method is that the declarations in the namespace table
89
	 * argument should add to or replace the declarations on the envelope.  This API does
90
	 * not specify what happens to existing declarations on the envelope which are not
91
	 * in the namespace table passed in.
92
	 * 
93
	 * @param namespaceTable The namespace table
94
	 */
95
	public void setNamespaceTable(Map namespaceTable);
96
97
	/**
98
	 * Returns a table of the namespace declarations that are on the envelope element of the
99
	 * SOAP message.  The table's keys are the namespace URIs and the values are the
100
	 * associated namespace prefixes.
101
	 * <br/>
102
	 * <br/>
103
	 * The namespace table returned by this method may be modified by the Web Services
104
	 * Explorer and later updated back to the message via the setNamesapceTable() method.
105
	 * 
106
	 * @return A table of namespace URIs to prefixes on the SOAP envelope.
107
	 */
108
	public Map getNamespaceTable();
109
110
	/**
111
	 * Sets the envelope element of this message.
112
	 * 
113
	 * @param envelope The envelope element.
114
	 */
115
	public void setEnvelope(Element envelope);
116
117
	/**
118
	 * Returns the envelope element of this message.  The deep parameter dictates whether
119
	 * the method returns the whole envelope with all its descendants or just the envelope 
120
	 * element itself.
121
	 * 
122
	 * @param deep If true, the envelope and its descendants are returned, otherwise only
123
	 * the envelope element itself is returned.
124
	 * @return An element.
125
	 */
126
	public Element getEnvelope(boolean deep);
127
128
	/**
129
	 * Sets the header element of this message.
130
	 * 
131
	 * @param header The header element.
132
	 */
133
	public void setHeader(Element header);
134
135
	/**
136
	 * Returns the header element of this message.  The deep parameter dictates whether
137
	 * the method returns the whole header with all its descendants or just the header 
138
	 * element itself.
139
	 * 
140
	 * @param deep If true, the header and its descendants are returned, otherwise only
141
	 * the header element itself is returned.
142
	 * @return An element.
143
	 */
144
	public Element getHeader(boolean deep);
145
146
	/**
147
	 * Sets an array of elements that goes into the message's header.
148
	 * 
149
	 * @param headerContent An array of elements.
150
	 */
151
	public void setHeaderContent(Element[] headerContent);
152
153
	/**
154
	 * Returns the array of elements that are inside the message's header.
155
	 * 
156
	 * @return An array of elements.
157
	 */
158
	public Element[] getHeaderContent();
159
160
	/**
161
	 * Sets the body element of this message.  For an RPC style message, the first child
162
	 * element of the body should be the RPC wrapper element.
163
	 * 
164
	 * @param body The body element.
165
	 */
166
	public void setBody(Element body);
167
168
	/**
169
	 * Returns the body of this message.  The deep parameter dictates whether
170
	 * the method returns the whole body with all its descendants elements or just the
171
	 * body.  For an RPC style message, the first child element of the 
172
	 * body should be the RPC wrapper element, regardless of the value of the deep
173
	 * parameter.
174
	 * 
175
	 * @param deep If true, the body and its descendants are returned, otherwise only
176
	 * the body (and the RPC wrapper element if the message is RPC style) is returned.
177
	 * @return An element.
178
	 */	
179
	public Element getBody(boolean deep);
180
181
	/**
182
	 * Sets an array of elements that goes into the message's body.  For an RPC style
183
	 * message, the body contents are the elements inside the RPC wrapper element.
184
	 * 
185
	 * @param bodyContent An array of elements.
186
	 */
187
	public void setBodyContent(Element[] bodyContent);
188
189
	/**
190
	 * Returns the array of elements that are inside the message's body.  For an RPC style
191
	 * message, the body contents are the elements inside the RPC wrapper element.
192
	 * 
193
	 * @return An array of elements.
194
	 */
195
	public Element[] getBodyContent();
196
197
	/**
198
	 * Set the fault element for this message, if any.
199
	 * 
200
	 * @param fault A fault element.
201
	 */
202
	public void setFault(Element fault);
203
204
	/**
205
	 * Returns the fault element, if any.
206
	 * 
207
	 * @return The fault element or null if no fault has occurred.
208
	 */
209
	public Element getFault();
210
211
	/**
212
	 * Returns the XML serialized form of this ISOAPMessage.
213
	 * 
214
	 * @return An XML string.
215
	 * @see ISerializer
216
	 * @throws TransportException 
217
	 */
218
	public String toXML() throws TransportException;
219
220
}
(-)src/org/eclipse/wst/ws/internal/explorer/platform/wsdl/transport/SOAPTransport.java (+146 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 * IBM Corporation - initial API and implementation
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
13
 *******************************************************************************/
14
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport;
15
16
import javax.wsdl.extensions.ExtensibilityElement;
17
import javax.wsdl.extensions.soap.SOAPBinding;
18
19
import org.apache.axis.Constants;
20
import org.eclipse.wst.ws.internal.explorer.plugin.ExplorerPlugin;
21
import org.eclipse.wst.ws.internal.explorer.transport.IDeserializer;
22
import org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage;
23
import org.eclipse.wst.ws.internal.explorer.transport.ISOAPTransport;
24
import org.eclipse.wst.ws.internal.explorer.transport.ISerializer;
25
import org.eclipse.wst.ws.internal.explorer.transport.MessageContext;
26
import org.eclipse.wst.ws.internal.explorer.transport.SOAPMessage;
27
import org.eclipse.wst.ws.internal.explorer.transport.TransportException;
28
import org.eclipse.wst.ws.internal.parser.discovery.NetUtils;
29
30
/**
31
 * WSE's default implementation of ISOAPTransport
32
 */
33
public class SOAPTransport implements ISOAPTransport {
34
35
	static final String PROP_READ_ONLY = "prop_read_only";
36
	static final String PROP_RAW_BYTES = "prop_raw_bytes";
37
	
38
	/*
39
	 * Constructor.
40
	 */
41
	SOAPTransport() {}
42
43
	/* (non-Javadoc)
44
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPTransport#newSerializer()
45
	 */
46
	public ISerializer newSerializer() {		
47
		return new SOAPMessageProcessor();
48
	}
49
	
50
	/* (non-Javadoc)
51
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPTransport#newDeserializer()
52
	 */
53
	public IDeserializer newDeserializer() {
54
		return new SOAPMessageProcessor();
55
	}
56
57
	/*
58
	 * Check if the binding is supported
59
	 */
60
	private void checkBinding(ExtensibilityElement binding) throws TransportException {
61
		
62
		String bindingURI = binding.getElementType().getNamespaceURI();
63
		
64
		// looking for SOAP 1.1 binding
65
		if (!(binding instanceof SOAPBinding) ||
66
			!Constants.URI_WSDL11_SOAP.equals(bindingURI))
67
			throw new TransportException(ExplorerPlugin.getMessage("%MSG_ERROR_UNSUPPORTED_BINDING", new String[] { bindingURI }));
68
	}
69
	
70
	/* (non-Javadoc)
71
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPTransport#newMessage(org.eclipse.wst.ws.internal.explorer.transport.MessageContext)
72
	 */
73
	public ISOAPMessage newMessage(MessageContext context) throws TransportException {
74
		
75
		checkBinding(context.getBindingProtocol());
76
		
77
		SOAPMessageProcessor processor = new SOAPMessageProcessor();
78
		ISOAPMessage message = new SOAPMessage(context, processor);
79
		processor.initMessage(message);			
80
		return message;				
81
	}
82
	
83
	/*
84
	 * Check if the message uses a binding and transport that we support.
85
	 */
86
	private void checkMessage(ISOAPMessage message) throws TransportException {
87
		
88
		ExtensibilityElement binding = message.getMessageContext().getBindingProtocol(); 
89
		checkBinding(binding);
90
		
91
		SOAPBinding soapBinding = (SOAPBinding) binding; 
92
			
93
		if (!Constants.URI_SOAP11_HTTP.equals(soapBinding.getTransportURI()))
94
			throw new TransportException(ExplorerPlugin.getMessage("%MSG_ERROR_UNSUPPORTED_TRANSPORT", new String[] { soapBinding.getTransportURI() }));
95
	}
96
		
97
	/*
98
	 * Create an HTTPTransport for internal use.
99
	 */
100
	private HTTPTransport createInternalTransport(String username, String password) {
101
102
		HTTPTransport internalTransport = new HTTPTransport();
103
		    
104
		if (username != null && password != null) {
105
			internalTransport.setHttpBasicAuthUsername(username);
106
			internalTransport.setHttpBasicAuthPassword(password);
107
		}
108
		
109
		return internalTransport;
110
	}	
111
	
112
	/* (non-Javadoc)
113
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPTransport#send(java.lang.String, java.lang.String, java.lang.String, org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage)
114
	 */
115
	public ISOAPMessage send(String url, String username, String password, ISOAPMessage message) throws TransportException {
116
		
117
		checkMessage(message);			
118
								
119
		try {
120
			HTTPTransport internalTransport = createInternalTransport(username, password);
121
			internalTransport.send(NetUtils.createURL(url), (String) message.getProperty(ISOAPMessage.PROP_SOAP_ACTION), message.toXML());
122
			
123
			SOAPMessageProcessor processor = new SOAPMessageProcessor();
124
			ISOAPMessage reply = new SOAPMessage(message.getMessageContext(), processor);
125
			reply.setProperty(PROP_READ_ONLY, Boolean.TRUE);
126
			
127
			byte[] rawBytes = internalTransport.receiveBytes();
128
			
129
			try { 
130
				processor.deserialize(ISOAPMessage.ENVELOPE, rawBytes, reply);
131
			}
132
			catch (Exception e) {
133
				// if error occurs during deserialization, we want to save a copy of the actual raw bytes
134
				reply.setProperty(PROP_RAW_BYTES, rawBytes);
135
			}
136
					
137
			return reply;
138
		}
139
		catch (TransportException e) {
140
			throw e;
141
	    }
142
	    catch (Exception e) {
143
	    	throw new TransportException(e);
144
	    }			
145
	}		
146
}
(-)src/org/eclipse/wst/ws/internal/explorer/transport/ISOAPTransport.java (+59 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 * IBM Corporation - initial API and implementation
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
13
 *******************************************************************************/
14
package org.eclipse.wst.ws.internal.explorer.transport;
15
16
/**
17
 * The ISOAPTransport is the core piece of the Web Services Explorer transport stack.
18
 * It is responsible for invoking the web service and it also acts as the factory for
19
 * creating ISerialier, IDeserializer, and ISOAPMessage instances which make up the
20
 * rest of the WSE transport.
21
 */
22
public interface ISOAPTransport {		
23
24
	/**
25
	 * Factory method for ISerializer.
26
	 * 
27
	 * @return An instance of ISerializer.
28
	 */
29
	public ISerializer newSerializer();
30
	
31
	/**
32
	 * Factory method for IDeserializer.
33
	 * 
34
	 * @return An instance of IDeserializer.
35
	 */
36
	public IDeserializer newDeserializer();
37
	
38
	/**
39
	 * Factory method for ISOAPMessage.
40
	 * 
41
	 * @param context MessageContext encapsulating information about the web service operation.
42
	 * @return An instance of ISOAPMessage.
43
	 * @throws TransportException
44
	 */
45
	public ISOAPMessage newMessage(MessageContext context) throws TransportException;
46
	
47
	/**
48
	 * Invokes the web service operation by sending the SOAP message, then parsing the results
49
	 * into a response ISOAPMessage.
50
	 * 
51
	 * @param url The endpoint URL.
52
	 * @param username Username to use for basic auth protected endpoints.  Set to null if not required.  
53
	 * @param password Password to use for basic auth protected endpoints.  Set to null if not required.
54
	 * @param message The SOAP request message.
55
	 * @return An ISOAPMesage representing the response from the web service invocation.
56
	 * @throws TransportException
57
	 */
58
	public ISOAPMessage send(String url, String username, String password, ISOAPMessage message) throws TransportException;
59
}
(-)src/org/eclipse/wst/ws/internal/explorer/platform/wsdl/transport/HTTPTransport.java (+640 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2004, 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * 
8
 * Contributors:
9
 * IBM Corporation - initial API and implementation
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
12
 * 20060131   125777 jesper@selskabet.org - Jesper S Moller
13
 * 20060222   118019 andyzhai@ca.ibm.com - Andy Zhai
14
 * 20060222   128564 jesper@selskabet.org - Jesper S Moller
15
 * 20060823    99034 makandre@ca.ibm.com - Andrew Mak, WSE support for basic-authenticating firewalls
16
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
17
 *******************************************************************************/
18
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport;
19
20
import java.io.BufferedReader;
21
import java.io.ByteArrayInputStream;
22
import java.io.ByteArrayOutputStream;
23
import java.io.IOException;
24
import java.io.InputStream;
25
import java.io.InputStreamReader;
26
import java.io.OutputStream;
27
import java.net.Socket;
28
import java.net.SocketTimeoutException;
29
import java.net.URL;
30
import java.net.UnknownHostException;
31
import java.util.Hashtable;
32
import javax.net.ssl.SSLSocketFactory;
33
34
import org.eclipse.wst.ws.internal.explorer.platform.util.XMLUtils;
35
import org.eclipse.wst.ws.internal.explorer.transport.HTTPTransportException;
36
import org.w3c.dom.Element;
37
import sun.misc.BASE64Encoder;
38
39
public class HTTPTransport
40
{
41
  private final String SYS_PROP_HTTPS_PROXY_HOST = "https.proxyHost";
42
  private final String SYS_PROP_HTTPS_PROXY_PORT = "https.proxyPort";
43
  private final String SYS_PROP_HTTPS_NON_PROXY_HOSTS = "https.nonProxyHosts";
44
  private final String SYS_PROP_HTTP_PROXY_HOST = "http.proxyHost";
45
  private final String SYS_PROP_HTTP_PROXY_PORT = "http.proxyPort";
46
  private final String SYS_PROP_HTTP_PROXY_USER_NAME = "http.proxyUserName";
47
  private final String SYS_PROP_HTTP_PROXY_PASSWORD = "http.proxyPassword";
48
  private final String SYS_PROP_HTTP_NON_PROXY_HOSTS = "http.nonProxyHosts";
49
  
50
  private final String HTTP_METHOD = "POST";
51
  private final String HTTP_CONNECT = "CONNECT";
52
  private final String HTTP_VERSION_1_0 = "HTTP/1.0";
53
  private final String HTTP_VERSION = "HTTP/1.1";
54
  private final String HTTP_HEADER_SOAP_ACTION = "SOAPAction";
55
  public static final String HTTP_HEADER_AUTH = "Authorization";
56
  public static final String HTTP_HEADER_WWW_AUTH = "WWW-Authenticate";
57
  private final String HTTP_HEADER_PROXY_AUTH = "Proxy-authorization";
58
  private final String HTTP_HEADER_COOKIE = "Cookie";
59
  private final String HTTP_HEADER_COOKIE2 = "Cookie2";
60
  private final String HTTP_HEADER_HOST = "Host";
61
  private final String HTTP_HEADER_CONTENT_TYPE = "Content-Type";
62
  public static final String HTTP_HEADER_CONTENT_LENGTH = "Content-Length";
63
  private final String HTTP_HEADER_ACCEPT = "Accept";
64
  private final String HTTP_HEADER_USER_AGENT = "User-Agent";
65
  private final String HTTP_HEADER_CACHE_CONTROL = "Cache-Control";
66
  private final String HTTP_HEADER_PRAGMA = "Pragma";
67
  private final String HTTP_HEADER_TRANSFER_ENCODEING = "Transfer-Encoding";
68
  private final String HTTP_HEADER_CONNECTION = "Connection";
69
  
70
  private final int HTTP_CODE_CONTINUE = 100;
71
  private final int HTTP_CODE_OK = 200;
72
  private final int HTTP_CODE_EXCEPTION = 300;
73
74
  private final String IBM_WEB_SERVICES_EXPLORER = "IBM Web Services Explorer";
75
  private final String TEXT_XML = "text/xml";
76
  private final String CONTENT_TYPE_VALUE = "text/xml; charset=utf-8";
77
  private final String ACCEPT_VALUE = "application/soap+xml, application/dime, multipart/related, text/*";
78
  public static final String BASIC = "Basic";
79
  private final String NO_CACHE = "no-cache";
80
  private final String CHUNKED = "chunked";
81
  private final String CLOSE = "close";
82
  private final String HTTPS = "https";
83
  private final char QUOTE = '\"';
84
  public static final char COLON = ':';
85
  private final char SPACE = ' ';
86
  private final char TAB = '\t';
87
  private final char R = '\r';
88
  private final char N = '\n';
89
  private final char ROOT = '/';
90
  private final String NEW_LINE = "\r\n";
91
  private final String EMPTY_STRING = "";
92
93
  private final int DEFAULT_HTTP_PORT = 80;
94
  private final int DEFAULT_HTTPS_PORT = 443;
95
  private final String DEFAULT_SOAP_ENCODING = "UTF-8";
96
  private final String DEFAULT_HTTP_HEADER_ENCODING = "iso-8859-1";
97
  private final boolean DEFAULT_CASE_SENSITIVE_FOR_HOST_NAME = false;
98
99
  private String httpBasicAuthUsername;
100
  private String httpBasicAuthPassword;
101
  private boolean maintainSession = false;
102
  private String cookie;
103
  private String cookie2;
104
  private HTTPResponse httpResponse;
105
106
  public String getHttpBasicAuthUsername()
107
  {
108
    return httpBasicAuthUsername;
109
  }
110
  
111
  public void setHttpBasicAuthUsername(String httpBasicAuthUsername)
112
  {
113
    this.httpBasicAuthUsername = httpBasicAuthUsername;
114
  }
115
  
116
  public String getHttpBasicAuthPassword()
117
  {
118
    return httpBasicAuthPassword;
119
  }
120
  
121
  public void setHttpBasicAuthPassword(String httpBasicAuthPassword)
122
  {
123
    this.httpBasicAuthPassword = httpBasicAuthPassword;
124
  }
125
126
  private String getMethod(URL url)
127
  {
128
    StringBuffer sb = new StringBuffer(HTTP_METHOD);
129
    sb.append(SPACE);
130
    String protocol = url.getProtocol();
131
    String httpProxyHost = System.getProperty(SYS_PROP_HTTP_PROXY_HOST);
132
    String httpsProxyHost = System.getProperty(SYS_PROP_HTTPS_PROXY_HOST);
133
    if (protocol.equalsIgnoreCase("http") && httpProxyHost != null && httpProxyHost.length() > 0)
134
    {
135
      sb.append(url.toString());
136
    }
137
    else if (protocol.equalsIgnoreCase("https") && httpsProxyHost != null && httpsProxyHost.length() > 0)
138
    {
139
      sb.append(url.toString());
140
    }
141
    else
142
    {
143
      String file = url.getFile();
144
      if (file != null && file.length() > 0)
145
        sb.append(file);
146
      else
147
        sb.append(ROOT);
148
    }
149
    sb.append(SPACE);
150
    sb.append(HTTP_VERSION);
151
    sb.append(NEW_LINE);
152
    return sb.toString();
153
  }
154
155
  private String getHost(URL url)
156
  {
157
    StringBuffer sb = new StringBuffer(HTTP_HEADER_HOST);
158
    sb.append(COLON);
159
    sb.append(SPACE);
160
    sb.append(url.getHost());
161
    sb.append(COLON);
162
    int port = url.getPort();
163
    if (port > 0)
164
      sb.append(String.valueOf(port));
165
    else if (url.getProtocol().equalsIgnoreCase(HTTPS))
166
      sb.append(DEFAULT_HTTPS_PORT);
167
    else
168
      sb.append(DEFAULT_HTTP_PORT);
169
    sb.append(NEW_LINE);
170
    return sb.toString();
171
  }
172
  
173
  private String getContentType()
174
  {
175
    return getHTTPHeader(HTTP_HEADER_CONTENT_TYPE, CONTENT_TYPE_VALUE);
176
  }
177
  
178
  private String getContentLength(byte[] payloadAsBytes)
179
  {
180
    return getHTTPHeader(HTTP_HEADER_CONTENT_LENGTH, String.valueOf(payloadAsBytes.length));
181
  }
182
183
  private String getSOAPAction(String soapAction)
184
  {
185
    StringBuffer sb = new StringBuffer(HTTP_HEADER_SOAP_ACTION);
186
    sb.append(COLON);
187
    sb.append(SPACE);
188
    sb.append(QUOTE);
189
    if (soapAction != null)
190
      sb.append(soapAction);
191
    sb.append(QUOTE);
192
    sb.append(NEW_LINE);
193
    return sb.toString();
194
  }
195
  
196
  private String getCookie()
197
  {
198
    if (maintainSession)
199
      return getHTTPHeader(HTTP_HEADER_COOKIE, cookie);
200
    else
201
      return EMPTY_STRING;
202
  }
203
  
204
  private String getCookie2()
205
  {
206
    if (maintainSession)
207
      return getHTTPHeader(HTTP_HEADER_COOKIE2, cookie2);
208
    else
209
      return EMPTY_STRING;
210
  }
211
  
212
  private String getWWWAuthentication()
213
  {
214
    if (httpBasicAuthUsername != null && httpBasicAuthPassword != null)
215
    {
216
      StringBuffer sb = new StringBuffer(httpBasicAuthUsername);
217
      sb.append(COLON);
218
      sb.append(httpBasicAuthPassword);
219
      BASE64Encoder encoder = new BASE64Encoder();
220
      String encodedUserNamePassword = encoder.encode(sb.toString().getBytes());
221
      sb.setLength(0);
222
      sb.append(HTTP_HEADER_AUTH);
223
      sb.append(COLON);
224
      sb.append(SPACE);
225
      sb.append(BASIC);
226
      sb.append(SPACE);
227
      sb.append(encodedUserNamePassword);
228
      sb.append(NEW_LINE);
229
      return sb.toString();
230
    }
231
    else
232
      return EMPTY_STRING;
233
  }
234
  
235
  private String getProxyAuthentication()
236
  {
237
    String proxyUserName = System.getProperty(SYS_PROP_HTTP_PROXY_USER_NAME);
238
    String proxyPassword = System.getProperty(SYS_PROP_HTTP_PROXY_PASSWORD);
239
    if (proxyUserName != null && proxyPassword != null)
240
    {
241
      StringBuffer sb = new StringBuffer(proxyUserName);
242
      sb.append(COLON);
243
      sb.append(proxyPassword);
244
      BASE64Encoder encoder = new BASE64Encoder();
245
      String encodedUserNamePassword = encoder.encode(sb.toString().getBytes());
246
      sb.setLength(0);
247
      sb.append(HTTP_HEADER_PROXY_AUTH);
248
      sb.append(COLON);
249
      sb.append(SPACE);
250
      sb.append(BASIC);
251
      sb.append(SPACE);
252
      sb.append(encodedUserNamePassword);
253
      sb.append(NEW_LINE);
254
      return sb.toString();
255
    }
256
    else
257
      return EMPTY_STRING;
258
  }
259
  
260
  private String getAccept()
261
  {
262
    return getHTTPHeader(HTTP_HEADER_ACCEPT, ACCEPT_VALUE);
263
  }
264
  
265
  private String getUserAgent()
266
  {
267
    return getHTTPHeader(HTTP_HEADER_USER_AGENT, IBM_WEB_SERVICES_EXPLORER);
268
  }
269
  
270
  private String getCacheControl()
271
  {
272
    return getHTTPHeader(HTTP_HEADER_CACHE_CONTROL, NO_CACHE);
273
  }
274
  
275
  private String getPragma()
276
  {
277
    return getHTTPHeader(HTTP_HEADER_PRAGMA, NO_CACHE);
278
  }
279
  
280
  private String getConnection()
281
  {
282
    return getHTTPHeader(HTTP_HEADER_CONNECTION, CLOSE);
283
  }
284
  
285
  private String getHTTPHeader(String key, String value)
286
  {
287
    if (value != null)
288
    {
289
      StringBuffer sb = new StringBuffer(key);
290
      sb.append(COLON);
291
      sb.append(SPACE);
292
      sb.append(value);
293
      sb.append(NEW_LINE);
294
      return sb.toString();
295
    }
296
    else
297
      return EMPTY_STRING;
298
  }
299
300
  public void send(URL url, String soapAction, String payload) throws UnknownHostException, IOException
301
  {
302
    byte[] payloadAsUTF8 = payload.getBytes(DEFAULT_SOAP_ENCODING);
303
       
304
    StringBuffer httpHeader = new StringBuffer();
305
    httpHeader.append(getMethod(url));
306
    httpHeader.append(getHost(url));
307
    httpHeader.append(getContentType());
308
    httpHeader.append(getContentLength(payloadAsUTF8));
309
    httpHeader.append(getAccept());
310
    httpHeader.append(getUserAgent());
311
    httpHeader.append(getCacheControl());
312
    httpHeader.append(getPragma());
313
    httpHeader.append(getSOAPAction(soapAction));
314
    httpHeader.append(getWWWAuthentication());
315
    httpHeader.append(getProxyAuthentication());
316
    httpHeader.append(getCookie());
317
    httpHeader.append(getCookie2());
318
    httpHeader.append(getConnection());
319
    httpHeader.append(NEW_LINE); // new line between the HTTP header and the payload
320
    Socket socket = buildSocket(url);
321
    InputStream is = socket.getInputStream();
322
    OutputStream os = socket.getOutputStream();
323
    os.write(httpHeader.toString().getBytes(DEFAULT_HTTP_HEADER_ENCODING));
324
    os.write(payloadAsUTF8);
325
    os.flush();
326
    httpResponse = new HTTPResponse();
327
    readHTTPResponseHeader(is, httpResponse);
328
    int code = httpResponse.getStatusCode();
329
    if (code == HTTP_CODE_CONTINUE)
330
    {
331
      httpResponse.reset();
332
      readHTTPResponseHeader(is, httpResponse);
333
    }
334
    readHTTPResponsePayload(is, httpResponse);
335
    os.close();
336
    is.close();
337
    socket.close();
338
    code = httpResponse.getStatusCode();
339
    String contentType = httpResponse.getHeader(HTTP_HEADER_CONTENT_TYPE.toLowerCase());
340
    if (code >= HTTP_CODE_EXCEPTION && (contentType == null || contentType.toLowerCase().indexOf(TEXT_XML.toLowerCase()) == -1))
341
      throw new HTTPTransportException(code, httpResponse.getStatusMessage(), httpResponse.getHeaders());
342
  }
343
344
  private void readHTTPResponseHeader(InputStream is, HTTPResponse resp) throws IOException
345
  {
346
    byte b = 0;
347
    int len = 0;
348
    int colonIndex = -1;
349
    String key;
350
    String value;
351
    boolean readTooMuch = false;
352
    ByteArrayOutputStream baos;
353
    for (baos = new ByteArrayOutputStream(4096);;)
354
    {
355
      if (!readTooMuch)
356
        b = (byte)is.read();
357
      if (b == -1)
358
        break;
359
      readTooMuch = false;
360
      if ((b != R) && (b != N))
361
      {
362
        if ((b == COLON) && (colonIndex == -1))
363
          colonIndex = len;
364
        len++;
365
        baos.write(b);
366
      }
367
      else if (b == R)
368
        continue;
369
      else // b == N
370
      {
371
        if (len == 0)
372
          break;
373
        b = (byte)is.read();
374
        readTooMuch = true;
375
        // A space or tab at the begining of a line means the header continues.
376
        if ((b == SPACE) || (b == TAB))
377
          continue;
378
        baos.close();
379
        byte[] bArray = baos.toByteArray();
380
        baos.reset();
381
        if (colonIndex != -1)
382
        {
383
          key = new String(bArray, 0, colonIndex, DEFAULT_HTTP_HEADER_ENCODING);
384
          value = new String(bArray, colonIndex + 1, len - 1 - colonIndex, DEFAULT_HTTP_HEADER_ENCODING);
385
          colonIndex = -1;
386
        }
387
        else
388
        {
389
          key = new String(bArray, 0, len, DEFAULT_HTTP_HEADER_ENCODING);
390
          value = EMPTY_STRING;
391
        }
392
        if (!resp.isStatusSet())
393
        {
394
          // Reader status code
395
          int start = key.indexOf(SPACE) + 1;
396
          String s = key.substring(start).trim();
397
          int end = s.indexOf(SPACE);
398
          if (end != -1)
399
            s = s.substring(0, end);
400
          try
401
          {
402
            resp.setStatusCode(Integer.parseInt(s));
403
          }
404
          catch (NumberFormatException nfe)
405
          {
406
            resp.setStatusCode(-1);
407
          }
408
          resp.setStatusMessage(key.substring(start + end + 1));
409
        }
410
        else
411
          resp.addHeader(key.toLowerCase().trim(), value.trim());
412
        len = 0;
413
      }
414
    }
415
    baos.close();
416
  }
417
418
  private void readHTTPResponsePayload(InputStream is, HTTPResponse resp) throws IOException
419
  {
420
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
421
    try
422
    {
423
      byte b = (byte)is.read();
424
      while (b != -1)
425
      {
426
        baos.write(b);
427
        b = (byte)is.read();
428
      }
429
    }
430
    catch (SocketTimeoutException ste)
431
    {
432
    }
433
    baos.close();
434
    resp.setPayload(baos.toByteArray());
435
  }
436
437
  /**
438
   * Receives the bytes from the last web service invocation.  This is used by WSE's default
439
   * SOAP transport.
440
   * 
441
   * @return A byte array.
442
   * @throws IOException
443
   */
444
  byte[] receiveBytes() throws IOException
445
  {
446
    if (httpResponse != null)
447
    {
448
        byte[] payload = httpResponse.getPayload();
449
        if (CHUNKED.equalsIgnoreCase(httpResponse.getHeader(HTTP_HEADER_TRANSFER_ENCODEING.toLowerCase())))
450
        {
451
          ByteArrayInputStream bais = new ByteArrayInputStream(payload);
452
          ChunkedInputStream cis = new ChunkedInputStream(bais);
453
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
454
          byte b;
455
          while ((b = (byte)cis.read()) != -1)
456
            baos.write(b);
457
          baos.close();
458
          cis.close();
459
          bais.close();
460
          return baos.toByteArray();
461
        }
462
        else
463
        {
464
          return payload;
465
        }
466
    }
467
    return null;
468
  }
469
  
470
  /**
471
   * This method is deprecated after WSE swtiches to using a pluggable transport via enhancement 176493.
472
   * The core functionality of this method is refactored to the receiveBytes() method. 
473
   * 
474
   * @deprecated
475
   */
476
  public BufferedReader receive()
477
  {
478
    try
479
    {
480
      byte[] payload = receiveBytes();
481
      if (payload != null) {
482
    	Element soapEnvelope = XMLUtils.byteArrayToElement(payload, false);
483
        // remove XML namespace declaration
484
        if (soapEnvelope != null)
485
          return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(XMLUtils.serialize(soapEnvelope, true).getBytes(DEFAULT_SOAP_ENCODING)), DEFAULT_SOAP_ENCODING)); 
486
      }
487
    }
488
    catch (Throwable t)
489
    {
490
    }
491
    return null;
492
  }
493
494
  public Hashtable getHeaders()
495
  {
496
    Hashtable headers = new Hashtable();
497
    if (httpResponse != null)
498
      headers.putAll(httpResponse.getHeaders());
499
    return headers;
500
  }
501
502
  /**
503
   * Builds the first line of a connection request to the proxy server
504
   * 
505
   * @param url The URL that we want to ultimately connect to.
506
   * @return A string of the form "CONNECT &lt;hostname&gt;:&lt;port&gt; HTTP/1.0".
507
   */
508
  private StringBuffer getConnectMethod(URL url) {
509
	
510
	  StringBuffer sb = new StringBuffer(HTTP_CONNECT);
511
	  sb.append(SPACE);	  
512
	  sb.append(url.getHost());
513
	  sb.append(COLON);
514
	  sb.append(url.getPort());
515
	  sb.append(SPACE);
516
	  sb.append(HTTP_VERSION_1_0);
517
	  sb.append(NEW_LINE);
518
	  return sb;
519
  }
520
  
521
  /**
522
   * Construct a socket to the proxy server which be used to tunnel through.
523
   * 
524
   * @param url The URL that we want to ultimately connect to.
525
   * @param proxyHost The proxy host.
526
   * @param proxyPort The proxy port.
527
   * @return A connected socket to the proxy server. 
528
   * @throws IOException 
529
   */
530
  private Socket buildTunnelSocket(URL url, String proxyHost, int proxyPort) throws IOException {
531
532
	  StringBuffer httpHeader = new StringBuffer();
533
	  httpHeader.append(getConnectMethod(url));
534
	  httpHeader.append(getProxyAuthentication());       
535
	  httpHeader.append(NEW_LINE);
536
    
537
	  Socket tunnel = new Socket(proxyHost, proxyPort);
538
    
539
	  InputStream  is = tunnel.getInputStream();
540
	  OutputStream os = tunnel.getOutputStream();
541
    
542
	  os.write(httpHeader.toString().getBytes(DEFAULT_HTTP_HEADER_ENCODING));        
543
	  os.flush();
544
    
545
	  HTTPResponse httpResponse = new HTTPResponse();
546
	  readHTTPResponseHeader(is, httpResponse);
547
    
548
	  int code = httpResponse.getStatusCode();
549
550
	  // ensure we are successfully connected to the proxy
551
	  if (code != HTTP_CODE_OK)
552
		  throw new HTTPTransportException(code, httpResponse.getStatusMessage(), httpResponse.getHeaders());
553
	  
554
	  return tunnel;
555
  }
556
  
557
  private Socket buildSocket(URL url) throws UnknownHostException, IOException
558
  {
559
    Socket s = null;
560
    String host = url.getHost();
561
    int port = url.getPort();
562
    String proxyHost = System.getProperty(SYS_PROP_HTTP_PROXY_HOST);
563
    int proxyPort = Integer.getInteger(SYS_PROP_HTTP_PROXY_PORT, DEFAULT_HTTP_PORT).intValue();
564
    
565
    String nonProxyHosts = System.getProperty(SYS_PROP_HTTP_NON_PROXY_HOSTS);
566
567
    //  String proxyUserName = System.getProperty(SYS_PROP_HTTP_PROXY_USER_NAME);
568
    //  String proxyPassword = System.getProperty(SYS_PROP_HTTP_PROXY_PASSWORD);
569
    if (url.getProtocol().equalsIgnoreCase(HTTPS))
570
    {
571
      proxyHost = System.getProperty(SYS_PROP_HTTPS_PROXY_HOST);
572
      proxyPort = Integer.getInteger(SYS_PROP_HTTPS_PROXY_PORT, DEFAULT_HTTPS_PORT).intValue();
573
      nonProxyHosts = System.getProperty(SYS_PROP_HTTPS_NON_PROXY_HOSTS);
574
575
      if (proxyHost != null && proxyHost.length() > 0 && !isHostInNonProxyHosts(host, nonProxyHosts, DEFAULT_CASE_SENSITIVE_FOR_HOST_NAME))
576
      {
577
        // SSL with proxy server
578
        Socket tunnel = buildTunnelSocket(url, proxyHost, proxyPort);       
579
        s = ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(tunnel, host, port, true);    	  
580
      }
581
      else
582
        s = SSLSocketFactory.getDefault().createSocket(host, (port > 0 ? port : DEFAULT_HTTPS_PORT));
583
      // Removing dependency on soap.jar
584
      //  s = SSLUtils.buildSSLSocket(host, (port > 0 ? port : DEFAULT_HTTPS_PORT), proxyHost, proxyPort);
585
      // TODO:
586
      // Build an SSL socket that supports proxyUser and proxyPassword,
587
      // as demonstrated in the following (original) line of code:
588
      //  s = SSLUtils.buildSSLSocket(host, (port > 0 ? port : DEFAULT_HTTPS_PORT), proxyHost, proxyPort, proxyUserName, proxyPassword);
589
    }
590
    else if (proxyHost != null && proxyHost.length() > 0 && !isHostInNonProxyHosts(host, nonProxyHosts, DEFAULT_CASE_SENSITIVE_FOR_HOST_NAME))
591
      s = new Socket(proxyHost, proxyPort);
592
    else
593
      s = new Socket(host, (port > 0 ? port : DEFAULT_HTTP_PORT));
594
    return s;
595
  }
596
  
597
  private boolean isHostInNonProxyHosts(String host, String nonProxyHosts, boolean caseSensitive)
598
  {
599
  	if (caseSensitive) return host.matches(createPatternFromString(nonProxyHosts));
600
  	else return host.toLowerCase().matches(createPatternFromString(nonProxyHosts.toLowerCase()));  
601
  }
602
  
603
  /*
604
   * This method is used to generate a valid regular expression for a 
605
   * normal java String used in the proxy mechanism. 
606
   * For example, the http.nonProxyHosts contains following String: 
607
   * "192.168.2.*|localhost|*.ibm.com" . It would be 
608
   * transformed into: "192\.168\.2\.\w*|localhost|\w*\.ibm\.com"
609
   * Thus, following host string would match above pattern:
610
   * 192.168.2.5 192.168.2. 192.168.2.666 192.168.2.w
611
   * localhost
612
   * torolab.ibm.com .ibm.com 123.ibm.com
613
   * 
614
   * Two transformations are done:
615
   * 1. replace all "." into "\." As in regular expression, '.' represents 
616
   *    any charater.  "\.' represents the real character '.'
617
   * 2. In order to get the real meaning of "*" used in property 
618
   *    http.nonProxyHosts, "\w*" is used to replace "*"
619
   *    "\w" represent a word character: [a-zA-Z_0-9]
620
   *    
621
   * Restriction:
622
   * The validity of address is not checked. 
623
   * (192.168.2.555 and 192.168.2.com are OK)
624
   * 
625
   * TODO check whether * occurs in address or hostname.
626
   * if it occuus in address representation, replace "*" with "\d*"
627
   * and check: value < 256 ?
628
   */
629
  private String createPatternFromString(String str) 
630
  {
631
    /* This is the same as following more understandable way:
632
	 * return str.replace(".", "\\.").replace("*", "\\w*");
633
	 * But, replace(CharSequence target, CharSequence replacement) can only be 
634
	 * supported after j2se 1.5, on the other hand, 
635
	 * replaceAll(String regex, String replacement) can be supported before 
636
	 * j2se 1.5.
637
	 */
638
    return str == null ? null : str.replaceAll("\\.", "\\.").replaceAll("\\*", "\\w*");
639
  }
640
}
(-)wsexplorer-src/org/eclipse/wst/ws/internal/explorer/platform/perspective/TransportProviderRegistry.java (+183 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 * IBM Corporation - initial API and implementation
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
13
 *******************************************************************************/
14
package org.eclipse.wst.ws.internal.explorer.platform.perspective;
15
16
import java.util.ArrayList;
17
import java.util.Arrays;
18
import java.util.Hashtable;
19
import java.util.Iterator;
20
import java.util.List;
21
import java.util.Map;
22
23
import org.eclipse.core.runtime.CoreException;
24
import org.eclipse.core.runtime.IConfigurationElement;
25
import org.eclipse.core.runtime.IExtensionRegistry;
26
import org.eclipse.core.runtime.Platform;
27
import org.eclipse.core.runtime.Preferences;
28
import org.eclipse.wst.ws.internal.explorer.plugin.ExplorerPlugin;
29
import org.eclipse.wst.ws.internal.explorer.transport.ISOAPTransportProvider;
30
31
/**
32
 * This class is responsible for loading the Web Services Explorer's transport provider
33
 * extensions and instantiating them when needed. 
34
 */
35
public class TransportProviderRegistry {
36
37
	private static final String PREF_TRANSPORT_PROVIDERS = "TRANSPORT_PROVIDERS";	
38
	private static final String EXTENSION_NAME           = "wseTransportProvider";
39
	private static final String SOAP_TRANSPORT_PROVIDER  = "soapTransportProvider";
40
	private static final String NAMESPACE_URI            = "namespaceURI";
41
	private static final String TRANSPORT_URI            = "transportURI";
42
	
43
	private static TransportProviderRegistry instance = null;
44
	
45
	private List preferredIDs        = null; 
46
	private Map soapProviderElements = null;
47
	private Map soapProviderCache    = null;
48
	
49
	/**
50
	 * Returns a singleton instance of this TransportProviderRegistry.
51
	 *  
52
	 * @return An instance of this class.
53
	 */
54
	public synchronized static TransportProviderRegistry getInstance() {
55
		if (instance == null)
56
			instance = new TransportProviderRegistry();
57
		return instance;
58
	}
59
	
60
	/*
61
	 * Constructor.
62
	 */
63
	private TransportProviderRegistry() {		
64
		
65
		// get the preference value
66
		Preferences preferences = ExplorerPlugin.getInstance().getPluginPreferences();
67
		String transportProviders = preferences.getString(PREF_TRANSPORT_PROVIDERS).replaceAll("\\s", "");
68
		
69
		// split it into a list of preferred transport provider IDs
70
		if (transportProviders.length() == 0)
71
			preferredIDs = new ArrayList();
72
		else			
73
			preferredIDs = Arrays.asList(transportProviders.split(","));
74
		
75
		// now find all extenders
76
		IExtensionRegistry registry = Platform.getExtensionRegistry();
77
	    IConfigurationElement[] configs = 
78
	    	registry.getConfigurationElementsFor(ExplorerPlugin.ID, EXTENSION_NAME); 
79
80
	    // currently we only have one type of providers: SOAP transport providers
81
	    soapProviderElements = new Hashtable();	    
82
	    for (int i = 0; i < configs.length; i++) {	    		    	
83
    		if (SOAP_TRANSPORT_PROVIDER.equals(configs[i].getName())) {	    			
84
    			String id = configs[i].getAttribute("id");
85
    			soapProviderElements.put(id, configs[i]);    			    				
86
    		}	    		    	
87
	    }
88
	    
89
	    soapProviderCache = new Hashtable();
90
	}		
91
	
92
	/*
93
	 * Determine if the URIs match.
94
	 */
95
	private boolean uriMatch(String required, String supported) {
96
		
97
		// not specified mean support everything
98
		if (supported == null)
99
			return true;
100
				
101
		if (!required.endsWith("/"))  required += "/";
102
		if (!supported.endsWith("/")) supported += "/";
103
		
104
		return required.equals(supported);
105
	}
106
	
107
	/*
108
	 * Create the extension for the given key, but only if it supports the binding namespace and transport
109
	 */
110
	private ISOAPTransportProvider createExtension(Object key, String namespaceURI, String transportURI) {
111
		
112
		IConfigurationElement element = (IConfigurationElement) soapProviderElements.get(key);						
113
		if (element == null)
114
			return null;
115
		
116
		boolean supportsNamespace = uriMatch(namespaceURI, element.getAttribute(NAMESPACE_URI));
117
		boolean supportsTransport = uriMatch(transportURI, element.getAttribute(TRANSPORT_URI));			
118
		
119
		if (supportsNamespace && supportsTransport) {			
120
			
121
			String providerClassID = element.getAttribute("class");
122
			Object obj = null;
123
			
124
			try {
125
				// check if we already have the transport provider cached,
126
				// if not, then create one
127
				synchronized (soapProviderCache) {
128
					obj = soapProviderCache.get(providerClassID); 					
129
					if (obj == null) {					
130
						obj = element.createExecutableExtension("class");
131
						soapProviderCache.put(providerClassID, obj);
132
					}					
133
				}
134
				return (ISOAPTransportProvider) obj;
135
			}
136
			catch (CoreException e) {}					
137
		}
138
		
139
		return null;
140
	}
141
	
142
	/**
143
	 * Get an ISOAPTransportProvider that supports the binding namespace and transport.  This method will
144
	 * first look for preferred IDs defined using the TRANSPORT_PROVIDERS preference key.  If a suitable
145
	 * provider is not found, it will then look at all other extenders in non-deterministic order.
146
	 * 
147
	 * @param namespaceURI The binding namespace URI
148
	 * @param transportURI The binding transport URI
149
	 * 
150
	 * @return Returns a suitable ISOAPTranportProvider for the given binding information, or null
151
	 * if there's no match.
152
	 */
153
	public ISOAPTransportProvider getSOAPTransportProvider(String namespaceURI, String transportURI) {
154
	
155
		ISOAPTransportProvider provider = null;
156
		
157
		Iterator iter = preferredIDs.iterator();
158
		
159
		// check preferred IDs first
160
		while (iter.hasNext()) {
161
			provider = createExtension(iter.next(), namespaceURI, transportURI);
162
			if (provider != null)
163
				return provider;
164
		}
165
		
166
		iter = soapProviderElements.keySet().iterator();
167
		
168
		// check rest of the providers
169
		while (iter.hasNext()) {
170
			Object key = iter.next();
171
		
172
			// already checked the preferred IDs
173
			if (preferredIDs.contains(key))
174
				continue;
175
			
176
			provider = createExtension(key, namespaceURI, transportURI);
177
			if (provider != null)
178
				return provider;			
179
		}
180
		
181
		return null;
182
	}
183
}
(-)src/org/eclipse/wst/ws/internal/explorer/platform/wsdl/transport/HTTPResponse.java (+91 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2004, 2005 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport;
12
13
import java.util.Hashtable;
14
import java.util.Map;
15
16
public class HTTPResponse
17
{
18
  private boolean statusSet;
19
  private int statusCode;
20
  private String statusMessage;
21
  private Hashtable headers;
22
  private byte[] payload;
23
24
  public HTTPResponse()
25
  {
26
    reset();
27
  }
28
29
  public void reset()
30
  {
31
    statusSet = false;
32
    statusCode = -1;
33
    statusMessage = null;
34
    if (headers != null)
35
      headers.clear();
36
    else
37
      headers = new Hashtable();
38
    payload = new byte[0];
39
  }
40
41
  public boolean isStatusSet()
42
  {
43
    return statusSet;
44
  }
45
46
  public int getStatusCode()
47
  {
48
    return statusCode;
49
  }
50
51
  public void setStatusCode(int statusCode)
52
  {
53
    statusSet = true;
54
    this.statusCode = statusCode;
55
  }
56
57
  public String getStatusMessage()
58
  {
59
    return statusMessage;
60
  }
61
62
  public void setStatusMessage(String statusMessage)
63
  {
64
    this.statusMessage = statusMessage;
65
  }
66
67
  public void addHeader(String key, String value)
68
  {
69
    headers.put(key, value);
70
  }
71
72
  public String getHeader(String key)
73
  {
74
    return (String) headers.get(key);
75
  }
76
77
  public Map getHeaders()
78
  {
79
    return headers;
80
  }
81
82
  public byte[] getPayload()
83
  {
84
    return payload;
85
  }
86
87
  public void setPayload(byte[] payload)
88
  {
89
    this.payload = payload;
90
  }
91
}
(-)schema/wseTransportProvider.exsd (+145 lines)
Added Link Here
1
<?xml version='1.0' encoding='UTF-8'?>
2
<!-- Schema file written by PDE -->
3
<schema targetNamespace="org.eclipse.wst.ws.explorer">
4
<annotation>
5
      <appInfo>
6
         <meta.schema plugin="org.eclipse.wst.ws.explorer" id="wseTransportProvider" name="Web Services Explorer Transport Provider"/>
7
      </appInfo>
8
      <documentation>
9
         [Enter description of this extension point.]
10
      </documentation>
11
   </annotation>
12
13
   <element name="extension">
14
      <complexType>
15
         <sequence minOccurs="1" maxOccurs="unbounded">
16
            <element ref="soapTransportProvider"/>
17
         </sequence>
18
         <attribute name="point" type="string" use="required">
19
            <annotation>
20
               <documentation>
21
                  A fully qualified identifier of the target extension point
22
               </documentation>
23
            </annotation>
24
         </attribute>
25
         <attribute name="id" type="string">
26
            <annotation>
27
               <documentation>
28
                  An optional identifier for this extension instance
29
               </documentation>
30
            </annotation>
31
         </attribute>
32
         <attribute name="name" type="string">
33
            <annotation>
34
               <documentation>
35
                  An optional name this extension instance
36
               </documentation>
37
               <appInfo>
38
                  <meta.attribute translatable="true"/>
39
               </appInfo>
40
            </annotation>
41
         </attribute>
42
      </complexType>
43
   </element>
44
45
   <element name="soapTransportProvider">
46
      <annotation>
47
         <documentation>
48
            This extension point entry allows an extender to plug in a new factory for creating org.eclipse.wst.ws.internal.explorer.transport.ISOAPTransport instances.  The ISOAPTranport is used by the Web Services Explorer for invoking web services operations that uses the SOAP message protocol.
49
         </documentation>
50
      </annotation>
51
      <complexType>
52
         <attribute name="class" type="string" use="required">
53
            <annotation>
54
               <documentation>
55
                  This class must implement the org.eclipse.wst.ws.internal.explorer.transport.ISOAPTransportProvider interface.
56
               </documentation>
57
               <appInfo>
58
                  <meta.attribute kind="java" basedOn="org.eclipse.wst.ws.internal.explorer.transport.ISOAPTransportProvider"/>
59
               </appInfo>
60
            </annotation>
61
         </attribute>
62
         <attribute name="id" type="string" use="required">
63
            <annotation>
64
               <documentation>
65
                  This id uniquely identifies this soapTransportProvider element.
66
               </documentation>
67
            </annotation>
68
         </attribute>
69
         <attribute name="name" type="string" use="required">
70
            <annotation>
71
               <documentation>
72
                  The name of this soapTransportProvider element.
73
               </documentation>
74
               <appInfo>
75
                  <meta.attribute translatable="true"/>
76
               </appInfo>
77
            </annotation>
78
         </attribute>
79
         <attribute name="namespaceURI" type="string">
80
            <annotation>
81
               <documentation>
82
                  The namespace URI of the soap:binding element that this transport provider claims support for.  For example, if this transport provider supports the SOAP 1.1 binding, the value of this attribute would be http://schemas.xmlsoap.org/wsdl/soap/.  If unspecified, this transport provider claims support for all SOAP bindings.
83
               </documentation>
84
            </annotation>
85
         </attribute>
86
         <attribute name="transportURI" type="string">
87
            <annotation>
88
               <documentation>
89
                  The transport protocol URI of the soap:binding element that this transport provider claims support for.  For example, if this transport provider supports SOAP over HTTP, the value of this attribute would be http://schemas.xmlsoap.org/soap/http.  If unspecified, this transport provider claims support for all transport protocols.
90
               </documentation>
91
            </annotation>
92
         </attribute>
93
      </complexType>
94
   </element>
95
96
   <annotation>
97
      <appInfo>
98
         <meta.section type="since"/>
99
      </appInfo>
100
      <documentation>
101
         &lt;b&gt;This extension point is part of an interim API that is still under development and expected to change significantly before reaching stability. It is being made available at this early stage to solicit feedback from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken (repeatedly) as the API evolves.&lt;/b&gt;
102
      </documentation>
103
   </annotation>
104
105
   <annotation>
106
      <appInfo>
107
         <meta.section type="examples"/>
108
      </appInfo>
109
      <documentation>
110
         [Enter extension point usage example here.]
111
      </documentation>
112
   </annotation>
113
114
   <annotation>
115
      <appInfo>
116
         <meta.section type="apiInfo"/>
117
      </appInfo>
118
      <documentation>
119
         [Enter API information here.]
120
      </documentation>
121
   </annotation>
122
123
   <annotation>
124
      <appInfo>
125
         <meta.section type="implementation"/>
126
      </appInfo>
127
      <documentation>
128
         [Enter information about supplied implementation of this extension point.]
129
      </documentation>
130
   </annotation>
131
132
   <annotation>
133
      <appInfo>
134
         <meta.section type="copyright"/>
135
      </appInfo>
136
      <documentation>
137
         Copyright (c) 2007 IBM Corporation and others.&lt;br&gt;
138
All rights reserved. This program and the accompanying materials are made 
139
available under the terms of the Eclipse Public License v1.0 which accompanies 
140
this distribution, and is available at &lt;a
141
href=&quot;http://www.eclipse.org/legal/epl-v10.html&quot;&gt;http://www.eclipse.org/legal/epl-v10.html&lt;/a&gt;
142
      </documentation>
143
   </annotation>
144
145
</schema>
(-)src/org/eclipse/wst/ws/internal/explorer/transport/ISerializer.java (+35 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 * IBM Corporation - initial API and implementation
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
13
 *******************************************************************************/
14
package org.eclipse.wst.ws.internal.explorer.transport;
15
16
/**
17
 * The ISerializer is responsible for taking an ISOAPMessage and serializing it
18
 * into an XML string.
19
 */
20
public interface ISerializer {
21
22
	/**
23
	 * Serialize the ISOAPMessage into an XML string.  The part parameter tells the method
24
	 * which part of the message (the envelope or the contents of the header or body) to
25
	 * serialize.  Note that "contents" refers to the list of elements inside the header
26
	 * or body, and not the header or body element itself.
27
	 * 
28
	 * @param part One of {@link ISOAPMessage#ENVELOPE}, {@link ISOAPMessage#HEADER_CONTENT}, or
29
	 * {@link ISOAPMessage#BODY_CONTENT}.
30
	 * @param message The ISOAPMessage to serialize.
31
	 * @return An XML string. 
32
	 * @throws TransportException
33
	 */
34
	public String serialize(int part, ISOAPMessage message) throws TransportException;
35
}
(-)src/org/eclipse/wst/ws/internal/explorer/transport/SOAPMessage.java (+339 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 * IBM Corporation - initial API and implementation
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
13
 *******************************************************************************/
14
package org.eclipse.wst.ws.internal.explorer.transport;
15
16
import java.util.Hashtable;
17
import java.util.Iterator;
18
import java.util.Map;
19
20
import org.w3c.dom.Attr;
21
import org.w3c.dom.Document;
22
import org.w3c.dom.Element;
23
import org.w3c.dom.NamedNodeMap;
24
import org.w3c.dom.Node;
25
import org.w3c.dom.NodeList;
26
27
/**
28
 * This is a default implementation of the ISOAPMessage interface that extenders of the Web
29
 * Services Explorer transport can use if they do not wish to implement their own message.  
30
 * This class is  implemented as a collection of loose pieces of the SOAP message, and each 
31
 * piece must be set individually (for example, setting the envelope element will not 
32
 * automatically populate the header or body elements).
33
 * <br/>
34
 * <br/>
35
 * This class does not know how to serialize itself.  It depends on an ISerializer provided by
36
 * the transport extender. 
37
 */
38
public final class SOAPMessage implements ISOAPMessage {
39
	
40
	private MessageContext context;
41
	private ISerializer serializer;
42
		
43
	private Map properties = new Hashtable();	
44
	
45
	private Element envelope = null;
46
	
47
	private Element header = null;
48
	private Element[] headerContent = null;
49
	
50
	private Element body = null;
51
	private Element[] bodyContent = null;	
52
		
53
	private Element fault = null;
54
		
55
	private String xml = null;
56
	
57
	/**
58
	 * Constructor.
59
	 * 
60
	 * @param context The MessageContext.
61
	 * @param serializer An ISerializer to use to serialize this message.
62
	 */
63
	public SOAPMessage(MessageContext context, ISerializer serializer) {
64
		this.context = context;
65
		this.serializer = serializer;
66
	}
67
	
68
	/* (non-Javadoc)
69
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage#getMessageContext()
70
	 */
71
	public MessageContext getMessageContext() {
72
		return context;
73
	}
74
		
75
	/* (non-Javadoc)
76
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage#setProperty(java.lang.String, java.lang.Object)
77
	 */
78
	public void setProperty(String key, Object value) {
79
		properties.put(key, value);
80
	}
81
	
82
	/* (non-Javadoc)
83
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage#getProperty(java.lang.String)
84
	 */
85
	public Object getProperty(String key) {
86
		return properties.get(key);
87
	}
88
	
89
	/* (non-Javadoc)
90
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage#setNamespaceTable(java.util.Map)
91
	 */
92
	public synchronized void setNamespaceTable(Map namespaceTable) {
93
		if (namespaceTable == null || envelope == null)
94
			return;
95
	
96
		Iterator iter = namespaceTable.entrySet().iterator();
97
		
98
		while (iter.hasNext()) {
99
			Map.Entry entry = (Map.Entry) iter.next();
100
			String name = "xmlns:" + entry.getValue();			
101
			envelope.setAttribute(name, entry.getKey().toString());			
102
		}
103
		
104
		xml = null;
105
	}
106
	
107
	/*
108
	 * If the attribute is a namespace declaration, the namespace prefix is returned.
109
	 * Otherwise null is returned.
110
	 */
111
	private String getNSPrefix(Attr attribute) {
112
		String name = attribute.getName();
113
		if (name.startsWith("xmlns:"))
114
			return name.substring(6);
115
		return null;
116
	}
117
	
118
	/* (non-Javadoc)
119
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage#getNamespaceTable()
120
	 */
121
	public Map getNamespaceTable() {
122
		
123
		Hashtable namespaceTable = new Hashtable();
124
		
125
		if (envelope != null) {
126
			NamedNodeMap attributes = envelope.getAttributes();
127
			for (int i = 0; i < attributes.getLength(); i++) {
128
				Attr attribute = (Attr) attributes.item(i);
129
				String prefix = getNSPrefix(attribute);
130
				if (prefix != null)
131
					namespaceTable.put(attribute.getValue(), prefix);
132
			}			
133
		}		
134
		
135
		return namespaceTable;
136
	}
137
	
138
	/*
139
	 * Appends a child node to a parent node, takes care of importing
140
	 * the child node if neccessary.
141
	 */
142
	private void appendNode(Node parent, Node child) {
143
		if (parent == null || child == null)
144
			return;
145
		
146
		Document owner = parent.getOwnerDocument();
147
		
148
		if (!owner.equals(child.getOwnerDocument()))
149
			child = owner.importNode(child, true);
150
		
151
		parent.appendChild(child);
152
	}
153
	
154
	/*
155
	 * Adds an array of elements to the parent element as child elements.
156
	 */
157
	private void appendChildren(Element parent, Element[] children) {
158
		if (parent == null || children == null)
159
			return;
160
		
161
		for (int i = 0; i < children.length; i++) {
162
			if (children[i] == null)
163
				continue;
164
			appendNode(parent, children[i]);
165
		}
166
	}		
167
	
168
	/* (non-Javadoc)
169
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage#setEnvelope(org.w3c.dom.Element)
170
	 */
171
	public synchronized void setEnvelope(Element envelope) {
172
		if (envelope == null)
173
			this.envelope = envelope;
174
		else
175
			this.envelope = (Element) envelope.cloneNode(false);
176
					
177
		xml = null;
178
	}
179
		
180
	/* (non-Javadoc)
181
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage#getEnvelope(boolean)
182
	 */
183
	public Element getEnvelope(boolean deep) {
184
		if (!deep)
185
			return envelope;
186
		
187
		synchronized (this) {
188
			if (envelope == null)
189
				return null;
190
			
191
			Element clonedEnvelope = (Element) envelope.cloneNode(false);
192
			
193
			if (headerContent != null && headerContent.length > 0)
194
				appendNode(clonedEnvelope, getHeader(true));
195
				
196
			appendNode(clonedEnvelope, getBody(true));
197
			
198
			return clonedEnvelope;	
199
		}
200
	}
201
	
202
	/* (non-Javadoc)
203
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage#setHeader(org.w3c.dom.Element)
204
	 */
205
	public synchronized void setHeader(Element header) {
206
		if (header == null)
207
			this.header = null;			
208
		else
209
			this.header = (Element) header.cloneNode(false);
210
211
		xml = null;
212
	}
213
	
214
	/* (non-Javadoc)
215
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage#getHeader(boolean)
216
	 */
217
	public Element getHeader(boolean deep) {
218
		if (!deep)
219
			return header;
220
		
221
		synchronized (this) {
222
			if (header == null)
223
				return null;
224
			
225
			Element clonedHeader = (Element) header.cloneNode(false);
226
			appendChildren(clonedHeader, headerContent);				
227
			return clonedHeader;
228
		}				
229
	}
230
	
231
	/* (non-Javadoc)
232
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage#setHeaderContent(org.w3c.dom.Element[])
233
	 */
234
	public synchronized void setHeaderContent(Element[] headerContent) {
235
		this.headerContent = headerContent;
236
		xml = null;
237
	}
238
	
239
	/* (non-Javadoc)
240
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage#getHeaderContent()
241
	 */
242
	public Element[] getHeaderContent() {
243
		return headerContent;
244
	}
245
	
246
	/* (non-Javadoc)
247
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage#setBody(org.w3c.dom.Element)
248
	 */
249
	public synchronized void setBody(Element body) {		
250
		if (body == null)
251
			this.body = null;
252
		else {
253
			this.body = (Element) body.cloneNode(false);
254
			
255
			if (!context.isDocumentStyle() && fault == null) {
256
				NodeList childElements = body.getElementsByTagName("*");
257
				if (childElements.getLength() > 0)
258
					this.body.appendChild(childElements.item(0).cloneNode(false));
259
			}
260
		}		
261
		xml = null;
262
	}
263
					
264
	/* (non-Javadoc)
265
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage#getBody(boolean)
266
	 */
267
	public Element getBody(boolean deep) {
268
		if (!deep)
269
			return body;
270
		
271
		synchronized (this) {
272
			if (body == null)
273
				return null;
274
		
275
			// copy the rpc wrapper element as well, if any
276
			Element clonedBody = (Element) body.cloneNode(true);		
277
			
278
			if (fault != null)
279
				appendNode(clonedBody, fault);
280
			else {
281
				Element target = clonedBody;
282
				
283
				// check for rpc wrapper
284
				if (clonedBody.getFirstChild() != null)
285
					target = (Element) clonedBody.getFirstChild();
286
				
287
				appendChildren(target, bodyContent);
288
			}
289
				
290
			return clonedBody;		
291
		}
292
	}
293
				
294
	/* (non-Javadoc)
295
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage#setBodyContent(org.w3c.dom.Element[])
296
	 */
297
	public synchronized void setBodyContent(Element[] bodyContent) {
298
		this.bodyContent = bodyContent;
299
		if (bodyContent != null)
300
			fault = null;
301
		xml = null;
302
	}
303
	
304
	/* (non-Javadoc)
305
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage#getBodyContent()
306
	 */
307
	public Element[] getBodyContent() {
308
		return bodyContent;
309
	}
310
	
311
	/* (non-Javadoc)
312
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage#setFault(org.w3c.dom.Element)
313
	 */
314
	public synchronized void setFault(Element fault) {
315
		this.fault = fault;
316
		if (fault != null) {
317
			if (body != null && body.getFirstChild() != null)
318
				body.removeChild(body.getFirstChild());
319
			bodyContent = null;
320
		}
321
		xml = null;
322
	}
323
	
324
	/* (non-Javadoc)
325
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage#getFault()
326
	 */
327
	public Element getFault() {
328
		return fault;
329
	}
330
		
331
	/* (non-Javadoc)
332
	 * @see org.eclipse.wst.ws.internal.explorer.transport.ISOAPMessage#toXML()
333
	 */
334
	public synchronized String toXML() throws TransportException {
335
		if (xml == null)
336
			xml = serializer.serialize(ENVELOPE, this);
337
		return xml;		
338
	}		
339
}
(-)src/org/eclipse/wst/ws/internal/explorer/transport/IDeserializer.java (+35 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 * IBM Corporation - initial API and implementation
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
13
 *******************************************************************************/
14
package org.eclipse.wst.ws.internal.explorer.transport;
15
16
/**
17
 * The IDeserializer is responsible for taking an XML string and deserializing it
18
 * into values to populate an ISOAPMessage.
19
 */
20
public interface IDeserializer {
21
	
22
	/**
23
	 * Deserialize the XML string into the ISOAPMessage.  The part parameter tells the method
24
	 * which part of the message (the envelope or the contents of the header or body) the XML
25
	 * string represents.  Note that "contents" refers to the list of elements inside the header
26
	 * or body, and not the header or body element itself.
27
	 * 
28
	 * @param part One of {@link ISOAPMessage#ENVELOPE}, {@link ISOAPMessage#HEADER_CONTENT}, or
29
	 * {@link ISOAPMessage#BODY_CONTENT}.
30
	 * @param xml The XML string to deserialize.
31
	 * @param message The ISOAPMessage to deserialize into.
32
	 * @throws TransportException
33
	 */
34
	public void deserialize(int part, String xml, ISOAPMessage message) throws TransportException;		
35
}
(-)src/org/eclipse/wst/ws/internal/explorer/platform/wsdl/util/SoapHelper.java (+143 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2002, 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * 
8
 * Contributors:
9
 * IBM Corporation - initial API and implementation
10
 * yyyymmdd bug      Email and other contact information
11
 * -------- -------- -----------------------------------------------------------
12
 * 20070305   117034 makandre@ca.ibm.com - Andrew Mak, Web Services Explorer should support SOAP Headers
13
 * 20070413   176493 makandre@ca.ibm.com - Andrew Mak, WSE: Make message/transport stack pluggable
14
 *******************************************************************************/
15
16
package org.eclipse.wst.ws.internal.explorer.platform.wsdl.util;
17
18
import java.util.Enumeration;
19
import java.util.Hashtable;
20
import org.apache.axis.Constants;
21
import org.eclipse.wst.ws.internal.explorer.platform.util.URLUtils;
22
import org.w3c.dom.Document;
23
import org.w3c.dom.Element;
24
25
public class SoapHelper
26
{
27
  private static Hashtable defaultSoapEnvelopeNamespaces_ = null;
28
  
29
  private static final void initDefaultSoapEnvelopeNamespaces()
30
  {
31
    defaultSoapEnvelopeNamespaces_ = new Hashtable();
32
    defaultSoapEnvelopeNamespaces_.put(Constants.URI_SOAP11_ENV,Constants.NS_PREFIX_SOAP_ENV);
33
    defaultSoapEnvelopeNamespaces_.put(Constants.URI_2001_SCHEMA_XSI,Constants.NS_PREFIX_SCHEMA_XSI);
34
    defaultSoapEnvelopeNamespaces_.put(Constants.URI_2001_SCHEMA_XSD,Constants.NS_PREFIX_SCHEMA_XSD);
35
  }
36
  
37
  public static final void addDefaultSoapEnvelopeNamespaces(Hashtable soapEnvelopeNamespaces)
38
  {
39
    if (defaultSoapEnvelopeNamespaces_ == null)
40
      initDefaultSoapEnvelopeNamespaces();
41
    Enumeration defaultSoapEnvelopeNamespaceURIs = defaultSoapEnvelopeNamespaces_.keys();
42
    while (defaultSoapEnvelopeNamespaceURIs.hasMoreElements())
43
    {
44
      String defaultSoapEnvelopeNamespaceURI = (String)defaultSoapEnvelopeNamespaceURIs.nextElement();
45
      soapEnvelopeNamespaces.put(defaultSoapEnvelopeNamespaceURI,(String)defaultSoapEnvelopeNamespaces_.get(defaultSoapEnvelopeNamespaceURI));
46
    }
47
  }
48
  
49
  public static final boolean isDefaultSoapEnvelopeNamespace(String namespaceURI,String namespacePrefix)
50
  {
51
    if (defaultSoapEnvelopeNamespaces_ == null)
52
      initDefaultSoapEnvelopeNamespaces();
53
    if (defaultSoapEnvelopeNamespaces_.get(namespaceURI) != null)
54
      return true;
55
    return false;
56
  }  
57
  
58
  public static final Element createSoapEnvelopeElement(Document doc,Hashtable soapEnvelopeNamespaceTable)
59
  {
60
    Element soapEnvelopeElement = doc.createElement("soapenv:Envelope");
61
    Enumeration e = soapEnvelopeNamespaceTable.keys();
62
    while (e.hasMoreElements())
63
    {
64
      String soapEnvelopeNamespaceURI = (String)e.nextElement();
65
      StringBuffer soapEnvelopeNamespaceAttr = new StringBuffer("xmlns:");
66
      soapEnvelopeNamespaceAttr.append((String)soapEnvelopeNamespaceTable.get(soapEnvelopeNamespaceURI));
67
      soapEnvelopeElement.setAttribute(soapEnvelopeNamespaceAttr.toString(),soapEnvelopeNamespaceURI);      
68
    }    
69
    return soapEnvelopeElement;
70
  }
71
  
72
  public static final Element createSoapHeaderElement(Document doc)
73
  {
74
    return doc.createElement("soapenv:Header");
75
  }
76
  
77
  public static final Element createSoapBodyElement(Document doc)
78
  {
79
    return doc.createElement("soapenv:Body");
80
  }
81
  
82
  public static final Element createRPCWrapperElement(Document doc,Hashtable soapEnvelopeNamespaceTable,String encodingNamespaceURI,String operationName, String encodingStyle)
83
  {
84
    int nsId = 0;
85
    StringBuffer wrapperElementName = new StringBuffer();
86
    String encodingNamespacePrefix = (String)soapEnvelopeNamespaceTable.get(encodingNamespaceURI);
87
    if (encodingNamespacePrefix != null)
88
      wrapperElementName.append(encodingNamespacePrefix);
89
    else
90
    {
91
      // Loop until we generate a unique prefix.
92
      do
93
      {
94
        wrapperElementName.setLength(0);
95
        wrapperElementName.append("ns").append(nsId);
96
        if (!soapEnvelopeNamespaceTable.containsValue(wrapperElementName.toString()))
97
          break;
98
        nsId++;
99
      } while (true);
100
      
101
      // need to ensure whatever prefix we choose is added to the namespace table
102
      // so that it will not be reused lated on
103
      soapEnvelopeNamespaceTable.put(encodingNamespaceURI, wrapperElementName.toString());
104
    }    
105
    String wrapperElementNamePrefix = wrapperElementName.toString();
106
    wrapperElementName.append(':').append(operationName);
107
    Element wrapperElement = doc.createElement(wrapperElementName.toString());
108
    StringBuffer namespaceAttrName = new StringBuffer("xmlns:");
109
    namespaceAttrName.append(wrapperElementNamePrefix);
110
    wrapperElement.setAttribute(namespaceAttrName.toString(),encodingNamespaceURI);
111
    if (encodingStyle != null)
112
      wrapperElement.setAttribute("soapenv:encodingStyle",encodingStyle);
113
    return wrapperElement;
114
  }
115
116
  public static final String encodeNamespaceDeclaration(String prefix, String uri)
117
  {
118
    StringBuffer sb = new StringBuffer();
119
    sb.append(prefix);
120
    sb.append(" ");
121
    sb.append(uri);
122
    String result = URLUtils.encode(sb.toString());
123
    return result;
124
  }
125
126
  public static final String[] decodeNamespaceDeclaration(String s)
127
  {
128
    String sCopy = URLUtils.decode(s);
129
    int index = sCopy.indexOf(" ");
130
    String[] nsDecl = new String[2];
131
    if (index != -1)
132
    {
133
      nsDecl[0] = sCopy.substring(0, index);
134
      nsDecl[1] = sCopy.substring(index+1, sCopy.length());
135
    }
136
    else
137
    {
138
      nsDecl[0] = null;
139
      nsDecl[1] = sCopy;
140
    }
141
    return nsDecl;
142
  }
143
}

Return to bug 176493