Exemple #1
0
 /** Sends a new message. */
 public void send(String recipient, String subject, String content_type, String content) {
   NameAddress to_url = new NameAddress(recipient);
   NameAddress from_url = new NameAddress(user_profile.from_url);
   MessageFactory msgf = new MessageFactory();
   Message req =
       msgf.createMessageRequest(sip_provider, to_url, from_url, subject, content_type, content);
   TransactionClient t = new TransactionClient(sip_provider, req, this);
   t.request();
 }
  public HttpSOAPConnection() throws SOAPException {

    try {
      messageFactory = MessageFactory.newInstance(SOAPConstants.DYNAMIC_SOAP_PROTOCOL);
    } catch (NoSuchMethodError ex) {
      // fallback to default SOAP 1.1 in this case for backward compatibility
      messageFactory = MessageFactory.newInstance();
    } catch (Exception ex) {
      log.log(Level.SEVERE, "SAAJ0001.p2p.cannot.create.msg.factory", ex);
      throw new SOAPExceptionImpl("Unable to create message factory", ex);
    }
  }
  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;
 }
 /**
  * Creates a new <tt>Request</tt> instance which is to be sent by this
  * <tt>StunCandidateHarvest</tt> in order to retry a specific <tt>Request</tt>. For example, the
  * long-term credential mechanism dictates that a <tt>Request</tt> is first sent by the client
  * without any credential-related attributes, then it gets challenged by the server and the client
  * retries the original <tt>Request</tt> with the appropriate credential-related attributes in
  * response.
  *
  * @param request the <tt>Request</tt> which is to be retried by this
  *     <tt>StunCandidateHarvest</tt>
  * @return the new <tt>Request</tt> instance which is to be sent by this
  *     <tt>StunCandidateHarvest</tt> in order to retry the specified <tt>request</tt>
  */
 protected Request createRequestToRetry(Request request) {
   switch (request.getMessageType()) {
     case Message.BINDING_REQUEST:
       return MessageFactory.createBindingRequest();
     default:
       throw new IllegalArgumentException("request.messageType");
   }
 }
Exemple #6
0
 /** When a new Message is received by the SipInterface. */
 public void onReceivedMessage(SipInterface sip, Message msg) { // printLog("Message received:
   // "+msg.getFirstLine().substring(0,msg.toString().indexOf('\r')));
   if (msg.isRequest()) {
     (new TransactionServer(sip_provider, msg, null))
         .respondWith(MessageFactory.createResponse(msg, 200, SipResponses.reasonOf(200), null));
     NameAddress sender = msg.getFromHeader().getNameAddress();
     NameAddress recipient = msg.getToHeader().getNameAddress();
     String subject = null;
     if (msg.hasSubjectHeader()) subject = msg.getSubjectHeader().getSubject();
     String content_type = msg.getContentTypeHeader().getContentType();
     String content = msg.getBody();
     if (listener != null)
       listener.onMaReceivedMessage(this, sender, recipient, subject, content_type, content);
   }
 }
  @Before
  public void setUp() throws Exception {
    persistenceService = PersistenceServiceProvider.getPersistenceService();
    trackingService = ContextTrackingProvider.getTrackingService();

    HumanTaskServerService.getInstance().initTaskServer();

    MessageServerSingleton.getInstance().start();

    consumer = MessageFactory.createMessageConsumer("IncomingCall");

    this.coreServicesMap = new HashMap();

    createRemoteNode();

    client = HumanTaskServerService.getInstance().initTaskClient();
  }
Exemple #8
0
  public void packetReceived(byte[] packet) {
    // XXX: hack: with the new packetsource format, packet does not
    // contain a crc field, so numElements_data() will be wrong. But we
    // access the data area via dataSet/dataGet, so we're ok.

    // this is where the source comes in to create the correct packet

    final TOSMsg msg = messageFactory.createTOSMsg(packet);

    if (DEBUG) Dump.dump("Received message", packet);

    if (drop_bad_crc && msg.get_crc() != 0x01) {
      // Drop message
      if (DISPLAY_ERROR_MSGS) Dump.dump("Dropping packet with bad CRC", packet);
      return;
    }

    if (groupId == MoteIF.ANY_GROUP_ID || msg.get_group() == groupId) {
      Integer type = new Integer(msg.get_type());
      Vector vec = (Vector) templateTbl.get(type);
      if (vec == null) {
        if (DEBUG)
          Dump.dump(
              "Received packet with type " + msg.get_type() + ", but no listeners registered",
              packet);
        return;
      }
      int length = msg.get_length();

      Enumeration en = vec.elements();
      while (en.hasMoreElements()) {
        msgTemplate temp = (msgTemplate) en.nextElement();

        Message received;

        // Erk - end up cloning the message multiple times in case
        // different templates used for different listeners
        try {
          received = temp.template.clone(length);
          received.dataSet(msg.dataGet(), msg.offset_data(0), 0, length);
        } catch (ArrayIndexOutOfBoundsException e) {
          /*
           * Note: this will not catch messages whose length is
           * incorrect, but less than DATA_LENGTH (see AM.h) + 2
           */
          error(temp, "invalid length message received (too long)");
          continue;
        } catch (Exception e) {
          error(temp, "couldn't clone message!");
          continue;
        }

        /*
         * Messages that are longer than the template might have a
         * variable-sized array at their end
         */
        if (temp.template.dataGet().length > length) {
          error(temp, "invalid length message received (too short)");
          continue;
        }
        temp.listener.messageReceived(msg.get_addr(), received);
      }

    } else {
      if (DISPLAY_ERROR_MSGS) Dump.dump("Dropping packet with bad group ID", packet);
    }
  }
  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());
    }
  }
  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;
  }
 /**
  * Creates a new <tt>Request</tt> which is to be sent to {@link StunCandidateHarvester#stunServer}
  * in order to start resolving {@link #hostCandidate}.
  *
  * @return a new <tt>Request</tt> which is to be sent to {@link StunCandidateHarvester#stunServer}
  *     in order to start resolving {@link #hostCandidate}
  */
 protected Request createRequestToStartResolvingCandidate() {
   return MessageFactory.createBindingRequest();
 }
  @Test
  public void genericEmergencyProcedureTest()
      throws HornetQException, InterruptedException, IOException, ClassNotFoundException {

    asynchProcedureStartWorker =
        new MessageConsumerWorker(
            "asyncProcedureStartCoreServer",
            new MessageConsumerWorkerHandler<AsyncProcedureStartMessage>() {

              @Override
              public void handleMessage(AsyncProcedureStartMessage message) {
                System.out.println(
                    ">>>>>>>>>>>Creating a new Procedure = " + message.getProcedureName());
                try {
                  ProceduresMGMTService.getInstance()
                      .newRequestedProcedure(
                          message.getEmergencyId(),
                          message.getProcedureName(),
                          message.getParameters());
                } catch (IOException ex) {
                  Logger.getLogger(GenericEmergencyProcedureTest.class.getName())
                      .log(Level.SEVERE, null, ex);
                }
              }
            });

    asynchProcedureStartWorker.start();

    MessageProducer producer = MessageFactory.createMessageProducer();
    Call initialCall = new Call(1, 2, new Date());

    producer.sendMessage(initialCall);
    producer.stop();

    Call call = (Call) consumer.receiveMessage();
    assertNotNull(call);

    GenericEmergencyProcedureImpl.getInstance().newPhoneCall(call);

    Thread.sleep(5000);

    doOperatorTask();

    // QUERY TO SEE THAT WE HAVE AN EMERGENCY ATTACHED TO THE CALL

    Thread.sleep(2000);

    doControlTask();

    Thread.sleep(6000);
    // I should have one task here, that has been created by the specific procedure started
    doGarageTask();

    Thread.sleep(3000);
    // I can asume that all the procedures are ended, we need to delegate this to the external
    // component
    AllProceduresEndedEvent allProceduresEndedEvent =
        new AllProceduresEndedEvent(null, new ArrayList<String>());
    GenericEmergencyProcedureImpl.getInstance()
        .allProceduresEnededNotification(allProceduresEndedEvent);
    // We should see the report in the console
    Thread.sleep(10000);
  }