Пример #1
0
  public SecurityToken logon(
      String anEndpointReference, String aUserName, String aPassword, String anApplicationID)
      throws LogonManagerException, SOAPException, IOException {
    SecurityToken result;
    SOAPMessage message;
    SOAPConnection conn = null;

    try {
      result = null;
      String request =
          REQUEST_FORMAT.format(
              ((Object) (new Object[] {fURL, aUserName, aPassword, anEndpointReference})));
      message =
          MessageFactory.newInstance()
              .createMessage(new MimeHeaders(), new ByteArrayInputStream(request.getBytes()));
      conn = SOAPConnectionFactory.newInstance().createConnection();
      SOAPMessage response = conn.call(message, fURL);
      SOAPBody body = response.getSOAPBody();
      if (body.hasFault()) throw new LogonManagerException(body.getFault());
      result = new SecurityToken();
      result.setSOAPBody(body);
      for (Iterator it = body.getChildElements(); it.hasNext(); fill(result, (Node) it.next())) ;
      return result;
    } finally {
      if (conn != null) conn.close();
    }
  }
 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;
 }
Пример #3
0
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {

    String retval = "<html> <H4>";

    try {
      // Create a message factory.
      MessageFactory mf = MessageFactory.newInstance();

      // Create a message from the message factory.
      SOAPMessage msg = mf.createMessage();

      // Message creation takes care of creating the SOAPPart - a
      // required part of the message as per the SOAP 1.1
      // specification.
      SOAPPart sp = msg.getSOAPPart();

      // Retrieve the envelope from the soap part to start building
      // the soap message.
      SOAPEnvelope envelope = sp.getEnvelope();

      // Create a soap header from the envelope.
      SOAPHeader hdr = envelope.getHeader();

      // Create a soap body from the envelope.
      SOAPBody bdy = envelope.getBody();

      // Add a soap body element to the soap body
      SOAPBodyElement gltp =
          bdy.addBodyElement(
              envelope.createName("GetLastTradePrice", "ztrade", "http://wombat.ztrade.com"));

      gltp.addChildElement(envelope.createName("symbol", "ztrade", "http://wombat.ztrade.com"))
          .addTextNode("SUNW");

      StringBuffer urlSB = new StringBuffer();
      urlSB.append(req.getScheme()).append("://").append(req.getServerName());
      urlSB.append(":").append(req.getServerPort()).append(req.getContextPath());
      String reqBase = urlSB.toString();

      if (data == null) {
        data = reqBase + "/index.html";
      }

      // Want to set an attachment from the following url.
      // Get context
      URL url = new URL(data);

      AttachmentPart ap = msg.createAttachmentPart(new DataHandler(url));

      ap.setContentType("text/html");

      // Add the attachment part to the message.
      msg.addAttachmentPart(ap);

      // Create an endpoint for the recipient of the message.
      if (to == null) {
        to = reqBase + "/receiver";
      }

      URL urlEndpoint = new URL(to);

      System.err.println("Sending message to URL: " + urlEndpoint);
      System.err.println("Sent message is logged in \"sent.msg\"");

      retval += " Sent message (check \"sent.msg\") and ";

      FileOutputStream sentFile = new FileOutputStream("sent.msg");
      msg.writeTo(sentFile);
      sentFile.close();

      // Send the message to the provider using the connection.
      SOAPMessage reply = con.call(msg, urlEndpoint);

      if (reply != null) {
        FileOutputStream replyFile = new FileOutputStream("reply.msg");
        reply.writeTo(replyFile);
        replyFile.close();
        System.err.println("Reply logged in \"reply.msg\"");
        retval += " received reply (check \"reply.msg\").</H4> </html>";

      } else {
        System.err.println("No reply");
        retval += " no reply was received. </H4> </html>";
      }

    } catch (Throwable e) {
      e.printStackTrace();
      logger.severe("Error in constructing or sending message " + e.getMessage());
      retval += " There was an error " + "in constructing or sending message. </H4> </html>";
    }

    try {
      OutputStream os = resp.getOutputStream();
      os.write(retval.getBytes());
      os.flush();
      os.close();
    } catch (IOException e) {
      e.printStackTrace();
      logger.severe("Error in outputting servlet response " + e.getMessage());
    }
  }
Пример #4
0
  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;
  }