Esempio n. 1
0
 /**
  * Inherited from TransactionClientListener. When an TransactionClientListener goes into the
  * "Terminated" state, receiving a 2xx response
  *
  * <p>If called for a INVITE transaction, it updates the dialog information, moves to D_CALL
  * state, add a listener to the SipProvider, creates a new AckTransactionClient(ack,this), and
  * fires <i>onSuccessResponse(this,code,body,msg)</i>.
  *
  * <p>If called for a BYE transaction, it moves to D_CLOSE state, removes the listener from
  * SipProvider, and fires <i>onClose(this,msg)</i>.
  */
 public void onTransSuccessResponse(TransactionClient tc, Message msg) {
   printLog("inside onTransSuccessResponse(tc,msg)", LogLevel.LOW);
   if (tc.getTransactionMethod().equals(SipMethods.INVITE)) {
     if (!verifyStatus(statusIs(D_INVITING) || statusIs(D_ReINVITING))) return;
     StatusLine statusline = msg.getStatusLine();
     int code = statusline.getCode();
     if (!verifyThat(
         code >= 200 && code < 300 && msg.getTransactionMethod().equals(SipMethods.INVITE),
         "2xx for invite was expected")) return;
     boolean re_inviting = statusIs(D_ReINVITING);
     changeStatus(D_CALL);
     update(Dialog.UAC, msg);
     if (invite_offer) { // invite_req=MessageFactory.createRequest(SipMethods.ACK,dialog_state,sdp.toString());
       // ack=MessageFactory.createRequest(this,SipMethods.ACK,null);
       ack_req = MessageFactory.create2xxAckRequest(this, null);
       AckTransactionClient ack_tc = new AckTransactionClient(sip_provider, ack_req, null);
       ack_tc.request();
     }
     if (!re_inviting) {
       listener.onDlgInviteSuccessResponse(this, code, statusline.getReason(), msg.getBody(), msg);
       listener.onDlgCall(this);
     } else
       listener.onDlgReInviteSuccessResponse(
           this, code, statusline.getReason(), msg.getBody(), msg);
   } else if (tc.getTransactionMethod().equals(SipMethods.BYE)) {
     if (!verifyStatus(statusIs(D_BYEING))) return;
     StatusLine statusline = msg.getStatusLine();
     int code = statusline.getCode();
     verifyThat(code >= 200 && code < 300, "2xx for bye was expected");
     changeStatus(D_CLOSE);
     listener.onDlgByeSuccessResponse(this, code, statusline.getReason(), msg);
     listener.onDlgClose(this);
   }
 }
Esempio n. 2
0
 private void register() {
   if (session != null && session.isConnected()) {
     onlineUsers.clear();
     // get the current list
     Message msg = session.sendMessage("", "list", "");
     System.out.println("LIST: " + msg.getBody());
     StringTokenizer st = new StringTokenizer(msg.getBody(), "\n");
     while (st.hasMoreTokens()) {
       onlineUsers.addElement(new HostItem(st.nextToken()));
     }
     session.postMessage("", "register", "");
   }
 }
Esempio n. 3
0
 public void processPacket(Packet p) {
   org.jivesoftware.smack.packet.Message message = (org.jivesoftware.smack.packet.Message) p;
   Message msg = new Message(message);
   // TODO add que les message pas de type errors
   ChatMUCAdapter.this.addMessage(msg);
   final int n = mRemoteListeners.beginBroadcast();
   for (int i = 0; i < n; i++) {
     IMessageListener listener = mRemoteListeners.getBroadcastItem(i);
     try {
       if (listener != null) {
         // HL detection
         // If the pseudo
         String bodylow = msg.getBody().toLowerCase();
         if (bodylow.contains(mNick.toLowerCase())) {
           msg.setHL(true);
         }
         // If in the hl list
         String hls =
             PreferenceManager.getDefaultSharedPreferences(mService)
                 .getString("settings_key_hls", "");
         if (!hls.equalsIgnoreCase("")) {
           for (String hl : hls.split(",")) {
             if (bodylow.contains(hl.toLowerCase())) {
               msg.setHL(true);
             }
           }
         }
         listener.processMUCMessage(ChatMUCAdapter.this, msg);
       }
     } catch (RemoteException e) {
       Log.w(TAG, "Error while diffusing message to listener", e);
     }
   }
   mRemoteListeners.finishBroadcast();
 }
  public void actionPerformed(ObjectOutputStream oos, Message msg) throws EventHandleException {
    try {
      /* get the handler of the ServerPeer */
      ServerPeer serverpeer = (ServerPeer) gui.peer();

      /* get the message body */
      SPLeaveReplacementBody body = (SPLeaveReplacementBody) msg.getBody();

      TreeNode treeNode = body.getTreeNode();
      treeNode.setContent(body.getContent());
      SPGeneralAction.saveData(body.getContent().getData());
      treeNode.setStatus(TreeNode.ACTIVE);
      treeNode.setRole(TreeNode.MASTER);
      treeNode.addCoOwnerList(body.getPhysicalSender());
      serverpeer.addListItem(treeNode);
      SPGeneralAction.updateRotateRoutingTable(serverpeer, treeNode);

      serverpeer.setActivateStablePosition(
          new ActivateStablePosition(serverpeer, treeNode, ServerPeer.TIME_TO_STABLE_POSITION));

      ((ServerGUI) gui).updatePane(treeNode);
    } catch (Exception e) {
      e.printStackTrace();
      throw new EventHandleException(
          "Replace a super peer's position failure when it leaves network", e);
    }
  }
Esempio n. 5
0
  /**
   * Handles a message received from the remote party.
   *
   * @param msg The Message object that was received.
   */
  private void doMessageReceived(Message msg) {
    assert (SwingUtilities.isEventDispatchThread()) : "not in UI thread";

    if (msg.getType() == Message.Type.ERROR) {
      JOptionPane.showMessageDialog(
          this,
          msg.getError().getMessage(),
          JavolinApp.getAppName() + ": Error",
          JOptionPane.ERROR_MESSAGE);
    } else if (msg.getType() == Message.Type.HEADLINE) {
      // Do nothing
    } else {
      String jid = msg.getFrom();
      if (jid != null) setUserResource(jid);

      Date date = null;
      PacketExtension ext = msg.getExtension("x", "jabber:x:delay");
      if (ext != null && ext instanceof DelayInformation) {
        date = ((DelayInformation) ext).getStamp();
      }

      mLog.message(mRemoteIdFull, mRemoteNick, msg.getBody(), date);
      Audio.playMessage();
    }
  }
Esempio n. 6
0
 /**
  * Inherited from TransactionClientListener. When the TransactionClientListener is in "Proceeding"
  * state and receives a new 1xx response
  *
  * <p>For INVITE transaction it fires <i>onFailureResponse(this,code,reason,body,msg)</i>.
  */
 public void onTransProvisionalResponse(TransactionClient tc, Message msg) {
   printLog("inside onTransProvisionalResponse(tc,mdg)", LogLevel.LOW);
   if (tc.getTransactionMethod().equals(SipMethods.INVITE)) {
     StatusLine statusline = msg.getStatusLine();
     listener.onDlgInviteProvisionalResponse(
         this, statusline.getCode(), statusline.getReason(), msg.getBody(), msg);
   }
 }
 /** Method derived from interface SipListener. */
 public void onReceivedMessage(SipProvider provider, Message msg) {
   if (msg.isRequest() && msg.isInvite()) {
     if (listener != null)
       listener.onNewInviteDialog(
           this,
           new InviteDialog(sip_provider, msg, listener),
           msg.getToHeader().getNameAddress(),
           msg.getFromHeader().getNameAddress(),
           msg.getBody(),
           msg);
   }
 }
Esempio n. 8
0
 public void receiveMsg(Message msg) {
   // System.out.println(msg.getSubject() + " : " + msg.getBody());
   String subject = msg.getSubject();
   if (subject != null) {
     if (subject.equals("online")) {
       onlineUsers.addElement(new HostItem(msg.getBody()));
       displayMessage(msg.getBody() + " : Online", onlineClientAttrSet);
     } else if (subject.equals("offline")) {
       onlineUsers.removeElement(new HostItem(msg.getBody()));
       displayMessage(msg.getBody() + " : Offline", offlineClientAttrSet);
     } else if (subject.equals("eavesdrop enabled")) {
       Object[] values = jListOnlineUsers.getSelectedValues();
       if (values == null) return;
       for (int i = 0; i < values.length; i++) {
         ((HostItem) values[i]).eavesDroppingEnabled = true;
       }
       jListOnlineUsers.updateUI();
     } else if (subject.equals("eavesdrop disabled")) {
       Object[] values = jListOnlineUsers.getSelectedValues();
       if (values == null) return;
       for (int i = 0; i < values.length; i++) {
         ((HostItem) values[i]).eavesDroppingEnabled = false;
       }
       jListOnlineUsers.updateUI();
     } else if (subject.equals("globaleavesdrop enabled")) {
       displayMessage("Global Eavesdropping Enabled", onlineClientAttrSet);
     } else if (subject.equals("globaleavesdrop disabled")) {
       displayMessage("Global Eavesdropping Disabled", offlineClientAttrSet);
     } else {
       String to = msg.getTo();
       String from = msg.getFrom() == null ? "server" : msg.getFrom();
       String body = msg.getBody() != null ? msg.getBody() : "";
       if (jTextFieldUser.getText().equals(to)) { // this message is sent to us
         displayMessage(subject, from, body, incomingMsgAttrSet);
       } else { // this is an eavesdrop message
         displayMessage(subject, to, from, body, eavesdropAttrSet);
       }
     }
   } else {
     subject = "";
     String to = msg.getTo();
     String from = msg.getFrom() == null ? "server" : msg.getFrom();
     String body = msg.getBody() != null ? msg.getBody() : "";
     if (jTextFieldUser.getText().equals(to)) { // this message is sent to us
       displayMessage(subject, from, body, incomingMsgAttrSet);
     } else { // this is an eavesdrop message
       displayMessage(subject, to, from, body, eavesdropAttrSet);
     }
   }
 }
Esempio n. 9
0
    public void messageReceived(Message message) {
      MessageType type = message.getType();

      switch (type) {
        case PARSER_SUMMARY:
          {
            Number body[] = (Number[]) message.getBody();
            int statementCount = (Integer) body[0];
            int syntaxErrors = (Integer) body[1];
            float elapsedTime = (Float) body[2];

            System.out.printf(PARSER_SUMMARY_FORMAT, statementCount, syntaxErrors, elapsedTime);
            break;
          }

        case SYNTAX_ERROR:
          {
            Object body[] = (Object[]) message.getBody();
            int lineNumber = (Integer) body[0];
            int position = (Integer) body[1];
            String tokenText = (String) body[2];
            String errorMessage = (String) body[3];

            int spaceCount = PREFIX_WIDTH + position;
            StringBuilder flagBuffer = new StringBuilder();

            // Spaces up to the error position
            for (int i = 1; i < spaceCount; ++i) flagBuffer.append(' ');

            // A pointer to the error followed by the error message
            flagBuffer.append("^\n*** ").append(errorMessage);

            // Text, if any, of the bad token
            if (tokenText != null) flagBuffer.append(" [at \"").append(tokenText).append("\"]");
            System.out.println(flagBuffer.toString());
            break;
          }
      }
    }
Esempio n. 10
0
  private void handlePacket(Packet packet) {
    if (packet instanceof Message) {
      Message msg = (Message) packet;
      // Check to see if the user left the queue.
      PacketExtension pe = msg.getExtension("depart-queue", "http://jabber.org/protocol/workgroup");
      PacketExtension queueStatus =
          msg.getExtension("queue-status", "http://jabber.org/protocol/workgroup");

      if (pe != null) {
        fireQueueDepartedEvent();
      } else if (queueStatus != null) {
        QueueUpdate queueUpdate = (QueueUpdate) queueStatus;
        if (queueUpdate.getPosition() != -1) {
          fireQueuePositionEvent(queueUpdate.getPosition());
        }
        if (queueUpdate.getRemaingTime() != -1) {
          fireQueueTimeEvent(queueUpdate.getRemaingTime());
        }
      } else {
        // Check if a room invitation was sent and if the sender is the workgroup
        MUCUser mucUser = (MUCUser) msg.getExtension("x", "http://jabber.org/protocol/muc#user");
        MUCUser.Invite invite = mucUser != null ? mucUser.getInvite() : null;
        if (invite != null && workgroupJID.equals(invite.getFrom())) {
          String sessionID = null;
          Map<String, List<String>> metaData = null;

          pe = msg.getExtension(SessionID.ELEMENT_NAME, SessionID.NAMESPACE);
          if (pe != null) {
            sessionID = ((SessionID) pe).getSessionID();
          }

          pe = msg.getExtension(MetaData.ELEMENT_NAME, MetaData.NAMESPACE);
          if (pe != null) {
            metaData = ((MetaData) pe).getMetaData();
          }

          WorkgroupInvitation inv =
              new WorkgroupInvitation(
                  connection.getUser(),
                  msg.getFrom(),
                  workgroupJID,
                  sessionID,
                  msg.getBody(),
                  msg.getFrom(),
                  metaData);

          fireInvitationEvent(inv);
        }
      }
    }
  }
Esempio n. 11
0
 public Message findSentMessageWithBody(String body) {
   synchronized (this.messages) {
     for (int i = this.messages.size() - 1; i >= 0; --i) {
       Message message = this.messages.get(i);
       if ((message.getStatus() == Message.STATUS_UNSEND
               || message.getStatus() == Message.STATUS_SEND)
           && message.getBody() != null
           && message.getBody().equals(body)) {
         return message;
       }
     }
     return null;
   }
 }
Esempio n. 12
0
    /**
     * Called by the source whenever it produces a message.
     *
     * @param message the message.
     */
    public void messageReceived(Message message) {
      MessageType type = message.getType();
      Object body[] = (Object[]) message.getBody();

      switch (type) {
        case SOURCE_LINE:
          {
            int lineNumber = (Integer) body[0];
            String lineText = (String) body[1];

            System.out.println(String.format(SOURCE_LINE_FORMAT, lineNumber, lineText));
            break;
          }
      }
    }
Esempio n. 13
0
 /**
  * Inherited from TransactionServerListener. When the TransactionServer goes into the "Trying"
  * state receiving a request
  *
  * <p>If called for a INVITE transaction, it initializes the dialog information, <br>
  * moves to D_INVITED state, and add a listener to the SipProvider, <br>
  * and fires <i>onInvite(caller,body,msg)</i>.
  */
 public void onTransRequest(TransactionServer ts, Message req) {
   printLog("inside onTransRequest(ts,msg)", LogLevel.LOW);
   if (ts.getTransactionMethod().equals(SipMethods.INVITE)) {
     if (!verifyStatus(statusIs(D_WAITING))) return;
     changeStatus(D_INVITED);
     invite_req = req;
     update(Dialog.UAS, invite_req);
     listener.onDlgInvite(
         this,
         invite_req.getToHeader().getNameAddress(),
         invite_req.getFromHeader().getNameAddress(),
         invite_req.getBody(),
         invite_req);
   }
 }
Esempio n. 14
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);
   }
 }
Esempio n. 15
0
 /**
  * Puts a message in the database Note: the timestamp will be stored as the current time at which
  * this method is called.
  */
 public void storeMessage(Message message) {
   con.updateDB(
       "INSERT INTO "
           + MESSAGES
           + " VALUES ( \""
           + message.getFrom()
           + "\", \""
           + message.getTo()
           + "\", \""
           + message.getBody()
           + "\", "
           + null
           + ", "
           + message.getType()
           + ")");
 }
Esempio n. 16
0
  public Packet doAction(Packet packet) throws PacketRejectedException {
    SessionManager sessionManager = SessionManager.getInstance();
    ClientSession clientSession = sessionManager.getSession(packet.getFrom());
    Packet rejectPacket;
    String pfFrom = JiveGlobals.getProperty("pf.From", "packetfilter");

    if (packet instanceof Message) {
      Message in = (Message) packet.createCopy();
      if (clientSession != null && in.getBody() != null) {

        in.setFrom(new JID(pfFrom));
        String rejectMessage =
            JiveGlobals.getProperty(
                "pf.rejectMessage", "Your message was rejected by the packet filter");
        in.setBody(rejectMessage);
        in.setType(Message.Type.error);
        in.setTo(packet.getFrom());
        String rejectSubject = JiveGlobals.getProperty("pf.rejectSubject", "Rejected");
        in.setSubject(rejectSubject);
        clientSession.process(in);
      }

    } else if (packet instanceof Presence) {
      rejectPacket = new Presence();
      rejectPacket.setTo(packet.getFrom());
      rejectPacket.setError(PacketError.Condition.forbidden);

    } else if (packet instanceof IQ) {
      rejectPacket = new IQ();
      rejectPacket.setTo(packet.getFrom());
      rejectPacket.setError(PacketError.Condition.forbidden);
    }
    if (doLog()) {
      Log.info("Rejecting packet from " + packet.getFrom() + " to " + packet.getTo());
    }
    throw new PacketRejectedException();
  }
Esempio n. 17
0
    /**
     * Called by the back end whenever it produces a message.
     *
     * @param message the message.
     */
    public void messageReceived(Message message) {
      MessageType type = message.getType();

      switch (type) {
        case SOURCE_LINE:
          {
            if (lines) {
              int lineNumber = (Integer) message.getBody();
              System.out.printf(LINE_FORMAT, lineNumber);
            }
            break;
          }

        case ASSIGN:
          {
            if (assign) {
              Object body[] = (Object[]) message.getBody();
              int lineNumber = (Integer) body[0];
              String variableName = (String) body[1];
              Object value = body[2];
              System.out.printf(ASSIGN_FORMAT, lineNumber, variableName, value);
            }
            break;
          }

        case FETCH:
          {
            if (fetch) {
              Object body[] = (Object[]) message.getBody();
              int lineNumber = (Integer) body[0];
              String variableName = (String) body[1];
              Object value = body[2];

              System.out.printf(FETCH_FORMAT, lineNumber, variableName, value);
            }
            break;
          }

        case CALL:
          {
            if (call) {
              Object body[] = (Object[]) message.getBody();
              int lineNumber = (Integer) body[0];
              String routineName = (String) body[1];

              System.out.printf(CALL_FORMAT, lineNumber, routineName);
            }
            break;
          }

        case RETURN:
          {
            if (returnn) {
              Object body[] = (Object[]) message.getBody();
              int lineNumber = (Integer) body[0];
              String routineName = (String) body[1];

              System.out.printf(RETURN_FORMAT, lineNumber, routineName);
            }
            break;
          }

        case RUNTIME_ERROR:
          {
            Object body[] = (Object[]) message.getBody();
            String errorMessage = (String) body[0];
            Integer lineNumber = (Integer) body[1];

            System.out.print("*** RUNTIME ERROR");
            if (lineNumber != null)
              System.out.print(" AT LINE " + String.format("%03d", lineNumber));
            System.out.println(": " + errorMessage);
            break;
          }

        case INTERPRETER_SUMMARY:
          {
            Number body[] = (Number[]) message.getBody();
            int executionCount = (Integer) body[0];
            int runtimeErrors = (Integer) body[1];
            float elapsedTime = (Float) body[2];

            System.out.printf(
                INTERPRETER_SUMMARY_FORMAT, executionCount, runtimeErrors, elapsedTime);
            break;
          }

        case COMPILER_SUMMARY:
          {
            Number body[] = (Number[]) message.getBody();
            int instructionCount = (Integer) body[0];
            float elapsedTime = (Float) body[1];

            System.out.printf(COMPILER_SUMMARY_FORMAT, instructionCount, elapsedTime);
            break;
          }
      }
    }
  public void actionPerformed(ObjectOutputStream oos, Message msg) throws EventHandleException {
    Message result = null;
    Head thead = new Head();

    try {
      /* get the handler of the ServerPeer */
      ServerPeer serverpeer = (ServerPeer) gui.peer();

      /* get the message body */
      SPLeaveFindReplacementNodeBody body = (SPLeaveFindReplacementNodeBody) msg.getBody();

      TreeNode treeNode = serverpeer.getTreeNode(body.getLogicalDestination());
      if (treeNode == null) {
        System.out.println("Tree node is null, do not process the message");
        return;
      }

      RoutingTableInfo leftRoutingTable = treeNode.getLeftRoutingTable();
      RoutingTableInfo rightRoutingTable = treeNode.getRightRoutingTable();
      RoutingItemInfo temptInfo, transferInfo = null;

      int i;

      if (treeNode.getLeftChild() != null) {
        // if it has left child
        body.setPhysicalSender(serverpeer.getPhysicalInfo());
        body.setLogicalSender(treeNode.getLogicalInfo());
        body.setLogicalDestination(treeNode.getLeftChild().getLogicalInfo());

        thead.setMsgType(MsgType.SP_LEAVE_FIND_REPLACEMENT_NODE.getValue());
        result = new Message(thead, body);
        serverpeer.sendMessage(treeNode.getLeftChild().getPhysicalInfo(), result);
      } else if (treeNode.getRightChild() != null) {
        // if it has right child
        body.setPhysicalSender(serverpeer.getPhysicalInfo());
        body.setLogicalSender(treeNode.getLogicalInfo());
        body.setLogicalDestination(treeNode.getRightChild().getLogicalInfo());

        thead.setMsgType(MsgType.SP_LEAVE_FIND_REPLACEMENT_NODE.getValue());
        result = new Message(thead, body);
        serverpeer.sendMessage(treeNode.getRightChild().getPhysicalInfo(), result);
      } else {
        // if it has no child, check routing table
        i = 0;
        while ((i < leftRoutingTable.getTableSize()) && (transferInfo == null)) {
          temptInfo = leftRoutingTable.getRoutingTableNode(i);
          if (temptInfo != null) {
            if ((temptInfo.getLeftChild() != null) || (temptInfo.getRightChild() != null)) {
              transferInfo = temptInfo;
            }
          }
          i++;
        }

        i = 0;
        while ((i < rightRoutingTable.getTableSize()) && (transferInfo == null)) {
          temptInfo = rightRoutingTable.getRoutingTableNode(i);
          if (temptInfo != null) {
            if ((temptInfo.getLeftChild() != null) || (temptInfo.getRightChild() != null)) {
              transferInfo = temptInfo;
            }
          }
          i++;
        }

        if (transferInfo != null) {
          body.setPhysicalSender(serverpeer.getPhysicalInfo());
          body.setLogicalSender(treeNode.getLogicalInfo());
          if (transferInfo.getLeftChild() != null) {
            body.setLogicalDestination(transferInfo.getLeftChild().getLogicalInfo());

            thead.setMsgType(MsgType.SP_LEAVE_FIND_REPLACEMENT_NODE.getValue());
            result = new Message(thead, body);
            serverpeer.sendMessage(transferInfo.getLeftChild().getPhysicalInfo(), result);
          } else {
            body.setLogicalDestination(transferInfo.getRightChild().getLogicalInfo());

            thead.setMsgType(MsgType.SP_LEAVE_FIND_REPLACEMENT_NODE.getValue());
            result = new Message(thead, body);
            serverpeer.sendMessage(transferInfo.getRightChild().getPhysicalInfo(), result);
          }
        } else {
          doLeaveAndReplace(serverpeer, treeNode, body);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw new EventHandleException(
          "Super peer finds a replacement peer failure when it leaves network", e);
    }
  }
Esempio n. 19
0
 /**
  * Inherited from class SipProviderListener. Called when a new message is received (out of any
  * ongoing transaction) for the current InviteDialog. Always checks for out-of-date methods (CSeq
  * header sequence number).
  *
  * <p>If the message is ACK(2xx/INVITE) request, it moves to D_CALL state, and fires
  * <i>onDlgAck(this,body,msg)</i>.
  *
  * <p>If the message is 2xx(INVITE) response, it create a new AckTransactionClient
  *
  * <p>If the message is BYE, it moves to D_BYED state, removes the listener from SipProvider,
  * fires onDlgBye(this,msg) then it responds with 200 OK, moves to D_CLOSE state and fires
  * onDlgClose(this)
  */
 public void onReceivedMessage(SipProvider sip_provider, Message msg) {
   printLog("inside onReceivedMessage(sip_provider,message)", LogLevel.MEDIUM);
   if (msg.isRequest()
       && !(msg.isAck() || msg.isCancel())
       && msg.getCSeqHeader().getSequenceNumber() <= getRemoteCSeq()) {
     printLog("Request message is too late (CSeq too small): Message discarded", LogLevel.HIGH);
     return;
   }
   // invite received
   if (msg.isRequest() && msg.isInvite()) {
     verifyStatus(statusIs(D_INIT) || statusIs(D_CALL));
     // NOTE: if the invite_ts.listen() is used, you should not arrive
     // here with the D_INIT state..
     // however state D_INIT has been included for robustness against
     // further changes.
     if (statusIs(D_INIT)) changeStatus(D_INVITED);
     else changeStatus(D_ReINVITED);
     invite_req = msg;
     invite_ts = new InviteTransactionServer(sip_provider, invite_req, this);
     // ((TransactionServer)transaction).listen();
     update(Dialog.UAS, invite_req);
     if (statusIs(D_INVITED))
       listener.onDlgInvite(
           this,
           invite_req.getToHeader().getNameAddress(),
           invite_req.getFromHeader().getNameAddress(),
           invite_req.getBody(),
           invite_req);
     else listener.onDlgReInvite(this, invite_req.getBody(), invite_req);
   } else
   // ack (of 2xx of INVITE)
   if (msg.isRequest() && msg.isAck()) {
     if (!verifyStatus(statusIs(D_ACCEPTED) || statusIs(D_ReACCEPTED))) return;
     changeStatus(D_CALL);
     // terminates the AckTransactionServer
     ack_ts.terminate();
     listener.onDlgAck(this, msg.getBody(), msg);
     listener.onDlgCall(this);
   } else
   // keep sending ACK (if already sent) for any "200 OK" received
   if (msg.isResponse()) {
     if (!verifyStatus(statusIs(D_CALL))) return;
     int code = msg.getStatusLine().getCode();
     verifyThat(code >= 200 && code < 300, "code 2xx was expected");
     if (ack_req != null) {
       AckTransactionClient ack_tc = new AckTransactionClient(sip_provider, ack_req, null);
       ack_tc.request();
     }
   } else
   // bye received
   if (msg.isRequest() && msg.isBye()) {
     if (!verifyStatus(statusIs(D_CALL) || statusIs(D_BYEING))) return;
     changeStatus(D_BYED);
     bye_ts = new TransactionServer(sip_provider, msg, this);
     // automatically sends a 200 OK
     Message resp = MessageFactory.createResponse(msg, 200, SipResponses.reasonOf(200), null);
     respond(resp);
     listener.onDlgBye(this, msg);
     changeStatus(D_CLOSE);
     listener.onDlgClose(this);
   } else
   // cancel received
   if (msg.isRequest() && msg.isCancel()) {
     if (!verifyStatus(statusIs(D_INVITED) || statusIs(D_ReINVITED))) return;
     // create a CANCEL TransactionServer and send a 200 OK (CANCEL)
     TransactionServer ts = new TransactionServer(sip_provider, msg, null);
     // ts.listen();
     ts.respondWith(MessageFactory.createResponse(msg, 200, SipResponses.reasonOf(200), null));
     // automatically sends a 487 Cancelled
     Message resp =
         MessageFactory.createResponse(invite_req, 487, SipResponses.reasonOf(487), null);
     respond(resp);
     listener.onDlgCancel(this, msg);
   } else
   // any other request received
   if (msg.isRequest()) {
     TransactionServer ts = new TransactionServer(sip_provider, msg, null);
     // ts.listen();
     ts.respondWith(MessageFactory.createResponse(msg, 405, SipResponses.reasonOf(405), null));
   }
 }
Esempio n. 20
0
  public static void main(String[] args) {
    if (args.length > 0) {
      try {
        if (args[0].equals("-stress")) {
          String userName = args[1];
          String server = args[2];
          String targetUser = args[3];
          int rate = Integer.parseInt(args[4]);
          Session session = new Session();
          if (session.connect(server, userName)) {
            long msgCount = 0;
            while (true) {
              for (int i = 0; i < rate; i++) {
                msgCount++;
                session.postMessage(
                    targetUser, ("subject " + String.valueOf(msgCount)), Util.randomString(1000));
              }
              Thread.currentThread().sleep(2000);
            }
          }
        } else if (args[0].equals("-stress2")) {
          String userName = args[1];
          String server = args[2];
          String targetUser = args[3];
          int rate = Integer.parseInt(args[4]);
          Session session = new Session();
          long msgCount = 0;
          while (true) {
            if (session.connect(server, userName)) {
              for (int i = 0; i < rate; i++) {
                msgCount++;
                session.postMessage(
                    targetUser, ("subject " + String.valueOf(msgCount)), Util.randomString(1000));
              }
              session.disconnect();
            }
            Thread.currentThread().sleep(2000);
          }

        } else if (args[0].equals("-stress3")) {
          String userName = args[1];
          String server = args[2];
          String targetUser = args[3];
          int rate = Integer.parseInt(args[4]);
          Session session = new Session();
          long msgCount = 0;
          while (true) {
            if (session.connect(server, userName)) {
              for (int i = 0; i < rate; i++) {
                msgCount++;
                session.postMessage(
                    targetUser, ("subject " + String.valueOf(msgCount)), Util.randomString(1000));
              }
              session.dropConnection();
            }
            Thread.currentThread().sleep(2000);
          }
        } else if (args[0].equals("-stress4")) {
          String userName = args[1];
          String server = args[2];
          String targetUser = args[3];
          int rate = Integer.parseInt(args[4]);
          Session session = new Session();
          long msgCount = 0;
          while (true) {
            if (session.connect(server, userName)) {
              for (int i = 0; i < rate; i++) {
                msgCount++;
                session.postMessage(
                    targetUser, ("subject " + String.valueOf(msgCount)), Util.fixedString(300000));
              }
              session.dropConnection();
            }
            Thread.currentThread().sleep(5000);
          }

        } else if (args[0].equals("-stress5")) {
          String userName = args[1];
          String server = args[2];
          String targetUser = args[3];
          int rate = Integer.parseInt(args[4]);
          Session session = new Session();
          if (session.connect(server, userName)) {
            long msgCount = 0;
            while (true) {
              for (int i = 0; i < rate; i++) {
                msgCount++;
                session.postMessage(
                    targetUser, ("subject " + String.valueOf(msgCount)), Util.randomString(10));
              }
              Thread.currentThread().sleep(2000);
            }
          }
        } else if (args[0].equals("-monitor")) {
          String userName = args[1];
          String server = args[2];
          long interval = Long.parseLong(args[3]);
          Session session = new Session();
          long msgCount = 0;
          if (session.connect(server, userName)) {
            while (true) {
              Message msg = session.sendMessage("", "get send queue stats", "");
              System.out.println("SEND QUEUE STATS");
              System.out.println(msg.getBody());
              Thread.currentThread().sleep(interval);
            }
          }
        } else if (args[0].equals("-responder")) {
          String userName = args[1];
          String server = args[2];
          long interval = Long.parseLong(args[3]);
          final Session session = new Session();
          if (session.connect(server, userName)) {
            session.addListener(
                new AsyncMessageReceiverListener() {
                  public void receiveMsg(Message msg) {
                    session.postMessage(
                        msg.getFrom(), "RE: " + msg.getFrom(), msg.getThread(), msg.getBody());
                  }

                  public void messageReceiverClosed(MessageReceiver mr) {}
                });
            while (true) {
              Thread.currentThread().sleep(interval);
            }
          }
        } else if (args[0].equals("-threaded-sender")) {
          String userName = args[1];
          String server = args[2];
          String targetUser = args[3];
          int rate = Integer.parseInt(args[4]);
          Session session = new Session();
          long msgCount = 0;
          if (session.connect(server, userName)) {
            while (true) {
              for (int i = 0; i < rate; i++) {
                msgCount++;
                Message reply =
                    session.sendMessage(
                        targetUser, ("subject " + String.valueOf(msgCount)), "body", 10000);
                if (reply == null) {
                  System.out.println("reply not received");
                }
              }
              Thread.currentThread().sleep(5000);
            }
          }
        }
      } catch (Exception e) {
        System.out.println(
            "Unable to start stress test.  Format: -stress <user name> <server> <target user> <msg rate>");
      }
    } else {
      Client client = new Client();
      client.setSize(800, 420);
      center(client);
      client.show();
    }
  }
Esempio n. 21
0
 /** Starts a new call with the <i>invite</i> message request */
 public void call(Message invite) {
   dialog = new InviteDialog(sip_provider, this);
   local_sdp = invite.getBody();
   if (local_sdp != null) dialog.invite(invite);
   else dialog.inviteWithoutOffer(invite);
 }
Esempio n. 22
0
  /** {@inheritDoc} */
  @Override
  public void send(Message msg) throws IllegalArgumentException, IOException {
    // Sanity checks
    if (msg.getTo() == null || msg.getSubject() == null || msg.getBody() == null) {
      throw new IllegalArgumentException("Message has no destination or no subject");
    }

    ArrayList<String> cmd = new ArrayList<String>();
    // mailx -b bcc -c cc -s subj to-addr to-addr
    cmd.add(mailer);
    if (msg.getBcc() != null) {
      cmd.add("-b");
      cmd.add(join(msg.getBcc(), ","));
    }
    if (msg.isHtml()) {
      cmd.add("-a");
      cmd.add("Content-type: text/html;");
    }
    if (msg.getCc() != null) {
      cmd.add("-c");
      cmd.add(join(msg.getCc(), ","));
    }
    cmd.add("-s");
    cmd.add(msg.getSubject());

    cmd.addAll(msg.getTo());

    if (msg.getSender() != null) {
      // Sender in the headers:
      cmd.add("-a");
      cmd.add(String.format("From: %s", msg.getSender()));
      // sendmail options are denoted with a double-hyphen
      cmd.add("--");
      // Envelope Sender
      cmd.add("-f");
      cmd.add(msg.getSender());
    }

    Log.i(LOG_TAG, String.format("About to send email with command: %s", cmd));
    String[] strArray = new String[cmd.size()];
    Process mailerProc = run(cmd.toArray(strArray));
    BufferedOutputStream mailerStdin = new BufferedOutputStream(mailerProc.getOutputStream());
    /* There is no such thing as a "character" in the land of the shell; there are only bytes.
     * Here, we convert the body from a Java string (consisting of characters) to a byte array
     * encoding each character with UTF-8.  Each character will be represented as between one
     * and four bytes apiece.
     */
    mailerStdin.write(msg.getBody().getBytes("UTF-8"));
    mailerStdin.flush();
    mailerStdin.close();

    int retValue;
    try {
      retValue = mailerProc.waitFor();
    } catch (InterruptedException e) {
      // ignore, but set retValue to something bogus
      retValue = -12345;
    }
    if (retValue != 0) {
      Log.e(LOG_TAG, String.format("Mailer finished with non-zero return value: %d", retValue));
      BufferedInputStream mailerStdout = new BufferedInputStream(mailerProc.getInputStream());
      StringBuilder stdout = new StringBuilder();
      int theByte;
      while ((theByte = mailerStdout.read()) != -1) {
        stdout.append((char) theByte);
      }
      Log.e(LOG_TAG, "Mailer output was: " + stdout.toString());
    } else {
      Log.v(LOG_TAG, "Mailer returned successfully.");
    }
  }
Esempio n. 23
0
  /**
   * Parses a message packet.
   *
   * @param parser the XML parser, positioned at the start of a message packet.
   * @return a Message packet.
   * @throws Exception if an exception occurs while parsing the packet.
   */
  public static Packet parseMessage(XmlPullParser parser) throws Exception {
    Message message = new Message();
    String id = parser.getAttributeValue("", "id");
    message.setPacketID(id == null ? Packet.ID_NOT_AVAILABLE : id);
    message.setTo(parser.getAttributeValue("", "to"));
    message.setFrom(parser.getAttributeValue("", "from"));
    message.setType(Message.Type.fromString(parser.getAttributeValue("", "type")));
    String language = getLanguageAttribute(parser);

    // determine message's default language
    String defaultLanguage = null;
    if (language != null && !"".equals(language.trim())) {
      message.setLanguage(language);
      defaultLanguage = language;
    } else {
      defaultLanguage = Packet.getDefaultLanguage();
    }

    // Parse sub-elements. We include extra logic to make sure the values
    // are only read once. This is because it's possible for the names to appear
    // in arbitrary sub-elements.
    boolean done = false;
    String thread = null;
    Map<String, Object> properties = null;
    while (!done) {
      int eventType = parser.next();
      if (eventType == XmlPullParser.START_TAG) {
        String elementName = parser.getName();
        String namespace = parser.getNamespace();
        if (elementName.equals("subject")) {
          String xmlLang = getLanguageAttribute(parser);
          if (xmlLang == null) {
            xmlLang = defaultLanguage;
          }

          String subject = parseContent(parser);

          if (message.getSubject(xmlLang) == null) {
            message.addSubject(xmlLang, subject);
          }
        } else if (elementName.equals("body")) {
          String xmlLang = getLanguageAttribute(parser);
          if (xmlLang == null) {
            xmlLang = defaultLanguage;
          }

          String body = parseContent(parser);

          if (message.getBody(xmlLang) == null) {
            message.addBody(xmlLang, body);
          }
        } else if (elementName.equals("thread")) {
          if (thread == null) {
            thread = parser.nextText();
          }
        } else if (elementName.equals("error")) {
          message.setError(parseError(parser));
        } else if (elementName.equals("properties") && namespace.equals(PROPERTIES_NAMESPACE)) {
          properties = parseProperties(parser);
        }
        // Otherwise, it must be a packet extension.
        else {
          message.addExtension(
              PacketParserUtils.parsePacketExtension(elementName, namespace, parser));
        }
      } else if (eventType == XmlPullParser.END_TAG) {
        if (parser.getName().equals("message")) {
          done = true;
        }
      }
    }

    message.setThread(thread);
    // Set packet properties.
    if (properties != null) {
      for (String name : properties.keySet()) {
        message.setProperty(name, properties.get(name));
      }
    }
    return message;
  }