/**
  * processRequest processes PhaseIV Web Service calls. It creates a soap message from input string
  * xmlRequest and invokes Phase IV Web Service processRequest method.
  *
  * @param PhaseIV xmlRequest
  * @return PhaseIV xmlResponse
  * @throws Exception
  */
 public String processRequest(String xmlRequest, String clientURL) throws Exception {
   try {
     if (Utils.getInstance().isNullString(xmlRequest)
         || Utils.getInstance().isNullString(clientURL)) {
       logger.debug("Recieved xmlRequest or clientURL as null");
       return null;
     }
     logger.debug("processRequest--> xmlRequest :" + xmlRequest);
     ByteArrayInputStream inStream = new ByteArrayInputStream(xmlRequest.getBytes());
     StreamSource source = new StreamSource(inStream);
     MessageFactory msgFactory = MessageFactory.newInstance();
     SOAPMessage sMsg = msgFactory.createMessage();
     SOAPPart sPart = sMsg.getSOAPPart();
     sPart.setContent(source);
     MimeHeaders mimeHeader = sMsg.getMimeHeaders();
     mimeHeader.setHeader("SOAPAction", "http://ejbs.phaseiv.bsg.adp.com");
     logger.debug("processRequest-->in PhaseIVClient before call");
     SOAPMessage respMsg = executeCall(sMsg, clientURL);
     logger.debug("processRequest-->in PhaseIVClient after call");
     // SOAPFault faultCode =
     // respMsg.getSOAPPart().getEnvelope().getBody().getFault();
     ByteArrayOutputStream outStream = new ByteArrayOutputStream();
     respMsg.writeTo(outStream);
     logger.debug("processRequest xmlResponse:" + outStream.toString());
     return outStream.toString();
   } catch (Exception exp) {
     logger.error("processRequest --> Error while processing request : " + exp.getMessage());
     logger.error("processRequest --> error xmlRequest:" + xmlRequest);
     exp.printStackTrace();
     throw exp;
   }
 }
  private Object parseMessage() {
    // Consume SOAP message, if any
    // TODO: Add a SOAP handler in Parser.java
    if (soapAction != null) {
      try {
        MimeHeaders mime_headers = new MimeHeaders();

        for (Object k : headers.getIds()) {
          if (k instanceof String) {
            String name = (String) k;
            String value = Context.toString(ScriptableObject.getProperty(headers, name));

            mime_headers.addHeader(name, value);
          }
        }

        return MessageFactory.newInstance(SOAPConstants.DYNAMIC_SOAP_PROTOCOL)
            .createMessage(mime_headers, request.getInputStream());
      } catch (IOException ex) {
        throw new ESXXException("Unable to read SOAP message stream: " + ex.getMessage());
      } catch (SOAPException ex) {
        throw new ESXXException(400 /* Bad Request */, "Invalid SOAP message: " + ex.getMessage());
      } finally {
        try {
          request.getInputStream().close();
        } catch (Exception ignored) {
        }
      }
    } else if (contentType != null && contentLength > 0) {
      try {
        ESXX esxx = ESXX.getInstance();
        return esxx.parseStream(
            contentType,
            request.getInputStream(),
            URI.create("urn:x-esxx:incoming-request-entity"),
            null,
            new java.io.PrintWriter(request.getErrorWriter()),
            Context.getCurrentContext(),
            this);
      } catch (Exception ex) {
        throw new ESXXException(
            400 /* Bad Request */, "Unable to parse request entity: " + ex.getMessage(), ex);
      } finally {
        try {
          request.getInputStream().close();
        } catch (Exception ignored) {
        }
      }
    } else {
      // Return a dummy object
      return Context.getCurrentContext().newObject(this);
    }
  }
 private static Collection<String> parseSoapResponseForUrls(byte[] data)
     throws SOAPException, IOException {
   // System.out.println(new String(data));
   final Collection<String> urls = new ArrayList<>();
   MessageFactory factory = MessageFactory.newInstance(WS_DISCOVERY_SOAP_VERSION);
   final MimeHeaders headers = new MimeHeaders();
   headers.addHeader("Content-type", WS_DISCOVERY_CONTENT_TYPE);
   SOAPMessage message = factory.createMessage(headers, new ByteArrayInputStream(data));
   SOAPBody body = message.getSOAPBody();
   for (Node node : getNodeMatching(body, ".*:XAddrs")) {
     if (node.getTextContent().length() > 0) {
       urls.addAll(Arrays.asList(node.getTextContent().split(" ")));
     }
   }
   return urls;
 }
Exemple #4
0
  /*
   * Binds the passed object xml string to SOAP message.
   * The SOAP Message will then be sent across to the remote
   * provider for processing.
   * @param xmlString the request/response xml string to be bound
   * @return SOAPMessage constructed from the xml string
   */
  public SOAPMessage bind(String xmlString) {
    SOAPMessage msg = null;
    MimeHeaders mimeHeaders = new MimeHeaders();
    mimeHeaders.addHeader("Content-Type", "text/xml");
    StringBuffer envBegin = new StringBuffer(100);
    envBegin
        .append("<")
        .append(IFSConstants.SOAP_ENV_PREFIX)
        .append(":Envelope")
        .append(IFSConstants.SPACE)
        .append("xmlns:")
        .append(IFSConstants.SOAP_ENV_PREFIX)
        .append("=\"")
        .append(IFSConstants.SOAP_URI)
        .append("\">")
        .append(IFSConstants.NL)
        .append("<")
        .append(IFSConstants.SOAP_ENV_PREFIX)
        .append(":Body>")
        .append(IFSConstants.NL);

    StringBuffer envEnd = new StringBuffer(100);
    envEnd
        .append(IFSConstants.START_END_ELEMENT)
        .append(IFSConstants.SOAP_ENV_PREFIX)
        .append(":Body>")
        .append(IFSConstants.NL)
        .append(IFSConstants.START_END_ELEMENT)
        .append(IFSConstants.SOAP_ENV_PREFIX)
        .append(":Envelope>")
        .append(IFSConstants.NL);
    try {
      StringBuffer sb = new StringBuffer(300);
      sb.append(envBegin).append(xmlString).append(envEnd);
      if (FSUtils.debug.messageEnabled()) {
        FSUtils.debug.message("response created is: " + sb.toString() + "\n--------------------");
      }
      ByteArrayOutputStream bop = new ByteArrayOutputStream();
      bop.write(sb.toString().getBytes(IFSConstants.DEFAULT_ENCODING));
      msg = fac.createMessage(mimeHeaders, new ByteArrayInputStream(bop.toByteArray()));
    } catch (Exception e) {
      FSUtils.debug.error("could not build response:", e);
      return null;
    }
    return msg;
  }
Exemple #5
0
  public SOAPClient(String url, String soapAction)
      throws UnsupportedOperationException, SOAPException {
    // Create the connection
    SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
    conn = scf.createConnection();

    // Create message
    MessageFactory mf = MessageFactory.newInstance();
    soapRequest = mf.createMessage();
    wsdlURL = url;

    // add SOAP Action
    if (soapAction != null) {
      MimeHeaders hd = soapRequest.getMimeHeaders();
      hd.addHeader("SOAPAction", soapAction);
    }
  }
  private static SOAPMessage createSOAPRequest() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    String serverURI = "http://ws.cdyne.com/";

    // SOAP Envelope
    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("example", serverURI);

    /*
    Constructed SOAP Request Message:
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
        <SOAP-ENV:Header/>
        <SOAP-ENV:Body>
            <example:VerifyEmail>
                <example:email>[email protected]</example:email>
                <example:LicenseKey>123</example:LicenseKey>
            </example:VerifyEmail>
        </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
     */

    // SOAP Body
    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
    soapBodyElem1.addTextNode("*****@*****.**");
    SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
    soapBodyElem2.addTextNode("123");

    MimeHeaders headers = soapMessage.getMimeHeaders();
    headers.addHeader("SOAPAction", serverURI + "VerifyEmail");

    soapMessage.saveChanges();

    /* Print the request message */
    System.out.print("Request SOAP Message:");
    soapMessage.writeTo(System.out);
    System.out.println();

    return soapMessage;
  }
Exemple #7
0
  /**
   * Converts Document to SOAPMessage
   *
   * @param doc the source Document
   * @return SOAPMessage
   * @throws SOAPBindingException if an error occurs while converting the document
   * @supported.api
   */
  public static SOAPMessage DocumentToSOAPMessage(Document doc) throws SOAPBindingException {
    SOAPMessage msg = null;
    try {
      MimeHeaders mimeHeaders = new MimeHeaders();
      mimeHeaders.addHeader("Content-Type", "text/xml");

      String xmlstr = XMLUtils.print(doc);
      if (debug.messageEnabled()) {
        debug.message("Utils.DocumentToSOAPMessage: xmlstr = " + xmlstr);
      }
      msg =
          messageFactory.createMessage(
              mimeHeaders,
              new ByteArrayInputStream(xmlstr.getBytes(SOAPBindingConstants.DEFAULT_ENCODING)));
    } catch (Exception e) {
      debug.error("Utils.DocumentToSOAPMessage", e);
      throw new SOAPBindingException(e.getMessage());
    }
    return msg;
  }
 @Override
 public void mapTo(Context context, SOAPBindingData target) throws Exception {
   SOAPMessage soapMessage = target.getSOAPMessage();
   MimeHeaders mimeHeaders = soapMessage.getMimeHeaders();
   SOAPHeader soapHeader = soapMessage.getSOAPHeader();
   for (Property property : context.getProperties(Scope.IN)) {
     Object value = property.getValue();
     if (value != null) {
       String name = property.getName();
       QName qname = XMLHelper.createQName(name);
       boolean qualifiedForSoapHeader = Strings.trimToNull(qname.getNamespaceURI()) != null;
       if (qualifiedForSoapHeader && matches(qname)) {
         if (value instanceof Node) {
           Node domNode = soapHeader.getOwnerDocument().importNode((Node) value, true);
           soapHeader.appendChild(domNode);
         } else if (value instanceof Configuration) {
           Element configElement = new ElementPuller().pull(new StringReader(value.toString()));
           Node configNode = soapHeader.getOwnerDocument().importNode(configElement, true);
           soapHeader.appendChild(configNode);
         } else {
           String v = value.toString();
           if (SOAPHeadersType.XML.equals(getSOAPHeadersType())) {
             try {
               Element xmlElement = new ElementPuller().pull(new StringReader(v));
               Node xmlNode = soapHeader.getOwnerDocument().importNode(xmlElement, true);
               soapHeader.appendChild(xmlNode);
             } catch (Throwable t) {
               soapHeader.addChildElement(qname).setValue(v);
             }
           } else {
             soapHeader.addChildElement(qname).setValue(v);
           }
         }
       } else {
         if (matches(name)) {
           mimeHeaders.addHeader(name, String.valueOf(value));
         }
       }
     }
   }
 }
 static Map<String, List<String>> toMap(MimeHeaders headers) {
   HashMap<String, List<String>> map = new HashMap<String, List<String>>();
   for (Iterator<MimeHeader> i = headers.getAllHeaders(); i.hasNext(); ) {
     MimeHeader mh = i.next();
     List<String> values = map.get(mh.getName());
     if (values == null) {
       values = new ArrayList<String>();
       map.put(mh.getName(), values);
     }
     values.add(mh.getValue());
   }
   return map;
 }
Exemple #10
0
  /*
   * ???
   *
   * @param response
   * @param responseBean
   * @throws DOMException
   * @throws SOAPException
   */
  private void extractHeaderDataSOAP(SOAPMessage response, HttpResponseBean responseBean)
      throws SOAPException {
    // extract MimeHeaders
    MimeHeaders mime = response.getMimeHeaders();
    Iterator<MimeHeader> iter = mime.getAllHeaders();

    while (iter.hasNext()) {
      MimeHeader mimeH = iter.next();
      responseBean.addEntryToResponseHeaders(mimeH.getName(), mimeH.getValue());
    }

    // extract SOAPHeaders from the envelope and a them to the mimeHeaders
    if (response.getSOAPHeader() != null) {
      javax.xml.soap.SOAPHeader header = response.getSOAPHeader();

      NodeList nodes = header.getChildNodes();

      for (int x = 0; x < nodes.getLength(); x++) {
        // if the header entry contains child nodes - write them with the node names
        if (nodes.item(x).hasChildNodes()) {
          NodeList childnodes = nodes.item(x).getChildNodes();
          StringBuilder buff = new StringBuilder();
          for (int y = 0; y < childnodes.getLength(); y++) {
            if (!"".equals(buff.toString())) {
              buff.append(" ");
            }
            buff.append(childnodes.item(y).getLocalName()).append(":");
            buff.append(childnodes.item(y).getTextContent());
          }
          responseBean.addEntryToResponseHeaders(nodes.item(x).getLocalName(), buff.toString());
        } else {
          responseBean.addEntryToResponseHeaders(
              nodes.item(x).getLocalName(), nodes.item(x).getTextContent());
        }
      }
    }
  }
  protected SOAPMessage createQueryMessage() {
    String queryStr = getQueryString();

    if (log.isDebugEnabled()) {
      log.debug("MDX query: " + queryStr);
    }

    try {
      MessageFactory mf = MessageFactory.newInstance();
      SOAPMessage message = mf.createMessage();

      MimeHeaders mh = message.getMimeHeaders();
      mh.setHeader("SOAPAction", "\"urn:schemas-microsoft-com:xml-analysis:Execute\"");

      SOAPPart soapPart = message.getSOAPPart();
      SOAPEnvelope envelope = soapPart.getEnvelope();
      SOAPBody body = envelope.getBody();
      Name nEx = envelope.createName("Execute", "", XMLA_URI);

      SOAPElement eEx = body.addChildElement(nEx);

      // add the parameters

      // COMMAND parameter
      // <Command>
      // <Statement>queryStr</Statement>
      // </Command>
      Name nCom = envelope.createName("Command", "", XMLA_URI);
      SOAPElement eCommand = eEx.addChildElement(nCom);
      Name nSta = envelope.createName("Statement", "", XMLA_URI);
      SOAPElement eStatement = eCommand.addChildElement(nSta);
      eStatement.addTextNode(queryStr);

      // <Properties>
      // <PropertyList>
      // <DataSourceInfo>dataSource</DataSourceInfo>
      // <Catalog>catalog</Catalog>
      // <Format>Multidimensional</Format>
      // <AxisFormat>TupleFormat</AxisFormat>
      // </PropertyList>
      // </Properties>
      Map paraList = new HashMap();
      String datasource =
          (String) getParameterValue(JRXmlaQueryExecuterFactory.PARAMETER_XMLA_DATASOURCE);
      paraList.put("DataSourceInfo", datasource);
      String catalog =
          (String) getParameterValue(JRXmlaQueryExecuterFactory.PARAMETER_XMLA_CATALOG);
      paraList.put("Catalog", catalog);
      paraList.put("Format", "Multidimensional");
      paraList.put("AxisFormat", "TupleFormat");
      addParameterList(envelope, eEx, "Properties", "PropertyList", paraList);
      message.saveChanges();

      if (log.isDebugEnabled()) {
        log.debug("XML/A query message: " + message.toString());
      }

      return message;
    } catch (SOAPException e) {
      throw new JRRuntimeException(e);
    }
  }
  @Override
  public final SOAPMessage call(final SOAPMessage request, final Object endpoint)
      throws SOAPException {

    SOAPMessage message = null;
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
      final MimeHeaders headers = request.getMimeHeaders();
      final String[] contentType = headers.getHeader("Content-Type");
      final String[] soapAction = headers.getHeader("SOAPAction");

      // build the Content-Type HTTP header parameter if not defined
      if (null == contentType) {
        final StringBuilder header = new StringBuilder();

        if (null == soapAction) {
          header.append("application/soap+xml; charset=UTF-8;");
        } else {
          header.append("text/xml; charset=UTF-8;");
        }

        // not defined as a MIME header but we need it as an HTTP header parameter
        this.conn.addRequestProperty("Content-Type", header.toString());
      } else {
        if (contentType.length > 1) {
          throw new IllegalArgumentException("Content-Type defined more than once.");
        }

        // user specified as a MIME header so add it as an HTTP header parameter
        this.conn.addRequestProperty("Content-Type", contentType[0]);
      }

      // specify SOAPAction as an HTTP header parameter
      if (null != soapAction) {
        if (soapAction.length > 1) {
          throw new IllegalArgumentException("SOAPAction defined more than once.");
        }
        this.conn.addRequestProperty("SOAPAction", soapAction[0]);
      }

      request.writeTo(bos);

      this.conn.connect(new URL(endpoint.toString()), bos);

      final MessageFactory factory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);

      try {
        message = factory.createMessage(null, this.conn.getInputStream());
      } catch (IOException e) {
        message = factory.createMessage(null, this.conn.getErrorStream());
      }

    } catch (MalformedURLException e) {
      throw new SOAPException(e);
    } catch (IOException e) {
      throw new SOAPException(e);
    } catch (GSSException e) {
      throw new SOAPException(e);
    } catch (PrivilegedActionException e) {
      throw new SOAPException(e);
    } finally {
      try {
        bos.close();
      } catch (IOException ioe) {
        assert true;
      }
      this.close();
    }

    return message;
  }
Exemple #13
0
  /**
   * Do the work of construction.
   *
   * @param initialContents may be String, byte[], InputStream, SOAPEnvelope, or AxisFault
   * @param bodyInStream is true if initialContents is an InputStream containing just the SOAP body
   *     (no SOAP-ENV)
   * @param contentType this if the contentType has been already determined (as in the case of
   *     servlets)
   * @param contentLocation the location of the content
   * @param mimeHeaders mime headers for attachments
   */
  private void setup(
      Object initialContents,
      boolean bodyInStream,
      String contentType,
      String contentLocation,
      javax.xml.soap.MimeHeaders mimeHeaders) {

    if (contentType == null && mimeHeaders != null) {
      String contentTypes[] = mimeHeaders.getHeader("Content-Type");
      contentType = (contentTypes != null) ? contentTypes[0] : null;
    }
    if (contentLocation == null && mimeHeaders != null) {
      String contentLocations[] = mimeHeaders.getHeader("Content-Location");
      contentLocation = (contentLocations != null) ? contentLocations[0] : null;
    }
    if (contentType != null) {
      int delimiterIndex = contentType.lastIndexOf("charset");
      if (delimiterIndex > 0) {
        String charsetPart = contentType.substring(delimiterIndex);
        int delimiterIndex2 = charsetPart.indexOf(';');
        if (delimiterIndex2 != -1) {
          charsetPart = charsetPart.substring(0, delimiterIndex2);
        }
        int charsetIndex = charsetPart.indexOf('=');
        String charset = charsetPart.substring(charsetIndex + 1).trim();
        if ((charset.startsWith("\"") || charset.startsWith("\'"))) {
          charset = charset.substring(1, charset.length());
        }
        if ((charset.endsWith("\"") || charset.endsWith("\'"))) {
          charset = charset.substring(0, charset.length() - 1);
        }
        try {
          setProperty(SOAPMessage.CHARACTER_SET_ENCODING, charset);
        } catch (SOAPException e) {
        }
      }
    }
    // Try to construct an AttachmentsImpl object for attachment
    // functionality.
    // If there is no org.apache.axis.attachments.AttachmentsImpl class,
    // it must mean activation.jar is not present and attachments are not
    // supported.
    if (isAttachmentSupportEnabled(getMessageContext())) {
      // Construct one, and cast to Attachments.
      // There must be exactly one constructor of AttachmentsImpl, which
      // must take an org.apache.axis.Message!
      Constructor attachImplConstr = attachImpl.getConstructors()[0];
      try {
        mAttachments =
            (Attachments)
                attachImplConstr.newInstance(
                    new Object[] {initialContents, contentType, contentLocation});

        // If it can't support it, it wont have a root part.
        mSOAPPart = (SOAPPart) mAttachments.getRootPart();
      } catch (InvocationTargetException ex) {
        log.fatal(Messages.getMessage("invocationTargetException00"), ex);
        throw new RuntimeException(ex.getMessage());
      } catch (InstantiationException ex) {
        log.fatal(Messages.getMessage("instantiationException00"), ex);
        throw new RuntimeException(ex.getMessage());
      } catch (IllegalAccessException ex) {
        log.fatal(Messages.getMessage("illegalAccessException00"), ex);
        throw new RuntimeException(ex.getMessage());
      }
    } else if (contentType != null && contentType.startsWith("multipart")) {
      throw new RuntimeException(Messages.getMessage("noAttachments"));
    }

    // text/xml
    if (null == mSOAPPart) {
      mSOAPPart = new SOAPPart(this, initialContents, bodyInStream);
    } else mSOAPPart.setMessage(this);

    // The stream was not determined by a more complex type so default to
    if (mAttachments != null) mAttachments.setRootPart(mSOAPPart);

    headers = (mimeHeaders == null) ? new MimeHeaders() : new MimeHeaders(mimeHeaders);
  }
  SOAPMessage doGet(URL endPoint) throws SOAPException {
    boolean isFailure = false;

    URL url = null;
    HttpURLConnection httpConnection = null;

    int responseCode = 0;
    try {
      /// Is https GET allowed??
      if (endPoint.getProtocol().equals("https")) initHttps();
      // Process the URL
      JaxmURI uri = new JaxmURI(endPoint.toString());
      String userInfo = uri.getUserinfo();

      url = endPoint;

      if (dL > 0) d("uri: " + userInfo + " " + url + " " + uri);

      // TBD
      //    Will deal with https later.
      if (!url.getProtocol().equalsIgnoreCase("http")
          && !url.getProtocol().equalsIgnoreCase("https")) {
        log.severe("SAAJ0052.p2p.protocol.mustbe.http.or.https");
        throw new IllegalArgumentException(
            "Protocol " + url.getProtocol() + " not supported in URL " + url);
      }
      httpConnection = (HttpURLConnection) createConnection(url);

      httpConnection.setRequestMethod("GET");

      httpConnection.setDoOutput(true);
      httpConnection.setDoInput(true);
      httpConnection.setUseCaches(false);
      httpConnection.setFollowRedirects(true);

      httpConnection.connect();

      try {

        responseCode = httpConnection.getResponseCode();

        // let HTTP_INTERNAL_ERROR (500) through because it is used for SOAP faults
        if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
          isFailure = true;
        } else if ((responseCode / 100) != 2) {
          log.log(
              Level.SEVERE,
              "SAAJ0008.p2p.bad.response",
              new String[] {httpConnection.getResponseMessage()});
          throw new SOAPExceptionImpl(
              "Bad response: (" + responseCode + httpConnection.getResponseMessage());
        }
      } catch (IOException e) {
        // on JDK1.3.1_01, we end up here, but then getResponseCode() succeeds!
        responseCode = httpConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
          isFailure = true;
        } else {
          throw e;
        }
      }

    } catch (SOAPException ex) {
      throw ex;
    } catch (Exception ex) {
      log.severe("SAAJ0012.p2p.get.failed");
      throw new SOAPExceptionImpl("Get failed", ex);
    }

    SOAPMessage response = null;
    if (responseCode == HttpURLConnection.HTTP_OK || isFailure) {
      try {
        MimeHeaders headers = new MimeHeaders();

        String key, value;

        // Header field 0 is the status line so we skip it.

        int i = 1;

        while (true) {
          key = httpConnection.getHeaderFieldKey(i);
          value = httpConnection.getHeaderField(i);

          if (key == null && value == null) break;

          if (key != null) {
            StringTokenizer values = new StringTokenizer(value, ",");
            while (values.hasMoreTokens()) headers.addHeader(key, values.nextToken().trim());
          }
          i++;
        }

        InputStream httpIn =
            (isFailure ? httpConnection.getErrorStream() : httpConnection.getInputStream());
        // If no reply message is returned,
        // content-Length header field value is expected to be zero.
        // java SE 6 documentation says :
        // available() : an estimate of the number of bytes that can be read
        // (or skipped over) from this input stream without blocking
        // or 0 when it reaches the end of the input stream.
        if ((httpIn == null)
            || (httpConnection.getContentLength() == 0)
            || (httpIn.available() == 0)) {
          response = null;
          log.warning("SAAJ0014.p2p.content.zero");
        } else {
          response = messageFactory.createMessage(headers, httpIn);
        }

        httpIn.close();
        httpConnection.disconnect();

      } catch (SOAPException ex) {
        throw ex;
      } catch (Exception ex) {
        log.log(Level.SEVERE, "SAAJ0010.p2p.cannot.read.resp", ex);
        throw new SOAPExceptionImpl("Unable to read response: " + ex.getMessage());
      }
    }
    return response;
  }
  SOAPMessage post(SOAPMessage message, URL endPoint) throws SOAPException {
    boolean isFailure = false;

    URL url = null;
    HttpURLConnection httpConnection = null;

    int responseCode = 0;
    try {
      if (endPoint.getProtocol().equals("https"))
        // if(!setHttps)
        initHttps();
      // Process the URL
      JaxmURI uri = new JaxmURI(endPoint.toString());
      String userInfo = uri.getUserinfo();

      url = endPoint;

      if (dL > 0) d("uri: " + userInfo + " " + url + " " + uri);

      // TBD
      //    Will deal with https later.
      if (!url.getProtocol().equalsIgnoreCase("http")
          && !url.getProtocol().equalsIgnoreCase("https")) {
        log.severe("SAAJ0052.p2p.protocol.mustbe.http.or.https");
        throw new IllegalArgumentException(
            "Protocol " + url.getProtocol() + " not supported in URL " + url);
      }
      httpConnection = (HttpURLConnection) createConnection(url);

      httpConnection.setRequestMethod("POST");

      httpConnection.setDoOutput(true);
      httpConnection.setDoInput(true);
      httpConnection.setUseCaches(false);
      httpConnection.setInstanceFollowRedirects(true);

      if (message.saveRequired()) message.saveChanges();

      MimeHeaders headers = message.getMimeHeaders();

      Iterator it = headers.getAllHeaders();
      boolean hasAuth = false; // true if we find explicit Auth header
      while (it.hasNext()) {
        MimeHeader header = (MimeHeader) it.next();

        String[] values = headers.getHeader(header.getName());
        if (values.length == 1)
          httpConnection.setRequestProperty(header.getName(), header.getValue());
        else {
          StringBuffer concat = new StringBuffer();
          int i = 0;
          while (i < values.length) {
            if (i != 0) concat.append(',');
            concat.append(values[i]);
            i++;
          }

          httpConnection.setRequestProperty(header.getName(), concat.toString());
        }

        if ("Authorization".equals(header.getName())) {
          hasAuth = true;
          log.fine("SAAJ0091.p2p.https.auth.in.POST.true");
        }
      }

      if (!hasAuth && userInfo != null) {
        initAuthUserInfo(httpConnection, userInfo);
      }

      OutputStream out = httpConnection.getOutputStream();
      message.writeTo(out);

      out.flush();
      out.close();

      httpConnection.connect();

      try {

        responseCode = httpConnection.getResponseCode();

        // let HTTP_INTERNAL_ERROR (500) through because it is used for SOAP faults
        if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
          isFailure = true;
        }
        // else if (responseCode != HttpURLConnection.HTTP_OK)
        // else if (!(responseCode >= HttpURLConnection.HTTP_OK && responseCode < 207))
        else if ((responseCode / 100) != 2) {
          log.log(
              Level.SEVERE,
              "SAAJ0008.p2p.bad.response",
              new String[] {httpConnection.getResponseMessage()});
          throw new SOAPExceptionImpl(
              "Bad response: (" + responseCode + httpConnection.getResponseMessage());
        }
      } catch (IOException e) {
        // on JDK1.3.1_01, we end up here, but then getResponseCode() succeeds!
        responseCode = httpConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
          isFailure = true;
        } else {
          throw e;
        }
      }

    } catch (SOAPException ex) {
      throw ex;
    } catch (Exception ex) {
      log.severe("SAAJ0009.p2p.msg.send.failed");
      throw new SOAPExceptionImpl("Message send failed", ex);
    }

    SOAPMessage response = null;
    if (responseCode == HttpURLConnection.HTTP_OK || isFailure) {
      try {
        MimeHeaders headers = new MimeHeaders();

        String key, value;

        // Header field 0 is the status line so we skip it.

        int i = 1;

        while (true) {
          key = httpConnection.getHeaderFieldKey(i);
          value = httpConnection.getHeaderField(i);

          if (key == null && value == null) break;

          if (key != null) {
            StringTokenizer values = new StringTokenizer(value, ",");
            while (values.hasMoreTokens()) headers.addHeader(key, values.nextToken().trim());
          }
          i++;
        }

        InputStream httpIn =
            (isFailure ? httpConnection.getErrorStream() : httpConnection.getInputStream());

        byte[] bytes = readFully(httpIn);

        int length =
            httpConnection.getContentLength() == -1
                ? bytes.length
                : httpConnection.getContentLength();

        // If no reply message is returned,
        // content-Length header field value is expected to be zero.
        if (length == 0) {
          response = null;
          log.warning("SAAJ0014.p2p.content.zero");
        } else {
          ByteInputStream in = new ByteInputStream(bytes, length);
          response = messageFactory.createMessage(headers, in);
        }

        httpIn.close();
        httpConnection.disconnect();

      } catch (SOAPException ex) {
        throw ex;
      } catch (Exception ex) {
        log.log(Level.SEVERE, "SAAJ0010.p2p.cannot.read.resp", ex);
        throw new SOAPExceptionImpl("Unable to read response: " + ex.getMessage());
      }
    }
    return response;
  }
 static String getHeader(MimeHeaders headers, String name) {
   String[] values = headers.getHeader(name);
   return (values != null && values.length > 0) ? values[0] : null;
 }