/** Process the invite request. */
  public void processInvite(RequestEvent requestEvent, ServerTransaction serverTransaction) {
    SipProvider sipProvider = (SipProvider) requestEvent.getSource();
    Request request = requestEvent.getRequest();
    try {
      System.out.println("shootme: got an Invite sending Trying");
      // System.out.println("shootme: " + request);
      Response response = messageFactory.createResponse(Response.RINGING, request);
      ServerTransaction st = requestEvent.getServerTransaction();

      if (st == null) {
        st = sipProvider.getNewServerTransaction(request);
      }
      dialog = st.getDialog();

      st.sendResponse(response);

      this.okResponse = messageFactory.createResponse(Response.OK, request);
      Address address =
          addressFactory.createAddress("Shootme <sip:" + myAddress + ":" + myPort + ">");
      ContactHeader contactHeader = headerFactory.createContactHeader(address);
      response.addHeader(contactHeader);
      ToHeader toHeader = (ToHeader) okResponse.getHeader(ToHeader.NAME);
      toHeader.setTag("4321"); // Application is supposed to set.
      okResponse.addHeader(contactHeader);
      this.inviteTid = st;
      // Defer sending the OK to simulate the phone ringing.
      // Answered in 1 second ( this guy is fast at taking calls)
      this.inviteRequest = request;

      new Timer().schedule(new MyTimerTask(this), 1000);
    } catch (Exception ex) {
      ex.printStackTrace();
      System.exit(0);
    }
  }
Exemple #2
0
  /** Process the invite request. */
  public void processInvite(RequestEvent requestEvent, ServerTransaction serverTransaction) {
    SipProvider sipProvider = (SipProvider) requestEvent.getSource();
    Request request = requestEvent.getRequest();
    try {
      System.out.println("shootme: got an Invite sending Trying");
      // System.out.println("shootme: " + request);
      Response response = messageFactory.createResponse(Response.TRYING, request);
      ServerTransaction st = requestEvent.getServerTransaction();

      if (st == null) {
        st = sipProvider.getNewServerTransaction(request);
      }
      dialog = st.getDialog();

      st.sendResponse(response);

      this.okResponse = messageFactory.createResponse(Response.BUSY_HERE, request);

      ToHeader toHeader = (ToHeader) okResponse.getHeader(ToHeader.NAME);
      toHeader.setTag("4321"); // Application is supposed to set.

      this.inviteTid = st;
      // Defer sending the OK to simulate the phone ringing.
      this.inviteRequest = request;

      new Timer().schedule(new MyTimerTask(this), 100);
    } catch (Exception ex) {
      ex.printStackTrace();
      System.exit(0);
    }
  }
  public void processBye(RequestEvent requestEvent, ServerTransaction serverTransaction) {
    try {
      logger.debug("DEBUG: IMByeProcessing, Processing BYE in progress...");

      Request request = requestEvent.getRequest();

      MessageFactory messageFactory = imUA.getMessageFactory();
      InstantMessagingGUI instantMessagingGUI = imUA.getInstantMessagingGUI();
      ListenerInstantMessaging listenerInstantMessaging =
          instantMessagingGUI.getListenerInstantMessaging();
      ChatSessionManager chatSessionManager = listenerInstantMessaging.getChatSessionManager();
      String buddy = IMUtilities.getKey(request, "From");
      if (chatSessionManager.hasAlreadyChatSession(buddy)) {
        chatSessionManager.removeChatSession(buddy);
        // chatSession.setExitedSession(true,"Your contact has exited
        // the session");
      } else {
        logger.debug("DEBUG: IMByeProcessing, processBye(), no active chatSession");
      }

      // Send an OK
      Response response = messageFactory.createResponse(Response.OK, request);
      serverTransaction.sendResponse(response);
      logger.debug("DEBUG: IMByeProcessing, processBye(), OK replied to the BYE");

      logger.debug("DEBUG: IMByeProcessing, Processing BYE completed...");
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Exemple #4
0
  /** Process the invite request. */
  public void processInvite(RequestEvent requestEvent, ServerTransaction serverTransaction) {
    SipProvider sipProvider = (SipProvider) requestEvent.getSource();
    Request request = requestEvent.getRequest();
    try {
      System.out.println("cutme: got an Invite sending Trying");
      // System.out.println("cutme: " + request);
      Response response = messageFactory.createResponse(Response.RINGING, request);
      String toTag = Integer.toString((int) (Math.random() * 10000000));
      ToHeader toHeader = (ToHeader) response.getHeader(ToHeader.NAME);
      toHeader.setTag(toTag); // Application is supposed to set.

      ServerTransaction st = requestEvent.getServerTransaction();

      if (st == null) {
        st = sipProvider.getNewServerTransaction(request);
      }
      inviteTid = st;
      inviteRequest = request;
      dialog = st.getDialog();
      //			inviteRequest = request;
      if (timeToWaitBeforeAnswer > 0) {
        Thread.sleep(timeToWaitBeforeAnswer);
      }

      st.sendResponse(response);
      // If we dont send final response this will receive cancel.
    } catch (Exception ex) {
      ex.printStackTrace();
      System.exit(0);
    }
  }
Exemple #5
0
  public void processCancel(RequestEvent requestEvent, ServerTransaction serverTransactionId) {
    Request request = requestEvent.getRequest();
    try {
      System.out.println("cutme:  got a cancel.");
      if (serverTransactionId == null) {
        System.out.println("cutme:  null tid.");
        return;
      }
      Response responseOK = messageFactory.createResponse(200, request);
      serverTransactionId.sendResponse(responseOK);
      Response response = messageFactory.createResponse(487, inviteRequest);
      inviteTid.sendResponse(response);

      this.canceled = true;

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Exemple #6
0
  public void processCancel(RequestEvent requestEvent, ServerTransaction serverTransactionId) {
    SipProvider sipProvider = (SipProvider) requestEvent.getSource();
    Request request = requestEvent.getRequest();
    try {
      System.out.println("shootme:  got a cancel.");
      if (serverTransactionId == null) {
        System.out.println("shootme:  null tid.");
        return;
      }
      Response response = messageFactory.createResponse(200, request);
      serverTransactionId.sendResponse(response);
      if (dialog.getState() != DialogState.CONFIRMED) {
        response = messageFactory.createResponse(Response.REQUEST_TERMINATED, inviteRequest);
        inviteTid.sendResponse(response);
      }

    } catch (Exception ex) {
      ex.printStackTrace();
      System.exit(0);
    }
  }
Exemple #7
0
  /** Process the bye request. */
  public void processBye(RequestEvent requestEvent, ServerTransaction serverTransactionId) {
    SipProvider sipProvider = (SipProvider) requestEvent.getSource();
    Request request = requestEvent.getRequest();
    try {
      System.out.println("shootme:  got a bye sending OK.");
      Response response = messageFactory.createResponse(200, request);
      serverTransactionId.sendResponse(response);
      System.out.println("Dialog State is " + serverTransactionId.getDialog().getState());

    } catch (Exception ex) {
      ex.printStackTrace();
      System.exit(0);
    }
  }
Exemple #8
0
  /** Process the bye request. */
  public void processBye(RequestEvent requestEvent, ServerTransaction serverTransactionId) {
    Request request = requestEvent.getRequest();
    Dialog dialog = requestEvent.getDialog();
    System.out.println("local party = " + dialog.getLocalParty());
    try {
      System.out.println("cutme:  got a bye sending OK.");
      Response response = messageFactory.createResponse(200, request);
      serverTransactionId.sendResponse(response);
      System.out.println("Dialog State is " + serverTransactionId.getDialog().getState());

    } catch (Exception ex) {
      ex.printStackTrace();
      System.exit(0);
    }
  }
 /** JAIN Listener method. */
 public void processTimeout(TimeoutEvent timeOutEvent) {
   ProxyDebug.println("TimeoutEvent received");
   SipProvider sipProvider = (SipProvider) timeOutEvent.getSource();
   TransactionsMapping transactionsMapping = null;
   if (timeOutEvent.isServerTransaction()) {
     ServerTransaction serverTransaction = timeOutEvent.getServerTransaction();
     Dialog dialog = serverTransaction.getDialog();
     if (dialog != null) {
       transactionsMapping = (TransactionsMapping) dialog.getApplicationData();
       transactionsMapping.removeMapping(serverTransaction);
     }
   } else {
     ClientTransaction clientTransaction = timeOutEvent.getClientTransaction();
     Dialog dialog = clientTransaction.getDialog();
     ServerTransaction st = null;
     if (dialog != null) {
       transactionsMapping = (TransactionsMapping) dialog.getApplicationData();
       if (transactionsMapping != null) {
         st = transactionsMapping.getServerTransaction(clientTransaction);
       }
       if (st == null) {
         ProxyDebug.println(
             "ERROR, Unable to retrieve the server transaction," + " cannot process timeout!");
         return;
       }
     } else {
       ProxyDebug.println(
           "ERROR, Unable to retrieve the transaction Mapping," + " cannot process timeout!");
       return;
     }
     Request request = st.getRequest();
     // This removes the given mapping from the table but not
     // necessarily the whole thing.
     transactionsMapping.removeMapping(clientTransaction);
     if (!transactionsMapping.hasMapping(st)) {
       // No more mappings left in the transaction table.
       try {
         Response response = messageFactory.createResponse(Response.REQUEST_TIMEOUT, request);
         st.sendResponse(response);
       } catch (ParseException ex) {
         ex.printStackTrace();
       } catch (SipException ex1) {
         ex1.printStackTrace();
       }
     }
   }
 }
  public void processRequest(RequestEvent requestEvent) {
    Request request = requestEvent.getRequest();
    ServerTransaction serverTransactionId = requestEvent.getServerTransaction();

    System.out.println(
        "\n\nRequest "
            + request.getMethod()
            + " received at "
            + sipStack.getStackName()
            + " with server transaction id "
            + serverTransactionId);

    if (request.getMethod().equals(Request.INVITE)) {
      processInvite(requestEvent, serverTransactionId);
    } else if (request.getMethod().equals(Request.ACK)) {
      processAck(requestEvent, serverTransactionId);
    } else if (request.getMethod().equals(Request.BYE)) {
      processBye(requestEvent, serverTransactionId);
    } else if (request.getMethod().equals(Request.CANCEL)) {
      processCancel(requestEvent, serverTransactionId);
    } else {
      try {
        serverTransactionId.sendResponse(messageFactory.createResponse(202, request));

        // send one back
        SipProvider prov = (SipProvider) requestEvent.getSource();
        Request refer = requestEvent.getDialog().createRequest("REFER");
        requestEvent.getDialog().sendRequest(prov.getNewClientTransaction(refer));

      } catch (SipException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (InvalidArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
Exemple #11
0
  public void processBye(Request request, ServerTransaction serverTransactionId) {
    try {
      System.out.println("shootist:  got a bye .");
      if (serverTransactionId == null) {
        System.out.println("shootist:  null TID.");
        return;
      }
      Dialog dialog = serverTransactionId.getDialog();
      System.out.println("Dialog State = " + dialog.getState());
      Response response = messageFactory.createResponse(200, request);
      serverTransactionId.sendResponse(response);
      System.out.println("shootist:  Sending OK.");
      System.out.println("Dialog State = " + dialog.getState());

      this.shutDown();

    } catch (Exception ex) {
      ex.printStackTrace();
      System.exit(0);
    }
  }
    /** Process the invite request. */
    public void processInvite(RequestEvent requestEvent, ServerTransaction serverTransaction) {
      SipProvider sipProvider = (SipProvider) requestEvent.getSource();
      Request request = requestEvent.getRequest();
      try {

        Response okResponse = messageFactory.createResponse(Response.OK, request);
        FromHeader from = (FromHeader) okResponse.getHeader(FromHeader.NAME);
        from.removeParameter("tag");
        Address address =
            addressFactory.createAddress("Shootme <sip:" + myAddress + ":" + myPort + ">");
        ContactHeader contactHeader = headerFactory.createContactHeader(address);
        ToHeader toHeader = (ToHeader) okResponse.getHeader(ToHeader.NAME);
        toHeader.setTag("4321"); // Application is supposed to set.
        okResponse.addHeader(contactHeader);
        sipProvider.sendResponse(okResponse); // Send it through the Provider.

      } catch (Exception ex) {
        ex.printStackTrace();
        System.exit(0);
      }
    }
Exemple #13
0
 public void processResponse(ResponseEvent responseEvent) {
   ClientTransaction ct = responseEvent.getClientTransaction();
   Response response = responseEvent.getResponse();
   ServerTransaction st = (ServerTransaction) ct.getApplicationData();
   try {
     Response otherResponse =
         messageFactory.createResponse(response.getStatusCode(), st.getRequest());
     if (response.getStatusCode() == 200 && ct.getRequest().getMethod().equals("INVITE")) {
       Address address =
           addressFactory.createAddress("B2BUA <sip:" + myAddress + ":" + myPort + ">");
       ContactHeader contactHeader = headerFactory.createContactHeader(address);
       response.addHeader(contactHeader);
       ToHeader toHeader = (ToHeader) otherResponse.getHeader(ToHeader.NAME);
       if (toHeader.getTag() == null)
         toHeader.setTag(new Long(counter.getAndIncrement()).toString());
       otherResponse.addHeader(contactHeader);
     }
     st.sendResponse(otherResponse);
   } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Exemple #14
0
  /** Process the any in dialog request - MESSAGE, BYE, INFO, UPDATE. */
  public void processInDialogRequest(
      RequestEvent requestEvent, ServerTransaction serverTransactionId) {
    SipProvider sipProvider = (SipProvider) requestEvent.getSource();
    Request request = requestEvent.getRequest();
    Dialog dialog = requestEvent.getDialog();
    System.out.println("local party = " + dialog.getLocalParty());
    try {
      System.out.println("b2bua:  got a bye sending OK.");
      Response response = messageFactory.createResponse(200, request);
      serverTransactionId.sendResponse(response);
      System.out.println("Dialog State is " + serverTransactionId.getDialog().getState());

      Dialog otherLeg = (Dialog) dialog.getApplicationData();
      Request otherBye = otherLeg.createRequest(request.getMethod());
      ClientTransaction clientTransaction = sipProvider.getNewClientTransaction(otherBye);
      clientTransaction.setApplicationData(serverTransactionId);
      serverTransactionId.setApplicationData(clientTransaction);
      otherLeg.sendRequest(clientTransaction);

    } catch (Exception ex) {
      ex.printStackTrace();
      System.exit(0);
    }
  }
  private void register() throws IOException {
    Log.info("Registering with " + registrar);
    FromHeader fromHeader = getFromHeader();
    Address fromAddress = fromHeader.getAddress();

    // Request URI
    SipURI requestURI = null;
    try {
      requestURI = addressFactory.createSipURI(null, registrar);

    } catch (ParseException e) {
      throw new IOException("Bad registrar address:" + registrar + " " + e.getMessage());
    }
    // requestURI.setPort(registrarPort);

    try {
      requestURI.setTransportParam(sipProvider.getListeningPoint().getTransport());

    } catch (ParseException e) {
      throw new IOException(
          sipProvider.getListeningPoint().getTransport()
              + " is not a valid transport! "
              + e.getMessage());
    }

    CallIdHeader callIdHeader = sipProvider.getNewCallId();
    CSeqHeader cSeqHeader = null;

    try {
      cSeqHeader = headerFactory.createCSeqHeader(1, Request.REGISTER);
    } catch (ParseException e) {
      // Should never happen
      throw new IOException("Corrupt Sip Stack " + e.getMessage());
    } catch (InvalidArgumentException e) {
      // Should never happen
      throw new IOException("The application is corrupt ");
    }

    ToHeader toHeader = null;
    try {
      String proxyWorkAround = System.getProperty("com.sun.mc.softphone.REGISTRAR_WORKAROUND");

      if (proxyWorkAround != null && proxyWorkAround.toUpperCase().equals("TRUE")) {

        SipURI toURI = (SipURI) (requestURI.clone());
        toURI.setUser(System.getProperty("user.name"));

        toHeader = headerFactory.createToHeader(addressFactory.createAddress(toURI), null);
      } else {
        toHeader = headerFactory.createToHeader(fromAddress, null);
      }
    } catch (ParseException e) {
      throw new IOException(
          "Could not create a To header for address:"
              + fromHeader.getAddress()
              + " "
              + e.getMessage());
    }

    ArrayList viaHeaders = getLocalViaHeaders();
    MaxForwardsHeader maxForwardsHeader = getMaxForwardsHeader();
    Request request = null;

    try {
      request =
          messageFactory.createRequest(
              requestURI,
              Request.REGISTER,
              callIdHeader,
              cSeqHeader,
              fromHeader,
              toHeader,
              viaHeaders,
              maxForwardsHeader);
    } catch (ParseException e) {
      throw new IOException("Could not create the register request! " + e.getMessage());
    }

    ExpiresHeader expHeader = null;

    for (int retry = 0; retry < 2; retry++) {
      try {
        expHeader = headerFactory.createExpiresHeader(expires);
      } catch (InvalidArgumentException e) {
        if (retry == 0) {
          continue;
        }
        throw new IOException(
            "Invalid registrations expiration parameter - " + expires + " " + e.getMessage());
      }
    }

    request.addHeader(expHeader);
    ContactHeader contactHeader = getRegistrationContactHeader();
    request.addHeader(contactHeader);

    try {
      SipURI routeURI =
          (SipURI) addressFactory.createURI("sip:" + proxyCredentials.getProxy() + ";lr");
      RouteHeader routeHeader =
          headerFactory.createRouteHeader(addressFactory.createAddress(routeURI));
      request.addHeader(routeHeader);

    } catch (Exception e) {

      Log.error("Creating registration route error ", e);
    }

    ClientTransaction regTrans = null;
    try {
      regTrans = sipProvider.getNewClientTransaction(request);
    } catch (TransactionUnavailableException e) {
      throw new IOException(
          "Could not create a register transaction!\n"
              + "Check that the Registrar address is correct! "
              + e.getMessage());
    }

    try {
      sipCallId = callIdHeader.getCallId();
      sipServerCallback.addSipListener(sipCallId, this);
      registerRequest = request;
      regTrans.sendRequest();

      Log.debug("Sent register request " + registerRequest);

      if (expires > 0) {
        scheduleReRegistration();
      }
    } catch (Exception e) {
      throw new IOException("Could not send out the register request! " + e.getMessage());
    }

    this.registerRequest = request;
  }
Exemple #16
0
  public ClientTransaction call(SipURI destination) {
    try {

      String fromName = "B2BUA";
      String fromSipAddress = "here.com";
      String fromDisplayName = "B2BUA";

      String toSipAddress = "there.com";
      String toUser = "******";
      String toDisplayName = "Target";

      // create >From Header
      SipURI fromAddress = addressFactory.createSipURI(fromName, fromSipAddress);

      Address fromNameAddress = addressFactory.createAddress(fromAddress);
      fromNameAddress.setDisplayName(fromDisplayName);
      FromHeader fromHeader =
          headerFactory.createFromHeader(
              fromNameAddress, new Long(counter.getAndIncrement()).toString());

      // create To Header
      SipURI toAddress = addressFactory.createSipURI(toUser, toSipAddress);
      Address toNameAddress = addressFactory.createAddress(toAddress);
      toNameAddress.setDisplayName(toDisplayName);
      ToHeader toHeader = headerFactory.createToHeader(toNameAddress, null);

      // create Request URI
      SipURI requestURI = destination;

      // Create ViaHeaders

      ArrayList viaHeaders = new ArrayList();
      String ipAddress = listeningPoint.getIPAddress();
      ViaHeader viaHeader =
          headerFactory.createViaHeader(
              ipAddress, sipProvider.getListeningPoint(transport).getPort(), transport, null);

      // add via headers
      viaHeaders.add(viaHeader);

      // Create ContentTypeHeader
      ContentTypeHeader contentTypeHeader =
          headerFactory.createContentTypeHeader("application", "sdp");

      // Create a new CallId header
      CallIdHeader callIdHeader = sipProvider.getNewCallId();

      // Create a new Cseq header
      CSeqHeader cSeqHeader = headerFactory.createCSeqHeader(1L, Request.INVITE);

      // Create a new MaxForwardsHeader
      MaxForwardsHeader maxForwards = headerFactory.createMaxForwardsHeader(70);

      // Create the request.
      Request request =
          messageFactory.createRequest(
              requestURI,
              Request.INVITE,
              callIdHeader,
              cSeqHeader,
              fromHeader,
              toHeader,
              viaHeaders,
              maxForwards);
      // Create contact headers
      String host = "127.0.0.1";

      SipURI contactUrl = addressFactory.createSipURI(fromName, host);
      contactUrl.setPort(listeningPoint.getPort());
      contactUrl.setLrParam();

      // Create the contact name address.
      SipURI contactURI = addressFactory.createSipURI(fromName, host);
      contactURI.setPort(sipProvider.getListeningPoint(transport).getPort());

      Address contactAddress = addressFactory.createAddress(contactURI);

      // Add the contact address.
      contactAddress.setDisplayName(fromName);

      ContactHeader contactHeader = headerFactory.createContactHeader(contactAddress);
      request.addHeader(contactHeader);

      // You can add extension headers of your own making
      // to the outgoing SIP request.
      // Add the extension header.
      Header extensionHeader = headerFactory.createHeader("My-Header", "my header value");
      request.addHeader(extensionHeader);

      String sdpData =
          "v=0\r\n"
              + "o=4855 13760799956958020 13760799956958020"
              + " IN IP4  129.6.55.78\r\n"
              + "s=mysession session\r\n"
              + "p=+46 8 52018010\r\n"
              + "c=IN IP4  129.6.55.78\r\n"
              + "t=0 0\r\n"
              + "m=audio 6022 RTP/AVP 0 4 18\r\n"
              + "a=rtpmap:0 PCMU/8000\r\n"
              + "a=rtpmap:4 G723/8000\r\n"
              + "a=rtpmap:18 G729A/8000\r\n"
              + "a=ptime:20\r\n";
      byte[] contents = sdpData.getBytes();

      request.setContent(contents, contentTypeHeader);
      // You can add as many extension headers as you
      // want.

      extensionHeader = headerFactory.createHeader("My-Other-Header", "my new header value ");
      request.addHeader(extensionHeader);

      Header callInfoHeader = headerFactory.createHeader("Call-Info", "<http://www.antd.nist.gov>");
      request.addHeader(callInfoHeader);

      // Create the client transaction.
      ClientTransaction inviteTid = sipProvider.getNewClientTransaction(request);

      System.out.println("inviteTid = " + inviteTid);

      // send the request out.

      inviteTid.sendRequest();

      return inviteTid;

    } catch (Exception ex) {
      System.out.println(ex.getMessage());
      ex.printStackTrace();
    }
    return null;
  }
  public void processResponse(ResponseEvent responseReceivedEvent) {
    /// System.out.println("=> BUNDLE: br.ufes.inf.ngn.televoto.client.logic | CLASS: LogicListener
    // | METOD: processResponse ");//By Ju
    try {
      Response myResponse = responseReceivedEvent.getResponse();
      logger.info("<<< " + myResponse.toString());

      ClientTransaction thisClientTransaction = responseReceivedEvent.getClientTransaction();

      int myStatusCode = myResponse.getStatusCode();

      switch (status) {
        case WAIT_PROV:
          if (!thisClientTransaction.equals(myClientTransaction))
            myClientTransaction = thisClientTransaction;

          if (myStatusCode < 200) {
            status = WAIT_FINAL;
            myDialog = thisClientTransaction.getDialog();
          } else if (myStatusCode < 300) {
            myDialog = thisClientTransaction.getDialog();
            CSeqHeader originalCSeq =
                (CSeqHeader) myClientTransaction.getRequest().getHeader(CSeqHeader.NAME);
            long numseq = originalCSeq.getSeqNumber();
            Request myAck = myDialog.createAck(numseq);
            myAck.addHeader(myContactHeader);
            myDialog.sendAck(myAck);
            // logger.info(">>> "+myAck.toString());
            status = ESTABLISHED;
            byte[] cont = (byte[]) myResponse.getContent();
            answerInfo = mySdpManager.getSdp(cont);

          } else {
            if (myStatusCode == 401) {

            } else {
              status = IDLE;
              CSeqHeader originalCSeq =
                  (CSeqHeader) myClientTransaction.getRequest().getHeader(CSeqHeader.NAME);
              long numseq = originalCSeq.getSeqNumber();
              Request myAck = myDialog.createAck(numseq);
              myAck.addHeader(myContactHeader);
              myDialog.sendAck(myAck);
              // logger.info(">>> "+myAck.toString());
            }
          }
          break;

        case WAIT_FINAL:
          if (!thisClientTransaction.equals(myClientTransaction))
            myClientTransaction = thisClientTransaction;

          if (myStatusCode < 200) {
            status = WAIT_FINAL;
            myDialog = thisClientTransaction.getDialog();
          } else if (myStatusCode < 300) {
            if (useQueue.equals("yes")) {
              status = IDLE;
            } else {
              status = ESTABLISHED;
            }

            myDialog = thisClientTransaction.getDialog();
            CSeqHeader originalCSeq =
                (CSeqHeader) myClientTransaction.getRequest().getHeader(CSeqHeader.NAME);
            long numseq = originalCSeq.getSeqNumber();
            Request myAck = myDialog.createAck(numseq); // Aquiiii
            myAck.addHeader(myContactHeader);
            myDialog.sendAck(myAck);
            // logger.info(">>> "+myAck.toString());
            byte[] cont = (byte[]) myResponse.getContent();
            answerInfo = mySdpManager.getSdp(cont);

          } else {
            // Cancelando requisição ao cliente
            Request myCancelRequest = myClientTransaction.createCancel();
            ClientTransaction myCancelClientTransaction =
                mySipProvider.getNewClientTransaction(myCancelRequest);
            myCancelClientTransaction.sendRequest();
            // logger.info(">>> " + myCancelRequest.toString());
            status = IDLE;
          }
          break;

        case REGISTERING:
          if (!thisClientTransaction.equals(myClientTransaction))
            myClientTransaction = thisClientTransaction;

          if (myStatusCode == 200) {
            status = IDLE;
            if (!Unregistring) {

              System.out.println(myName + ": Registrado");

              // inserir captura de timestamp
              // logger.info(myName + ";INVITE;" +  getTime());
              // Random gerador = new Random();
              // int temp = gerador.nextInt(10);
              // System.out.println(myName + ": Esperando " + temp + "segundos");
              // Thread.sleep(temp);

              System.out.println(myName + ": chamando " + destination);

              SdpInfo offerInfo = new SdpInfo();
              offerInfo.IpAddress = myIP;
              offerInfo.aport = myAudioPort;
              offerInfo.aformat = 0;
              byte[] content = mySdpManager.createSdp(offerInfo);

              // Via
              // ViaHeader comentei
              myViaHeader = myHeaderFactory.createViaHeader(myIP, myPort, "udp", null);
              myViaHeader.setRPort();
              ArrayList viaHeaders = new ArrayList();
              viaHeaders.add(myViaHeader);

              // From
              Address addressOfRecord = myAddressFactory.createAddress("<sip:" + myUserID + ">");
              FromHeader myFromHeader = myHeaderFactory.createFromHeader(addressOfRecord, "456249");

              // To
              String dstURI[] = destination.split("@");
              String dstSipAlias = dstURI[0];
              Address destinationAddress =
                  myAddressFactory.createAddress("<sip:" + destination + ">");
              javax.sip.address.URI myRequestURI = destinationAddress.getURI();
              ToHeader myToHeader = myHeaderFactory.createToHeader(destinationAddress, null);

              // MaxForwards
              MaxForwardsHeader myMaxForwardsHeader = myHeaderFactory.createMaxForwardsHeader(70);

              // Call-ID
              CallIdHeader myCallIdHeader = mySipProvider.getNewCallId();

              // CSeq
              Random random = new Random();
              CSeqHeader myCSeqHeader =
                  myHeaderFactory.createCSeqHeader(random.nextInt(1000) * 1L, "INVITE");

              // Create SIP request
              Request myRequest =
                  myMessageFactory.createRequest(
                      myRequestURI,
                      "INVITE",
                      myCallIdHeader,
                      myCSeqHeader,
                      myFromHeader,
                      myToHeader,
                      viaHeaders,
                      myMaxForwardsHeader);

              // Contact
              Address contactAddress =
                  myAddressFactory.createAddress(
                      "<sip:" + mySipAlias + "@" + myIP + ":" + myPort + ";transport=udp>");
              myContactHeader = myHeaderFactory.createContactHeader(contactAddress);
              myRequest.addHeader(myContactHeader);

              // Allow
              Allow myAllow = new Allow();
              myAllow.setMethod(
                  "INVITE, ACK, CANCEL, BYE, MESSAGE, OPTIONS, NOTIFY, PRACK, UPDATE, REFER");
              myRequest.addHeader(myAllow);

              // Privacy
              Privacy myPrivacy = new Privacy("none");
              myRequest.addHeader(myPrivacy);

              // PPreferredIdentity
              HeaderFactoryImpl myHeaderFactoryImpl = new HeaderFactoryImpl();
              PPreferredIdentityHeader myPPreferredIdentityHeader =
                  myHeaderFactoryImpl.createPPreferredIdentityHeader(
                      myAddressFactory.createAddress("sip:" + myName + '@' + myServer));
              myRequest.addHeader(myPPreferredIdentityHeader);

              // Route
              Address routeAddress =
                  myAddressFactory.createAddress("sip:orig@scscf." + myServer + ":6060;lr");
              // RouteHeader comentei
              myRouteHeader = myHeaderFactory.createRouteHeader(routeAddress);
              myRequest.addHeader(myRouteHeader);

              // Para proxy funcionar
              SipURI outboundProxyURI = myAddressFactory.createSipURI("proxy", myProxyIP);
              outboundProxyURI.setLrParam();
              outboundProxyURI.setPort(myProxyPort);
              myRouteHeader =
                  myHeaderFactory.createRouteHeader(
                      myAddressFactory.createAddress(outboundProxyURI));
              myRequest.addFirst(myRouteHeader);

              // Content Type
              ContentTypeHeader contentTypeHeader =
                  myHeaderFactory.createContentTypeHeader("application", "sdp");
              myRequest.setContent(content, contentTypeHeader);

              // ClientTransaction comentei aqui
              myClientTransaction = mySipProvider.getNewClientTransaction(myRequest);
              myClientTransaction.setRetransmitTimer(700);
              myClientTransaction.sendRequest();

              status = WAIT_PROV;

              logger.info(">>> " + myRequest.toString());

            } else {
              this.setOff(mySipStack);
            }
          } else {
            if (myStatusCode == 403) {

              System.out.println("Problemas com credenciais!!!!\n");
            } else if (myStatusCode == 401) {

              myName = (String) this.getLocalName();
              myUserID = (String) this.getLocalName() + "@" + myServer;

              Address contactAddress =
                  myAddressFactory.createAddress("sip:" + myName + '@' + myIP + ":" + myPort);
              myContactHeader = myHeaderFactory.createContactHeader(contactAddress);

              myViaHeader = myHeaderFactory.createViaHeader(myIP, myPort, "udp", null);

              fromAddress = myAddressFactory.createAddress(myName + " <sip:" + myUserID + ">");

              Address registrarAddress = myAddressFactory.createAddress("sip:" + myServer);
              Address registerToAddress = fromAddress;
              Address registerFromAddress = fromAddress;

              ToHeader myToHeader = myHeaderFactory.createToHeader(registerToAddress, null);
              FromHeader myFromHeader =
                  myHeaderFactory.createFromHeader(registerFromAddress, "647554");

              ArrayList myViaHeaders = new ArrayList();
              myViaHeaders.add(myViaHeader);

              // System.out.println("myClientTransaction.getRequest():"+
              // myClientTransaction.getRequest());
              CSeqHeader originalCSeq =
                  (CSeqHeader) myClientTransaction.getRequest().getHeader(CSeqHeader.NAME);
              long numseq = originalCSeq.getSeqNumber();
              MaxForwardsHeader myMaxForwardsHeader = myHeaderFactory.createMaxForwardsHeader(70);
              CSeqHeader myCSeqHeader = myHeaderFactory.createCSeqHeader(numseq + 1L, "REGISTER");

              CallIdHeader myCallID =
                  (CallIdHeader) myClientTransaction.getRequest().getHeader(CallIdHeader.NAME);
              CallIdHeader myCallIDHeader = myCallID;
              SipURI myRequestURI = (SipURI) registrarAddress.getURI();
              Request myRegisterRequest =
                  myMessageFactory.createRequest(
                      myRequestURI,
                      "REGISTER",
                      myCallIDHeader,
                      myCSeqHeader,
                      myFromHeader,
                      myToHeader,
                      myViaHeaders,
                      myMaxForwardsHeader);
              myRegisterRequest.addHeader(myContactHeader);

              // Expires
              ExpiresHeader myExpiresHeader;
              if (Unregistring) {
                myExpiresHeader = myHeaderFactory.createExpiresHeader(0);
                myContactHeader.setExpires(0);
              } else {
                myExpiresHeader = myHeaderFactory.createExpiresHeader(60000);
              }
              myRegisterRequest.addHeader(myExpiresHeader);

              // Allow
              Allow myAllow = new Allow();
              myAllow.setMethod(
                  "INVITE, ACK, CANCEL, BYE, MESSAGE, OPTIONS, NOTIFY, PRACK, UPDATE, REFER");
              myRegisterRequest.addHeader(myAllow);

              // Privacy
              Privacy myPrivacy = new Privacy("none");
              myRegisterRequest.addHeader(myPrivacy);

              // PPreferredIdentity
              HeaderFactoryImpl myHeaderFactoryImpl = new HeaderFactoryImpl();
              PPreferredIdentityHeader myPPreferredIdentityHeader =
                  myHeaderFactoryImpl.createPPreferredIdentityHeader(
                      myAddressFactory.createAddress("sip:" + myName + '@' + myServer));
              myRegisterRequest.addHeader(myPPreferredIdentityHeader);

              // Supported
              Supported mySupported = new Supported("path");
              myRegisterRequest.addHeader(mySupported);

              myWWWAuthenticateHeader =
                  Utils.makeAuthHeader(
                      myHeaderFactory, myResponse, myRegisterRequest, myUserID, myPassword);
              myRegisterRequest.addHeader(myWWWAuthenticateHeader);

              myClientTransaction = mySipProvider.getNewClientTransaction(myRegisterRequest);
              myClientTransaction.sendRequest();

              // logger.info(">>> "+myRegisterRequest.toString());
              // System.out.println(">>> " + myRegisterRequest.toString());
              status = REGISTERING;
            }
          }
          break;
      }
    } catch (Exception excep) {
      excep.printStackTrace();
    }
  }
  public void processRequest(RequestEvent requestReceivedEvent) {
    /// System.out.println("=> BUNDLE: br.ufes.inf.ngn.televoto.client.logic | CLASS: LogicListener
    // | METOD: processRequest ");//By Ju

    String method;
    Response myResponse;
    ToHeader myToHeader;
    Request myRequest = requestReceivedEvent.getRequest();
    method = myRequest.getMethod();
    // logger.info(myRequest.toString());
    if (!method.equals("CANCEL")) {
      myServerTransaction = requestReceivedEvent.getServerTransaction();
    }
    try {

      switch (status) {
        case WAIT_PROV:
          status = WAIT_ACK;
          System.out.println("Chamando....");
          break;

        case IDLE:
          if (method.equals("INVITE")) {
            if (myServerTransaction == null) {
              myServerTransaction = mySipProvider.getNewServerTransaction(myRequest);
            }
            byte[] cont = (byte[]) myRequest.getContent();
            offerInfo = mySdpManager.getSdp(cont);

            answerInfo.IpAddress = myIP;
            answerInfo.aport = myAudioPort;
            answerInfo.aformat = offerInfo.aformat;

            if (useQueue.equals("yes")) {
              status = ESTABLISHED;
            } else {
              // envio do PROVISIONAL 180
              myResponse = myMessageFactory.createResponse(180, myRequest);
              myResponse.addHeader(myContactHeader);
              myToHeader = (ToHeader) myResponse.getHeader("To");
              myToHeader.setTag("454326");
              myServerTransaction.sendResponse(myResponse);
              myDialog = myServerTransaction.getDialog();
              // logger.info(">>> "+myResponse.toString());
              status = WAIT_ACK;
            }
            // inicio do envio do ACK ao cliente em confirmacao ao PROV_180 e envio do SDP
            Request originalRequest = myServerTransaction.getRequest();
            myResponse = myMessageFactory.createResponse(200, originalRequest);
            // System.out.println(originalRequest.toString());
            myToHeader = (ToHeader) myResponse.getHeader("To");
            myResponse.addHeader(myContactHeader);

            // SEND ANSWER SDP

            ContentTypeHeader contentTypeHeader =
                myHeaderFactory.createContentTypeHeader("application", "sdp");
            byte[] content = mySdpManager.createSdp(answerInfo);
            myResponse.setContent(content, contentTypeHeader);

            // aguardando ACK do cliente
            myServerTransaction.sendResponse(myResponse);
            myDialog = myServerTransaction.getDialog();

            new Timer().schedule(new MyTimerTask(this), 500000); // Aqui!!!
            // logger.info(">>> " + myResponse.toString());

          }
          if (method.equals("OPTIONS")) {
            if (myServerTransaction == null) {
              myServerTransaction = mySipProvider.getNewServerTransaction(myRequest);
            }

            Request originalRequest = myServerTransaction.getRequest();
            myResponse = myMessageFactory.createResponse(200, originalRequest);
            myResponse.addHeader(myContactHeader);
            myServerTransaction.sendResponse(myResponse);
          }

          break;
        case ESTABLISHED:
          if (method.equals("BYE")) {
            // capturar o timestamp
            // logger.info(myName + ";BYE;" +  getTime());
            System.out.println(myName + ": BYE");
            myResponse = myMessageFactory.createResponse(200, myRequest);
            myResponse.addHeader(myContactHeader);
            myServerTransaction.sendResponse(myResponse);
            // logger.info(">>> "+myResponse.toString());
            if (ack == 1) {
              ack = 0;
              redial++;

              if (redial <= dialTimes) {
                // inserir captura timestamp
                logger.info(myName + ";BYE;" + getTime());
                System.out.println(myName + ": rediscagem " + redial + " para: " + destination);

                String dstURI[] = destination.split("@");
                String dstSipAlias = dstURI[0];
                Address destinationAddress =
                    myAddressFactory.createAddress(dstSipAlias + " <sip:" + destination + ">");
                javax.sip.address.URI myRequestURI = destinationAddress.getURI();

                Address addressOfRecord =
                    myAddressFactory.createAddress(
                        mySipAlias + " <sip:" + mySipAlias + "@" + myIP + ":" + myPort + ">");
                // HeaderFactory comentei
                myHeaderFactory = mySipFactory.createHeaderFactory();
                // ViaHeader comentei
                myViaHeader = myHeaderFactory.createViaHeader(myIP, myPort, "udp", null);
                ArrayList viaHeaders = new ArrayList();
                viaHeaders.add(myViaHeader);
                MaxForwardsHeader myMaxForwardsHeader = myHeaderFactory.createMaxForwardsHeader(70);
                CallIdHeader myCallIdHeader = mySipProvider.getNewCallId();
                CSeqHeader myCSeqHeader = myHeaderFactory.createCSeqHeader(1L, "INVITE");
                FromHeader myFromHeader =
                    myHeaderFactory.createFromHeader(addressOfRecord, "456249");
                myToHeader = myHeaderFactory.createToHeader(destinationAddress, null);

                myRequest =
                    myMessageFactory.createRequest(
                        myRequestURI,
                        "INVITE",
                        myCallIdHeader,
                        myCSeqHeader,
                        myFromHeader,
                        myToHeader,
                        viaHeaders,
                        myMaxForwardsHeader);

                Address contactAddress =
                    myAddressFactory.createAddress(
                        "<sip:" + mySipAlias + "@" + myIP + ":" + myPort + ">");
                myContactHeader = myHeaderFactory.createContactHeader(contactAddress);
                myRequest.addHeader(myContactHeader);

                SdpInfo offerInfo = new SdpInfo();

                offerInfo.IpAddress = myIP;
                offerInfo.aport = myAudioPort;

                offerInfo.aformat = 0;

                ContentTypeHeader contentTypeHeader =
                    myHeaderFactory.createContentTypeHeader("application", "sdp");
                byte[] content = mySdpManager.createSdp(offerInfo);
                myRequest.setContent(content, contentTypeHeader);

                // ClientTransaction Comentei aqui
                myClientTransaction = mySipProvider.getNewClientTransaction(myRequest);
                myClientTransaction.sendRequest();
                logger.info(myName + ";INVITE;" + getTime());
                // System.out.println(myRequest);
                status = WAIT_PROV;
              } else {
                status = IDLE;
                System.out.println(myName + ": pronto.");
              }
            } else ack++;
          }
          break;

        case RINGING:
          if (method.equals("CANCEL")) {
            ServerTransaction myCancelServerTransaction =
                requestReceivedEvent.getServerTransaction();
            Request originalRequest = myServerTransaction.getRequest();
            myResponse = myMessageFactory.createResponse(487, originalRequest);
            myServerTransaction.sendResponse(myResponse);
            Response myCancelResponse = myMessageFactory.createResponse(200, myRequest);
            myCancelServerTransaction.sendResponse(myCancelResponse);
            // logger.info(">>> "+myResponse.toString());
            // logger.info(">>> "+myCancelResponse.toString());
            status = IDLE;
          }
          break;

        case WAIT_ACK:
          if (method.equals("ACK")) {
            status = ESTABLISHED;
            System.out.println("Conectado ...");
            // SendMedia(offerInfo.IpAddress, offerInfo.aport);
          }

          break;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void setup() {
    /// System.out.println("=> BUNDLE: br.ufes.inf.ngn.televoto.client.logic | CLASS: LogicListener
    // | METOD: setup ");//By Ju
    try {
      // String log4jConfPath = "//etc//osgi//log4j.properties"; //comentei
      // PropertyConfigurator.configure(log4jConfPath);
      if (!Unregistring) { // Se é um registro
        Object parametros[] = new Object[9];
        parametros = getArguments();
        myDataSource = Activator.ds;
        myServer = (String) parametros[3];
        destination = (String) parametros[6];
        dialTimes = (Integer) parametros[7];
        useQueue = (String) parametros[8];

        try {
          myIP = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
          e.printStackTrace();
        }

        mySipAlias = (String) parametros[0];
        myName = (String) this.getLocalName();
        myUserID = (String) parametros[1];
        ;
        myPassword = (String) parametros[5];
        myPort = (Integer) parametros[2];
        myAudioPort = (Integer) parametros[4];
        myProxyIP = (String) parametros[9];
        myProxyPort = (Integer) parametros[10];
        afmt = Activator.afmt;
        mySipFactory = SipFactory.getInstance();
        mySipFactory.setPathName("gov.nist");
      }
      mySdpManager = new SdpManager();
      answerInfo = new SdpInfo();
      offerInfo = new SdpInfo();

      myProperties = new Properties();
      myProperties.setProperty("javax.sip.STACK_NAME", myName);
      myProperties.setProperty(
          "javax.sip.OUTBOUND_PROXY", myProxyIP + ":" + myProxyPort + "/UDP"); // Proxy
      mySipStack = mySipFactory.createSipStack(myProperties);
      myMessageFactory = mySipFactory.createMessageFactory();
      myHeaderFactory = mySipFactory.createHeaderFactory();
      myAddressFactory = mySipFactory.createAddressFactory();
      if (!Unregistring) {
        myListeningPoint = mySipStack.createListeningPoint(myIP, myPort, "udp");
        mySipProvider = mySipStack.createSipProvider(myListeningPoint);
        mySipProvider.addSipListener(this);
      }

      myViaHeader = myHeaderFactory.createViaHeader(myIP, myPort, "udp", null);

      Address routeAddress = myAddressFactory.createAddress("sip:" + myServer + ";lr");
      myRouteHeader = myHeaderFactory.createRouteHeader(routeAddress);

      fromAddress = myAddressFactory.createAddress(myName + " <sip:" + myUserID + ">");

      Address registrarAddress = myAddressFactory.createAddress("sip:" + myServer);
      Address registerToAddress = fromAddress;
      Address registerFromAddress = fromAddress;

      ToHeader myToHeader = myHeaderFactory.createToHeader(registerToAddress, null);
      FromHeader myFromHeader = myHeaderFactory.createFromHeader(registerFromAddress, "647554");

      ArrayList myViaHeaders = new ArrayList();
      myViaHeaders.add(myViaHeader);

      MaxForwardsHeader myMaxForwardsHeader = myHeaderFactory.createMaxForwardsHeader(70);
      Random random = new Random();
      CSeqHeader myCSeqHeader =
          myHeaderFactory.createCSeqHeader(random.nextInt(1000) * 1L, "REGISTER");

      CallIdHeader myCallIDHeader = mySipProvider.getNewCallId();
      SipURI myRequestURI = (SipURI) registrarAddress.getURI();
      Request myRegisterRequest =
          myMessageFactory.createRequest(
              myRequestURI,
              "REGISTER",
              myCallIDHeader,
              myCSeqHeader,
              myFromHeader,
              myToHeader,
              myViaHeaders,
              myMaxForwardsHeader);

      // Expires
      ExpiresHeader myExpiresHeader;
      if (Unregistring) {
        myContactHeader.setExpires(0);
        myExpiresHeader = myHeaderFactory.createExpiresHeader(0);
      } else {
        myExpiresHeader = myHeaderFactory.createExpiresHeader(60000);
      }
      myRegisterRequest.addHeader(myExpiresHeader);

      // Allow
      Allow myAllow = new Allow();
      myAllow.setMethod("INVITE, ACK, CANCEL, BYE, MESSAGE, OPTIONS, NOTIFY, PRACK, UPDATE, REFER");
      myRegisterRequest.addHeader(myAllow);

      // Contact
      Address contactAddress =
          myAddressFactory.createAddress(
              "sip:" + myName + '@' + myIP + ":" + myPort + ";transport=udp");
      myContactHeader = myHeaderFactory.createContactHeader(contactAddress);
      myRegisterRequest.addHeader(myContactHeader);

      // Authorization
      Authorization myAuthorization = new Authorization();
      myAuthorization.setScheme("Digest");
      myAuthorization.setUsername(myUserID);
      myAuthorization.setRealm(myServer);
      myAuthorization.setNonce("");
      myAuthorization.setURI(myRegisterRequest.getRequestURI());
      myAuthorization.setResponse("");
      myRegisterRequest.addHeader(myAuthorization);

      // PPreferredIdentity
      HeaderFactoryImpl myHeaderFactoryImpl = new HeaderFactoryImpl();
      PPreferredIdentityHeader myPPreferredIdentityHeader =
          myHeaderFactoryImpl.createPPreferredIdentityHeader(
              myAddressFactory.createAddress("sip:" + myName + '@' + myServer));
      myRegisterRequest.addHeader(myPPreferredIdentityHeader);

      // Privacy
      Privacy myPrivacy = new Privacy("none");
      myRegisterRequest.addHeader(myPrivacy);

      // Supported
      Supported mySupported = new Supported("path");
      myRegisterRequest.addHeader(mySupported);

      // Envia requisição SIP
      myClientTransaction = mySipProvider.getNewClientTransaction(myRegisterRequest);
      myClientTransaction.sendRequest();

      // logger.info(myRegisterRequest.toString());
      // System.out.println(">>> " + myRegisterRequest.toString());
      status = REGISTERING;
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /** This is a listener method. */
  public void processRequest(RequestEvent requestEvent) {
    Request request = requestEvent.getRequest();
    SipProvider sipProvider = (SipProvider) requestEvent.getSource();
    ServerTransaction serverTransaction = requestEvent.getServerTransaction();
    try {

      if (ProxyDebug.debug)
        ProxyDebug.println(
            "\n****************************************************"
                + "\nRequest "
                + request.getMethod()
                + " received:\n"
                + request.toString());

      if (ProxyDebug.debug) ProxyUtilities.printTransaction(serverTransaction);

      /** **************************************************************************** */
      /** ********************* PROXY BEHAVIOR *********************************** */
      /** **************************************************************************** */

      /*
       * RFC 3261: 16.2: For all new requests, including any with unknown
       * methods, an element intending to proxy the request MUST:
       *
       * 1. Validate the request (Section 16.3)
       *
       * 2. Preprocess routing information (Section 16.4)
       *
       * 3. Determine target(s) for the request (Section 16.5)
       *
       * 4. Forward the request to each target (Section 16.6)
       *
       * 5. Process all responses (Section 16.7)
       */

      /** **************************************************************************** */
      /** *************************** 1. Validate the request (Section 16.3) ********* */
      /** **************************************************************************** */

      /*
       * Before an element can proxy a request, it MUST verify the
       * message's validity
       */

      RequestValidation requestValidation = new RequestValidation(this);
      if (!requestValidation.validateRequest(sipProvider, request, serverTransaction)) {
        // An appropriate response has been sent back by the request
        // validation step, so we just return. The request has been
        // processed!
        if (ProxyDebug.debug)
          ProxyDebug.println(
              "Proxy, processRequest(), the request has not been"
                  + " validated, so the request is discarded "
                  + " (an error code has normally been"
                  + " sent back)");
        return;
      }

      // Let's check if the ACK is for the proxy: if there is no Route
      // header: it is mandatory for the ACK to be forwarded
      if (request.getMethod().equals(Request.ACK)) {
        ListIterator routes = request.getHeaders(RouteHeader.NAME);

        if (routes == null || !routes.hasNext()) {
          if (ProxyDebug.debug)
            ProxyDebug.println(
                "Proxy, processRequest(), "
                    + "the request is an ACK"
                    + " targeted for the proxy, we ignore it");
          return;
        }
        /* added code */
        CallID call_id = (CallID) request.getHeader(CallID.CALL_ID);
        String call_id_str = call_id.getCallId();
        TimeThreadController.Start(call_id_str);
        /* end of added code */

      }

      if (serverTransaction == null) {
        String method = request.getMethod();
        // Methods that creates dialogs, so that can
        // generate transactions
        if (method.equals(Request.INVITE) || method.equals(Request.SUBSCRIBE)) {
          try {
            serverTransaction = sipProvider.getNewServerTransaction(request);
            TransactionsMapping transactionsMapping =
                (TransactionsMapping) serverTransaction.getDialog().getApplicationData();
            if (transactionsMapping == null) {
              transactionsMapping = new TransactionsMapping(serverTransaction);
            }
          } catch (TransactionAlreadyExistsException e) {
            if (ProxyDebug.debug)
              ProxyDebug.println(
                  "Proxy, processRequest(), this request" + " is a retransmission, we drop it!");
          }
        }
      }

      /** ************************************************************************ */
      /** **** 2. Preprocess routing information (Section 16.4) ****************** */
      /** ************************************************************************ */

      /*
       * The proxy MUST inspect the Request-URI of the request. If the
       * Request-URI of the request contains a value this proxy previously
       * placed into a Record-Route header field (see Section 16.6 item
       * 4), the proxy MUST replace the Request-URI in the request with
       * the last value from the Route header field, and remove that value
       * from the Route header field. The proxy MUST then proceed as if it
       * received this modified request. ..... (idem to below:) 16.12. The
       * proxy will inspect the URI in the topmost Route header field
       * value. If it indicates this proxy, the proxy removes it from the
       * Route header field (this route node has been reached).
       */

      ListIterator routes = request.getHeaders(RouteHeader.NAME);
      if (routes != null) {
        if (routes.hasNext()) {
          RouteHeader routeHeader = (RouteHeader) routes.next();
          Address routeAddress = routeHeader.getAddress();
          SipURI routeSipURI = (SipURI) routeAddress.getURI();

          String host = routeSipURI.getHost();
          int port = routeSipURI.getPort();

          if (sipStack.getIPAddress().equals(host)) {
            Iterator lps = sipStack.getListeningPoints();
            while (lps != null && lps.hasNext()) {
              ListeningPoint lp = (ListeningPoint) lps.next();
              if (lp.getPort() == port) {
                if (ProxyDebug.debug)
                  ProxyDebug.println(
                      "Proxy, processRequest(),"
                          + " we remove the first route form "
                          + " the RouteHeader;"
                          + " it matches the proxy");
                routes.remove();
                break;
              }
            }
          }
        }
      }

      /*
       * If the Request-URI contains a maddr parameter, the proxy MUST
       * check to see if its value is in the set of addresses or domains
       * the proxy is configured to be responsible for. If the Request-URI
       * has a maddr parameter with a value the proxy is responsible for,
       * and the request was received using the port and transport
       * indicated (explicitly or by default) in the Request-URI, the
       * proxy MUST strip the maddr and any non-default port or transport
       * parameter and continue processing as if those values had not been
       * present in the request.
       */

      URI requestURI = request.getRequestURI();
      if (requestURI.isSipURI()) {
        SipURI requestSipURI = (SipURI) requestURI;
        if (requestSipURI.getMAddrParam() != null) {
          // The domain the proxy is configured to be responsible for
          // is defined
          // by stack_domain parameter in the configuration file:
          if (configuration.hasDomain(requestSipURI.getMAddrParam())) {
            if (ProxyDebug.debug)
              ProxyDebug.println(
                  "Proxy, processRequest(),"
                      + " The maddr contains a domain we are responsible for,"
                      + " we remove the mAddr parameter from the original"
                      + " request");
            // We have to strip the madr parameter:
            requestSipURI.removeParameter("maddr");
            // We have to strip the port parameter:
            if (requestSipURI.getPort() != 5060 && requestSipURI.getPort() != -1) {
              requestSipURI.setPort(5060);
            }
            // We have to strip the transport parameter:
            requestSipURI.removeParameter("transport");
          } else {
            // The Maddr parameter is not a domain we have to take
            // care of, we pass this check...
          }
        } else {
          // No Maddr parameter, we pass this check...
        }
      } else {
        // No SipURI, so no Maddr parameter, we pass this check...
      }

      /** *************************************************************************** */
      /** *********** 3. Determine target(s) for the request (Section 16.5) ********* */
      /** ************************************************************************** */
      /*
       * The set of targets will either be predetermined by the contents
       * of the request or will be obtained from an abstract location
       * service. Each target in the set is represented as a URI.
       */

      Vector targetURIList = new Vector();
      URI targetURI;

      /*
       * If the Request-URI of the request contains an maddr parameter,
       * the Request-URI MUST be placed into the target set as the only
       * target URI, and the proxy MUST proceed to Section 16.6.
       */

      if (requestURI.isSipURI()) {
        SipURI requestSipURI = (SipURI) requestURI;
        if (requestSipURI.getMAddrParam() != null) {
          targetURI = requestURI;
          targetURIList.addElement(targetURI);
          if (ProxyDebug.debug)
            ProxyDebug.println(
                "Proxy, processRequest(),"
                    + " the only target is the Request-URI (mAddr parameter)");

          // 4. Forward the request statefully:
          requestForwarding.forwardRequest(
              targetURIList, sipProvider, request, serverTransaction, true);

          return;
        }
      }

      /*
       * If the domain of the Request-URI indicates a domain this element
       * is not responsible for, the Request-URI MUST be placed into the
       * target set as the only target, and the element MUST proceed to
       * the task of Request Forwarding (Section 16.6).
       */

      if (requestURI.isSipURI()) {
        SipURI requestSipURI = (SipURI) requestURI;
        if (!configuration.hasDomain(requestSipURI.getHost())) {
          if (ProxyDebug.debug)
            ProxyDebug.println(
                "Proxy, processRequest(),"
                    + " we are not responsible for the domain: Let's check if we have"
                    + " a registration for this domain from another proxy");

          // We have to check if another proxy did not registered
          // to us, in this case we have to use the contacts provided
          // by the registered proxy to create the targets:
          if (registrar.hasDomainRegistered(request)) {
            targetURIList = registrar.getDomainContactsURI(request);
            if (targetURIList != null && !targetURIList.isEmpty()) {
              if (ProxyDebug.debug) {
                ProxyDebug.println(
                    "Proxy, processRequest(), we have"
                        + " a registration for this domain from another proxy");
              }
              // 4. Forward the request statefully:
              requestForwarding.forwardRequest(
                  targetURIList, sipProvider, request, serverTransaction, true);
              return;

            } else {
              targetURIList = new Vector();
              ProxyDebug.println(
                  "Proxy, processRequest(),"
                      + " we are not responsible for the domain: the only target"
                      + " URI is given by the request-URI");
              targetURI = requestURI;
              targetURIList.addElement(targetURI);
            }
          } else {
            ProxyDebug.println(
                "Proxy, processRequest(),"
                    + " we are not responsible for the domain: the only target"
                    + " URI is given by the request-URI");
            targetURI = requestURI;
            targetURIList.addElement(targetURI);
          }

          // 4. Forward the request statelessly:
          requestForwarding.forwardRequest(
              targetURIList, sipProvider, request, serverTransaction, false);

          return;
        } else {
          ProxyDebug.println(
              "Proxy, processRequest(),"
                  + " we are responsible for the domain... Let's find the contact...");
        }
      }

      // we use a SIP registrar:
      if (request.getMethod().equals(Request.REGISTER)) {
        if (ProxyDebug.debug) ProxyDebug.println("Incoming request Register");
        // we call the RegisterProcessing:
        registrar.processRegister(request, sipProvider, serverTransaction);
        // Henrik: let the presenceserver do some processing too
        if (isPresenceServer()) {
          presenceServer.processRegisterRequest(sipProvider, request, serverTransaction);
        }

        return;
      }

      /*
       * If we receive a subscription targeted to a user that is
       * publishing its state here, send to presence server
       */
      if (isPresenceServer() && (request.getMethod().equals(Request.SUBSCRIBE))) {
        ProxyDebug.println("Incoming request Subscribe");

        if (presenceServer.isStateAgent(request)) {
          Request clonedRequest = (Request) request.clone();
          presenceServer.processSubscribeRequest(sipProvider, clonedRequest, serverTransaction);
        } else {
          // Do we know this guy?

          targetURIList = registrar.getContactsURI(request);
          if (targetURIList == null) {
            // If not respond that we dont know him.
            ProxyDebug.println(
                "Proxy: received a Subscribe request to "
                    + " a user in our domain that was not found, "
                    + " responded 404");
            Response response = messageFactory.createResponse(Response.NOT_FOUND, request);
            if (serverTransaction != null) serverTransaction.sendResponse(response);
            else sipProvider.sendResponse(response);
            return;
          } else {
            ProxyDebug.println(
                "Trying to forward subscribe to "
                    + targetURIList.toString()
                    + "\n"
                    + request.toString());
            requestForwarding.forwardRequest(
                targetURIList, sipProvider, request, serverTransaction, false);
          }
        }
        return;
      }

      /** Received a Notify. TOADD: Check if it match active VirtualSubscriptions and update it */
      if (isPresenceServer() && (request.getMethod().equals(Request.NOTIFY))) {
        System.out.println("Incoming request Notify");

        Response response = messageFactory.createResponse(481, request);
        response.setReasonPhrase("Subscription does not exist");
        if (serverTransaction != null) serverTransaction.sendResponse(response);
        else sipProvider.sendResponse(response);
        ProxyDebug.println("Proxy: received a Notify request. Probably wrong, responded 481");
        return;
      }

      if (isPresenceServer() && (request.getMethod().equalsIgnoreCase("PUBLISH"))) {

        System.out.println("Incoming request Publish");

        ProxyDebug.println("Proxy: received a Publish request.");
        Request clonedRequest = (Request) request.clone();

        if (presenceServer.isStateAgent(clonedRequest)) {
          ProxyDebug.println("PresenceServer.isStateAgent");
        } else {
          ProxyDebug.println("PresenceServer is NOT StateAgent");
        }

        if (presenceServer.isStateAgent(clonedRequest)) {
          presenceServer.processPublishRequest(sipProvider, clonedRequest, serverTransaction);
        } else {
          Response response = messageFactory.createResponse(Response.NOT_FOUND, request);
          if (serverTransaction != null) serverTransaction.sendResponse(response);
          else sipProvider.sendResponse(response);
        }
        return;
      }

      // Forward to next hop but dont reply OK right away for the
      // BYE. Bye is end-to-end not hop by hop!
      if (request.getMethod().equals(Request.BYE)) {

        if (serverTransaction == null) {
          if (ProxyDebug.debug) ProxyDebug.println("Proxy, null server transaction for BYE");
          return;
        }

        /* added code */
        CallID call_id = (CallID) request.getHeader(CallID.CALL_ID);
        String call_id_str = call_id.getCallId();
        long end_time = TimeThreadController.Stop(call_id_str);

        To tou = (To) request.getHeader(ToHeader.NAME);
        From fromu = (From) request.getHeader(FromHeader.NAME);

        String FromUser = fromu.getUserAtHostPort();
        String ToUser = tou.getUserAtHostPort();

        StringBuffer sb = new StringBuffer(FromUser);
        int endsAt = sb.indexOf("@");
        String FromUsername = sb.substring(0, endsAt);
        sb = new StringBuffer(ToUser);
        endsAt = sb.indexOf("@");
        String ToUsername = sb.substring(0, endsAt);
        BillStrategyApply bill = new BillStrategyApply(new StandardBillPolicy());
        long start_time = TimeThreadController.getStartTime();
        java.sql.Timestamp s = new java.sql.Timestamp(start_time);
        System.out.println("START TIME POU BIKE :" + s.toString());
        BigDecimal cost = bill.executeStrategy(1, 2, start_time, end_time);
        ProcessBill.updateCallDB(FromUsername, ToUsername, start_time, end_time, cost);

        /* end of added code */

        Dialog d = serverTransaction.getDialog();
        TransactionsMapping transactionsMapping = (TransactionsMapping) d.getApplicationData();
        Dialog peerDialog = (Dialog) transactionsMapping.getPeerDialog(serverTransaction);
        Request clonedRequest = (Request) request.clone();
        FromHeader from = (FromHeader) clonedRequest.getHeader(FromHeader.NAME);
        from.removeParameter("tag");
        ToHeader to = (ToHeader) clonedRequest.getHeader(ToHeader.NAME);
        to.removeParameter("tag");
        ViaHeader via = this.getStackViaHeader();
        clonedRequest.addHeader(via);
        if (peerDialog.getState() != null) {
          ClientTransaction newct = sipProvider.getNewClientTransaction(clonedRequest);
          transactionsMapping.addMapping(serverTransaction, newct);
          peerDialog.sendRequest(newct);
          return;
        } else {
          // the peer dialog is not yet established so bail out.
          // this is a client error - client is sending BYE
          // before dialog establishment.
          if (ProxyDebug.debug) ProxyDebug.println("Proxy, bad dialog state - BYE dropped");
          return;
        }
      }

      /*
       * If the target set for the request has not been predetermined as
       * described above, this implies that the element is responsible for
       * the domain in the Request-URI, and the element MAY use whatever
       * mechanism it desires to determine where to send the request. ...
       * When accessing the location service constructed by a registrar,
       * the Request-URI MUST first be canonicalized as described in
       * Section 10.3 before being used as an index.
       */
      if (requestURI.isSipURI()) {
        SipURI requestSipURI = (SipURI) requestURI;
        Iterator iterator = requestSipURI.getParameterNames();
        if (ProxyDebug.debug)
          ProxyDebug.println("Proxy, processRequest(), we canonicalized" + " the request-URI");
        while (iterator != null && iterator.hasNext()) {
          String name = (String) iterator.next();
          requestSipURI.removeParameter(name);
        }
      }

      if (registrar.hasRegistration(request)) {

        targetURIList = registrar.getContactsURI(request);

        // We fork only INVITE
        if (targetURIList != null
            && targetURIList.size() > 1
            && !request.getMethod().equals("INVITE")) {
          if (ProxyDebug.debug)
            ProxyDebug.println(
                "Proxy, processRequest(), the request "
                    + " to fork is not an INVITE, so we will process"
                    + " it with the first target as the only target.");
          targetURI = (URI) targetURIList.firstElement();
          targetURIList = new Vector();
          targetURIList.addElement(targetURI);
          // 4. Forward the request statefully to the target:
          requestForwarding.forwardRequest(
              targetURIList, sipProvider, request, serverTransaction, true);
          return;
        }

        if (targetURIList != null && !targetURIList.isEmpty()) {
          if (ProxyDebug.debug)
            ProxyDebug.println(
                "Proxy, processRequest(), the target set"
                    + " is the set of the contacts URI from the "
                    + " location service");

          To to = (To) request.getHeader(ToHeader.NAME);
          From from = (From) request.getHeader(FromHeader.NAME);

          String FromUser = from.getUserAtHostPort();
          String ToUser = to.getUserAtHostPort();

          StringBuffer sb = new StringBuffer(FromUser);
          int endsAt = sb.indexOf("@");
          String FromUsername = sb.substring(0, endsAt);
          sb = new StringBuffer(ToUser);
          endsAt = sb.indexOf("@");
          String ToUsername = sb.substring(0, endsAt);

          if (!block.CheckBlock(FromUsername, ToUsername)) {
            Response response =
                messageFactory.createResponse(Response.TEMPORARILY_UNAVAILABLE, request);
            if (serverTransaction != null) serverTransaction.sendResponse(response);
            else sipProvider.sendResponse(response);
            return;
          }
          /*
           * // ECE355 Changes - Aug. 2005. // Call registry service,
           * get response (uri - wsdl). // if response is not null
           * then // do our staff // send to caller decline message by
           * building a decline msg // and attach wsdl uri in the
           * message body // else .. continue the logic below ...
           *
           *
           * // Lets assume that wsdl_string contains the message with
           * all the // service names and uri's for each service in
           * the required format
           *
           * // Query for web services for the receiver of INVITE //
           * Use WebServices class to get services for org
           *
           * String messageBody = "" ; WebServicesQuery wsq = null ;
           * wsq = WebServicesQuery.getInstance();
           *
           * // Get services info for receiver // A receiver is
           * represented as an organization in the Service Registry
           *
           * To to = (To)request.getHeader(ToHeader.NAME); String
           * toAddress = to.getUserAtHostPort();
           *
           * // Remove all characters after the @ sign from To address
           * StringBuffer sb = new StringBuffer(toAddress); int endsAt
           * = sb.indexOf("@"); String orgNamePattern =
           * sb.substring(0, endsAt);
           *
           *
           * Collection serviceInfoColl =
           * wsq.findServicesForOrg(orgNamePattern);
           *
           * // If services are found for this receiver (Org), build
           * DECLINE message and // send to client if (serviceInfoColl
           * != null) { if (serviceInfoColl.size()!= 0 ){
           * System.out.println("Found " + serviceInfoColl.size() +
           * " services for o rg " + orgNamePattern) ; // Build
           * message body for DECLINE message with Service Info
           * messageBody = serviceInfoColl.size()+ " -- " ;
           *
           * Iterator servIter = serviceInfoColl.iterator(); while
           * (servIter.hasNext()) { ServiceInfo servInfo =
           * (ServiceInfo)servIter.next(); messageBody = messageBody +
           * servInfo.getDescription()+ " " + servInfo.getWsdluri() +
           * " " + servInfo.getEndPoint()+ " -- ";
           *
           *
           * System.out.println("Name: " + servInfo.getName()) ;
           * System.out.println("Providing Organization: " +
           * servInfo.getProvidingOrganization()) ;
           * System.out.println("Description: " +
           * servInfo.getDescription()) ;
           * System.out.println("Service End Point " +
           * servInfo.getEndPoint()) ; System.out.println("wsdl wri "
           * + servInfo.getWsdluri()) ;
           * System.out.println("---------------------------------");
           *
           *
           *
           * }
           *
           * System.out.println("ServiceInfo - Message Body  " +
           * messageBody) ;
           *
           * // Build and send DECLINE message with web service info
           *
           * ContentTypeHeader contentTypeHeader = new ContentType(
           * "text", "plain");
           *
           * Response response = messageFactory.createResponse(
           * Response.DECLINE, request, contentTypeHeader,
           * messageBody);
           *
           *
           *
           * if (serverTransaction != null)
           * serverTransaction.sendResponse(response); else
           * sipProvider.sendResponse(response); return; } else
           * System.out.println("There are no services for org " +
           * orgNamePattern) ;
           *
           * }
           *
           * // End of ECE355 change
           */

          // 4. Forward the request statefully to each target Section
          // 16.6.:
          requestForwarding.forwardRequest(
              targetURIList, sipProvider, request, serverTransaction, true);

          return;
        } else {
          // Let's continue and try the default hop.
        }
      }

      // The registrar cannot help to decide the targets, so let's use
      // our router: the default hop!
      ProxyDebug.println(
          "Proxy, processRequest(), the registrar cannot help"
              + " to decide the targets, so let's use our router: the default hop");
      Router router = sipStack.getRouter();
      if (router != null) {
        ProxyHop hop = (ProxyHop) router.getOutboundProxy();
        if (hop != null) {
          if (ProxyDebug.debug)
            ProxyDebug.println(
                "Proxy, processRequest(), the target set" + " is the defaut hop: outbound proxy");

          // Bug fix contributed by Joe Provino
          String user = null;

          if (requestURI.isSipURI()) {
            SipURI requestSipURI = (SipURI) requestURI;
            user = requestSipURI.getUser();
          }

          SipURI hopURI = addressFactory.createSipURI(user, hop.getHost());
          hopURI.setTransportParam(hop.getTransport());
          hopURI.setPort(hop.getPort());
          targetURI = hopURI;
          targetURIList.addElement(targetURI);

          // 4. Forward the request statelessly to each target Section
          // 16.6.:
          requestForwarding.forwardRequest(
              targetURIList, sipProvider, request, serverTransaction, false);

          return;
        }
      }

      /*
       * If the target set remains empty after applying all of the above,
       * the proxy MUST return an error response, which SHOULD be the 480
       * (Temporarily Unavailable) response.
       */
      Response response = messageFactory.createResponse(Response.TEMPORARILY_UNAVAILABLE, request);
      if (serverTransaction != null) serverTransaction.sendResponse(response);
      else sipProvider.sendResponse(response);

      if (ProxyDebug.debug)
        ProxyDebug.println(
            "Proxy, processRequest(), unable to set "
                + " the targets, 480 (Temporarily Unavailable) replied:\n"
                + response.toString());

    } catch (Exception ex) {
      try {
        if (ProxyDebug.debug) {
          ProxyDebug.println("Proxy, processRequest(), internal error, " + "exception raised:");
          ProxyDebug.logException(ex);
          ex.printStackTrace();
        }

        // This is an internal error:
        // Let's return a 500 SERVER_INTERNAL_ERROR
        Response response = messageFactory.createResponse(Response.SERVER_INTERNAL_ERROR, request);
        if (serverTransaction != null) serverTransaction.sendResponse(response);
        else sipProvider.sendResponse(response);

        if (ProxyDebug.debug)
          ProxyDebug.println(
              "Proxy, processRequest(),"
                  + " 500 SERVER_INTERNAL_ERROR replied:\n"
                  + response.toString());
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
  public void processMessage(Request request, ServerTransaction serverTransaction) {
    try {
      SipProvider sipProvider = imUA.getSipProvider();
      MessageFactory messageFactory = imUA.getMessageFactory();
      HeaderFactory headerFactory = imUA.getHeaderFactory();
      AddressFactory addressFactory = imUA.getAddressFactory();

      InstantMessagingGUI instantMessagingGUI = imUA.getInstantMessagingGUI();
      ListenerInstantMessaging listenerInstantMessaging =
          instantMessagingGUI.getListenerInstantMessaging();
      ChatSessionManager chatSessionManager = listenerInstantMessaging.getChatSessionManager();
      ChatSession chatSession = null;
      String fromURL = IMUtilities.getKey(request, "From");
      if (chatSessionManager.hasAlreadyChatSession(fromURL))
        chatSession = chatSessionManager.getChatSession(fromURL);
      else chatSession = chatSessionManager.createChatSession(fromURL);

      DebugIM.println("IMMessageProcessing, processMEssage(), ChatSession:" + chatSession);
      DebugIM.println("Processing MESSAGE in progress...");

      // Send an OK
      Response response = messageFactory.createResponse(Response.OK, request);
      // Contact header:
      SipURI sipURI = addressFactory.createSipURI(null, imUA.getIMAddress());
      sipURI.setPort(imUA.getIMPort());
      sipURI.setTransportParam(imUA.getIMProtocol());
      Address contactAddress = addressFactory.createAddress(sipURI);
      ContactHeader contactHeader = headerFactory.createContactHeader(contactAddress);
      response.setHeader(contactHeader);
      ToHeader toHeader = (ToHeader) response.getHeader(ToHeader.NAME);
      if (toHeader.getTag() == null) {
        // It is the first message without a TO tag
        toHeader.setTag(new Integer((int) (Math.random() * 10000)).toString());
      }

      if (chatSession.isEstablishedSession()) {
        DebugIM.println("The Session already exists");
        serverTransaction.sendResponse(response);
        DebugIM.println("OK replied to the MESSAGE:\n" + response.toString());
      } else {
        DebugIM.println("The Session does not exists yet. ");
        serverTransaction.sendResponse(response);
        DebugIM.println("OK replied to the MESSAGE:\n" + response.toString());

        Dialog dialog = serverTransaction.getDialog();
        if (dialog == null) {
          DebugIM.println("ERROR, IMProcessing, processMessage(), the dialog is null");
          return;
        }
        // We need to store the dialog:
        chatSession.setDialog(dialog);
        chatSession.setEstablishedSession(true);
        DebugIM.println("The DIALOG object has been stored in the ChatSession");
      }

      Object content = request.getContent();
      String text = null;
      if (content instanceof String) text = (String) content;
      else if (content instanceof byte[]) {
        text = new String((byte[]) content);
      } else {
      }
      if (text != null) {
        chatSession.displayRemoteText(text);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  public void processSubscribe(Request request, ServerTransaction serverTransaction) {
    logger.debug("Processing SUBSCRIBE in progress ");
    try {

      MessageFactory messageFactory = imUA.getMessageFactory();
      HeaderFactory headerFactory = imUA.getHeaderFactory();
      AddressFactory addressFactory = imUA.getAddressFactory();
      Dialog dialog = serverTransaction.getDialog();

      // ********** Terminating subscriptions **********
      ExpiresHeader expiresHeader = (ExpiresHeader) request.getHeader(ExpiresHeader.NAME);
      if (expiresHeader != null && expiresHeader.getExpires() == 0) {
        if (dialog != null) {
          // Terminating an existing subscription
          Response response = messageFactory.createResponse(Response.OK, request);
          serverTransaction.sendResponse(response);
          IMNotifyProcessing imNotifyProcessing = imUA.getIMNotifyProcessing();
          imNotifyProcessing.sendNotify(response, null, dialog);
          return;
        } else {
          // Terminating an non existing subscription
          Response response =
              messageFactory.createResponse(Response.CALL_OR_TRANSACTION_DOES_NOT_EXIST, request);
          serverTransaction.sendResponse(response);
          return;
        }
      }

      // ********** Non-terminating subscriptions ************

      // send a 202 Accepted while waiting for authorization from user
      Response response = messageFactory.createResponse(Response.ACCEPTED, request);
      // Tag:
      ToHeader toHeader = (ToHeader) response.getHeader(ToHeader.NAME);
      if (toHeader.getTag() == null)
        toHeader.setTag(new Integer((int) (Math.random() * 10000)).toString());
      serverTransaction.sendResponse(response);
      logger.debug(response.toString());

      // We have to ask the user to authorize the guy to be in his buddy
      // list
      String presentityURL = IMUtilities.getKey(request, "From");
      SipProvider sipProvider = imUA.getSipProvider();
      InstantMessagingGUI imGUI = imUA.getInstantMessagingGUI();
      boolean authorization = imGUI.getAuthorizationForBuddy(presentityURL);
      if (authorization) {
        logger.debug(
            "DEBUG: SubscribeProcessing, processSubscribe(), " + " Response 202 Accepted sent.");

        // We have to create or update the subscriber!
        PresenceManager presenceManager = imUA.getPresenceManager();
        String subscriberURL = IMUtilities.getKey(request, "From");

        if (dialog != null) presenceManager.addSubscriber(subscriberURL, response, dialog);
        else {
          logger.debug(
              "ERROR, IMSubscribeProcessing, processSubscribe(), the"
                  + " dialog for the SUBSCRIBE we received is null!!! No subscriber added....");
          return;
        }

        // Let's see if this buddy is in our buddy list
        // if not let's ask to add him!
        BuddyList buddyList = imGUI.getBuddyList();
        ListenerInstantMessaging listenerIM = imGUI.getListenerInstantMessaging();
        if (!buddyList.hasBuddy(subscriberURL)) {
          // Let's ask:
          listenerIM.addContact(subscriberURL);
        }

        /** ********************** send NOTIFY ************************* */
        // We send a NOTIFY for any of our status but offline
        String localStatus = listenerIM.getLocalStatus();
        if (!localStatus.equals("offline")) {
          IMNotifyProcessing imNotifyProcessing = imUA.getIMNotifyProcessing();
          Subscriber subscriber = presenceManager.getSubscriber(subscriberURL);
          // Response okSent=subscriber.getOkSent();

          subscriberURL = subscriber.getSubscriberName();

          String contactAddress = imUA.getIMAddress() + ":" + imUA.getIMPort();

          String subStatus = listenerIM.getLocalStatus();
          String status = null;
          if (subStatus.equals("offline")) status = "closed";
          else status = "open";
          String xmlBody =
              imNotifyProcessing.xmlPidfParser.createXMLBody(
                  status, subStatus, subscriberURL, contactAddress);
          imNotifyProcessing.sendNotify(response, xmlBody, dialog);
        }
      } else {
        // User did not authorize subscription. Terminate it!
        logger.debug(
            "DEBUG, IMSubsribeProcessing, processSubscribe(), " + " Subscription declined!");
        logger.debug(
            "DEBUG, IMSubsribeProcessing, processSubscribe(), "
                + " Sending a Notify with Subscribe-state=terminated");

        IMNotifyProcessing imNotifyProcessing = imUA.getIMNotifyProcessing();
        if (dialog != null) {
          imNotifyProcessing.sendNotify(response, null, dialog);
          logger.debug(
              "DEBUG, IMSubsribeProcessing, processSubscribe(), "
                  + " Sending a Notify with Subscribe-state=terminated");
        } else {
          logger.debug(
              "ERROR, IMSubscribeProcessing, processSubscribe(), the"
                  + " dialog for the SUBSCRIBE we received is null!!! \n"
                  + "   No terminating Notify sent");
        }
        imNotifyProcessing.sendNotify(response, null, dialog);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  public void sendSubscribe(String localURL, String buddyURI, boolean EXPIRED) {
    try {
      logger.debug("Sending SUBSCRIBE in progress to the buddy: " + buddyURI);
      int proxyPort = imUA.getProxyPort();
      String proxyAddress = imUA.getProxyAddress();
      String imProtocol = imUA.getIMProtocol();
      SipStack sipStack = imUA.getSipStack();
      SipProvider sipProvider = imUA.getSipProvider();
      MessageFactory messageFactory = imUA.getMessageFactory();
      HeaderFactory headerFactory = imUA.getHeaderFactory();
      AddressFactory addressFactory = imUA.getAddressFactory();

      // Request-URI:
      // URI requestURI=addressFactory.createURI(buddyURI);
      SipURI requestURI = addressFactory.createSipURI(null, proxyAddress);
      requestURI.setPort(proxyPort);
      requestURI.setTransportParam(imProtocol);

      // Call-Id:
      CallIdHeader callIdHeader = null;

      // CSeq:
      CSeqHeader cseqHeader = null;

      // To header:
      ToHeader toHeader = null;

      // From Header:
      FromHeader fromHeader = null;

      // Via header
      String branchId = Utils.generateBranchId();
      ViaHeader viaHeader =
          headerFactory.createViaHeader(
              imUA.getIMAddress(), imUA.getIMPort(), imProtocol, branchId);
      Vector viaList = new Vector();
      viaList.addElement(viaHeader);

      PresenceManager presenceManager = imUA.getPresenceManager();
      Presentity presentity = presenceManager.getPresentity(buddyURI);
      Dialog dialog = null;
      if (presentity != null) dialog = presentity.getDialog();

      if (dialog != null) {

        // We have to remove the subscriber and the Presentity related
        // with this Buddy...
        presenceManager.removePresentity(buddyURI);
        Subscriber subscriber = presenceManager.getSubscriber(buddyURI);
        if (subscriber == null) {
          // It means that the guy does not have us in his buddy list
          // nothing to do!!!
        } else {
          presenceManager.removeSubscriber(buddyURI);
        }

        Address localAddress = dialog.getLocalParty();
        Address remoteAddress = dialog.getRemoteParty();

        fromHeader = headerFactory.createFromHeader(localAddress, dialog.getLocalTag());
        toHeader = headerFactory.createToHeader(remoteAddress, dialog.getRemoteTag());

        long cseq = dialog.getLocalSeqNumber();
        cseqHeader = headerFactory.createCSeqHeader(cseq, "MESSAGE");

        callIdHeader = dialog.getCallId();
      } else {
        String localTag = Utils.generateTag();

        Address toAddress = addressFactory.createAddress(buddyURI);
        Address fromAddress = addressFactory.createAddress(localURL);

        fromHeader = headerFactory.createFromHeader(fromAddress, localTag);
        toHeader = headerFactory.createToHeader(toAddress, null);

        // CSeq:
        cseqHeader = headerFactory.createCSeqHeader(1L, "SUBSCRIBE");

        callIdCounter++;
        // Call-ID:
        callIdHeader =
            (CallIdHeader)
                headerFactory.createCallIdHeader("nist-sip-im-subscribe-callId" + callIdCounter);
      }

      // MaxForwards header:
      MaxForwardsHeader maxForwardsHeader = headerFactory.createMaxForwardsHeader(70);

      Request request =
          messageFactory.createRequest(
              requestURI,
              "SUBSCRIBE",
              callIdHeader,
              cseqHeader,
              fromHeader,
              toHeader,
              viaList,
              maxForwardsHeader);

      RouteHeader rh = this.imUA.getRouteToProxy();
      request.setHeader(rh);

      // Contact header:
      SipURI sipURI = addressFactory.createSipURI(null, imUA.getIMAddress());
      sipURI.setPort(imUA.getIMPort());
      sipURI.setTransportParam(imUA.getIMProtocol());
      Address contactAddress = addressFactory.createAddress(sipURI);
      ContactHeader contactHeader = headerFactory.createContactHeader(contactAddress);
      request.setHeader(contactHeader);

      ExpiresHeader expiresHeader = null;
      if (EXPIRED) {
        expiresHeader = headerFactory.createExpiresHeader(0);
      } else {
        expiresHeader = headerFactory.createExpiresHeader(presenceManager.getExpiresTime());
      }
      request.setHeader(expiresHeader);

      // WE have to add a new Header: "Event"
      Header eventHeader = headerFactory.createHeader("Event", "presence");
      request.setHeader(eventHeader);

      // Add Acceptw Header
      Header acceptHeader = headerFactory.createHeader("Accept", "application/pidf+xml");
      request.setHeader(acceptHeader);

      // ProxyAuthorization header if not null:
      ProxyAuthorizationHeader proxyAuthHeader = imUA.getProxyAuthorizationHeader();
      if (proxyAuthHeader != null) request.setHeader(proxyAuthHeader);

      ClientTransaction clientTransaction = sipProvider.getNewClientTransaction(request);

      if (dialog != null) {
        dialog.sendRequest(clientTransaction);
      } else {
        clientTransaction.sendRequest();
      }

      logger.debug("IMSubscribeProcessing, sendSubscribe(), SUBSCRIBE sent:\n" + request);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  public void sendPublish(String localURI, String status) {
    try {
      logger.debug("Sending PUBLISH in progress");
      int proxyPort = imUA.getProxyPort();
      String proxyAddress = imUA.getProxyAddress();
      String imProtocol = imUA.getIMProtocol();
      SipStack sipStack = imUA.getSipStack();
      SipProvider sipProvider = imUA.getSipProvider();
      MessageFactory messageFactory = imUA.getMessageFactory();
      HeaderFactory headerFactory = imUA.getHeaderFactory();
      AddressFactory addressFactory = imUA.getAddressFactory();

      // Request-URI:
      if (localURI.startsWith("sip:")) localURI = localURI.substring(4, localURI.length());
      SipURI requestURI = addressFactory.createSipURI(null, localURI);
      requestURI.setPort(proxyPort);
      requestURI.setTransportParam(imProtocol);

      // Via header
      String branchId = Utils.generateBranchId();
      ViaHeader viaHeader =
          headerFactory.createViaHeader(
              imUA.getIMAddress(), imUA.getIMPort(), imProtocol, branchId);
      Vector viaList = new Vector();
      viaList.addElement(viaHeader);

      // To header:
      System.out.println("XXX localURI=" + localURI);
      Address localAddress = addressFactory.createAddress("sip:" + localURI);
      ToHeader toHeader = headerFactory.createToHeader(localAddress, null);

      // From header:
      String localTag = Utils.generateTag();
      FromHeader fromHeader = headerFactory.createFromHeader(localAddress, localTag);

      // Call-ID:
      CallIdHeader callIdHeader = headerFactory.createCallIdHeader(callIdCounter + localURI);

      // CSeq:
      CSeqHeader cseqHeader = headerFactory.createCSeqHeader(1L, "PUBLISH");

      // MaxForwards header:
      MaxForwardsHeader maxForwardsHeader = headerFactory.createMaxForwardsHeader(70);

      // Create Request
      Request request =
          messageFactory.createRequest(
              requestURI,
              "PUBLISH",
              callIdHeader,
              cseqHeader,
              fromHeader,
              toHeader,
              viaList,
              maxForwardsHeader);

      // Expires header: (none, let server chose)

      // Event header:
      Header header = headerFactory.createHeader("Event", "presence");
      request.setHeader(header);

      RouteHeader routeHeader = this.imUA.getRouteToProxy();

      request.setHeader(routeHeader);

      // Content and Content-Type header:
      String basic;
      if (status.equals("offline")) basic = "closed";
      else basic = "open";

      String content =
          "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
              + "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\""
              + " entity=\""
              + localURI
              + "\">\n"
              + " <tuple id=\""
              + entity
              + "\">\n"
              + "  <status>\n"
              + "   <basic>"
              + basic
              + "</basic>\n"
              + "  </status>\n"
              + "  <note>"
              + status
              + "</note>\n"
              + " </tuple>\n"
              + "</presence>";

      ContentTypeHeader contentTypeHeader =
          headerFactory.createContentTypeHeader("application", "pidf+xml");
      request.setContent(content, contentTypeHeader);

      // Content-Length header:
      ContentLengthHeader contentLengthHeader =
          headerFactory.createContentLengthHeader(content.length());
      request.setContentLength(contentLengthHeader);

      // Send request
      ClientTransaction clientTransaction = sipProvider.getNewClientTransaction(request);
      clientTransaction.sendRequest();

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
    public void init() {
      SipFactory sipFactory = null;
      sipStack = null;
      sipFactory = SipFactory.getInstance();
      sipFactory.setPathName("gov.nist");
      Properties properties = new Properties();
      // If you want to try TCP transport change the following to
      String transport = "udp";
      String peerHostPort = "127.0.0.1:5070";
      properties.setProperty("javax.sip.OUTBOUND_PROXY", peerHostPort + "/" + transport);
      // If you want to use UDP then uncomment this.
      properties.setProperty("javax.sip.STACK_NAME", "shootist");

      // The following properties are specific to nist-sip
      // and are not necessarily part of any other jain-sip
      // implementation.
      // You can set a max message size for tcp transport to
      // guard against denial of service attack.
      properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", "shootistdebug.txt");
      properties.setProperty("gov.nist.javax.sip.SERVER_LOG", "shootistlog.txt");

      // Drop the client connection after we are done with the transaction.
      properties.setProperty("gov.nist.javax.sip.CACHE_CLIENT_CONNECTIONS", "false");
      // Set to 0 (or NONE) in your production code for max speed.
      // You need 16 (or TRACE) for logging traces. 32 (or DEBUG) for debug + traces.
      // Your code will limp at 32 but it is best for debugging.
      properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "DEBUG");
      if (System.getProperty("enableNIO") != null
          && System.getProperty("enableNIO").equalsIgnoreCase("true")) {
        properties.setProperty(
            "gov.nist.javax.sip.MESSAGE_PROCESSOR_FACTORY",
            NioMessageProcessorFactory.class.getName());
      }
      try {
        // Create SipStack object
        sipStack = sipFactory.createSipStack(properties);
        System.out.println("createSipStack " + sipStack);
      } catch (PeerUnavailableException e) {
        // could not find
        // gov.nist.jain.protocol.ip.sip.SipStackImpl
        // in the classpath
        e.printStackTrace();
        System.err.println(e.getMessage());
        fail("Problem with setup");
      }

      try {
        headerFactory = sipFactory.createHeaderFactory();
        addressFactory = sipFactory.createAddressFactory();
        messageFactory = sipFactory.createMessageFactory();
        udpListeningPoint = sipStack.createListeningPoint("127.0.0.1", 5060, "udp");
        sipProvider = sipStack.createSipProvider(udpListeningPoint);
        Shootist listener = this;
        sipProvider.addSipListener(listener);

        String fromName = "BigGuy";
        String fromSipAddress = "here.com";
        String fromDisplayName = "The Master Blaster";

        String toSipAddress = "there.com";
        String toUser = "******";
        String toDisplayName = "The Little Blister";

        // create >From Header
        SipURI fromAddress = addressFactory.createSipURI(fromName, fromSipAddress);

        Address fromNameAddress = addressFactory.createAddress(fromAddress);
        fromNameAddress.setDisplayName(fromDisplayName);
        FromHeader fromHeader = headerFactory.createFromHeader(fromNameAddress, "12345");

        // create To Header
        SipURI toAddress = addressFactory.createSipURI(toUser, toSipAddress);
        Address toNameAddress = addressFactory.createAddress(toAddress);
        toNameAddress.setDisplayName(toDisplayName);
        ToHeader toHeader = headerFactory.createToHeader(toNameAddress, null);

        // create Request URI
        SipURI requestURI = addressFactory.createSipURI(toUser, peerHostPort);

        // Create ViaHeaders

        ArrayList viaHeaders = new ArrayList();
        String ipAddress = udpListeningPoint.getIPAddress();
        ViaHeader viaHeader =
            headerFactory.createViaHeader(
                ipAddress, sipProvider.getListeningPoint(transport).getPort(), transport, null);

        // add via headers
        viaHeaders.add(viaHeader);

        // Create ContentTypeHeader
        ContentTypeHeader contentTypeHeader =
            headerFactory.createContentTypeHeader("application", "sdp");

        // Create a new CallId header
        CallIdHeader callIdHeader = sipProvider.getNewCallId();

        // Create a new Cseq header
        CSeqHeader cSeqHeader = headerFactory.createCSeqHeader(1L, Request.INVITE);

        // Create a new MaxForwardsHeader
        MaxForwardsHeader maxForwards = headerFactory.createMaxForwardsHeader(70);

        // Create the request.
        Request request =
            messageFactory.createRequest(
                requestURI,
                Request.INVITE,
                callIdHeader,
                cSeqHeader,
                fromHeader,
                toHeader,
                viaHeaders,
                maxForwards);
        // Create contact headers
        String host = "127.0.0.1";

        SipURI contactUrl = addressFactory.createSipURI(fromName, host);
        contactUrl.setPort(udpListeningPoint.getPort());
        contactUrl.setLrParam();

        // Create the contact name address.
        SipURI contactURI = addressFactory.createSipURI(fromName, host);
        contactURI.setPort(sipProvider.getListeningPoint(transport).getPort());

        Address contactAddress = addressFactory.createAddress(contactURI);

        // Add the contact address.
        contactAddress.setDisplayName(fromName);

        contactHeader = headerFactory.createContactHeader(contactAddress);
        request.addHeader(contactHeader);

        // You can add extension headers of your own making
        // to the outgoing SIP request.
        // Add the extension header.
        Header extensionHeader = headerFactory.createHeader("My-Header", "my header value");
        request.addHeader(extensionHeader);

        String sdpData =
            "v=0\r\n"
                + "o=4855 13760799956958020 13760799956958020"
                + " IN IP4  129.6.55.78\r\n"
                + "s=mysession session\r\n"
                + "p=+46 8 52018010\r\n"
                + "c=IN IP4  129.6.55.78\r\n"
                + "t=0 0\r\n"
                + "m=audio 6022 RTP/AVP 0 4 18\r\n"
                + "a=rtpmap:0 PCMU/8000\r\n"
                + "a=rtpmap:4 G723/8000\r\n"
                + "a=rtpmap:18 G729A/8000\r\n"
                + "a=ptime:20\r\n";
        byte[] contents = sdpData.getBytes();

        request.setContent(contents, contentTypeHeader);
        // You can add as many extension headers as you
        // want.

        extensionHeader = headerFactory.createHeader("My-Other-Header", "my new header value ");
        request.addHeader(extensionHeader);

        Header callInfoHeader =
            headerFactory.createHeader("Call-Info", "<http://www.antd.nist.gov>");
        request.addHeader(callInfoHeader);

        // Create the client transaction.
        ClientTransaction inviteTid = sipProvider.getNewClientTransaction(request);

        // send the request out.
        inviteTid.sendRequest();

        dialog = inviteTid.getDialog();

      } catch (Exception ex) {
        fail("cannot create or send initial invite");
      }
    }
  public void sendMessage(
      String localSipURL, String remoteSipURL, String text, ChatSession chatSession) {
    try {
      DebugIM.println("IMMessageProcessing, ChatSession:" + chatSession);
      DebugIM.println("Sending a MESSAGE in progress to " + remoteSipURL);

      SipProvider sipProvider = imUA.getSipProvider();
      MessageFactory messageFactory = imUA.getMessageFactory();
      HeaderFactory headerFactory = imUA.getHeaderFactory();
      AddressFactory addressFactory = imUA.getAddressFactory();

      String proxyAddress = imUA.getProxyAddress();
      SipURI requestURI = null;
      if (proxyAddress != null) {
        requestURI = addressFactory.createSipURI(null, proxyAddress);
        requestURI.setPort(imUA.getProxyPort());
        requestURI.setTransportParam(imUA.getIMProtocol());
      } else {
        requestURI = (SipURI) addressFactory.createURI(remoteSipURL);
        requestURI.setTransportParam(imUA.getIMProtocol());
      }

      // Call-Id:
      CallIdHeader callIdHeader = null;

      // CSeq:
      CSeqHeader cseqHeader = null;

      // To header:
      ToHeader toHeader = null;

      // From Header:
      FromHeader fromHeader = null;

      //  Via header
      String branchId = Utils.generateBranchId();
      ViaHeader viaHeader =
          headerFactory.createViaHeader(
              imUA.getIMAddress(), imUA.getIMPort(), imUA.getIMProtocol(), branchId);
      Vector viaList = new Vector();
      viaList.addElement(viaHeader);

      // MaxForwards header:
      MaxForwardsHeader maxForwardsHeader = headerFactory.createMaxForwardsHeader(70);
      Dialog dialog = chatSession.getDialog();
      if (chatSession.isEstablishedSession()) {
        DebugIM.println(
            "DEBUG, IMMessageProcessing, sendMessage(), we get"
                + " the DIALOG from the ChatSession");

        Address localAddress = dialog.getLocalParty();
        Address remoteAddress = dialog.getRemoteParty();
        //  if (dialog.isServer()) {
        // We received the first MESSAGE
        fromHeader = headerFactory.createFromHeader(localAddress, dialog.getLocalTag());
        toHeader = headerFactory.createToHeader(remoteAddress, dialog.getRemoteTag());
        //  }
        //  else {

        //   }
        int cseq = dialog.getLocalSequenceNumber();
        DebugIM.println("the cseq number got from the dialog:" + cseq);
        cseqHeader = headerFactory.createCSeqHeader(cseq, "MESSAGE");

        callIdHeader = dialog.getCallId();

      } else {
        DebugIM.println(
            "DEBUG, IMMessageProcessing, sendMessage(), the "
                + " session has not been established yet! We create the first message");

        // To header:
        Address toAddress = addressFactory.createAddress(remoteSipURL);

        // From Header:
        Address fromAddress = addressFactory.createAddress(localSipURL);

        // We have to initiate the dialog: means to create the From tag
        String localTag = Utils.generateTag();
        fromHeader = headerFactory.createFromHeader(fromAddress, localTag);
        toHeader = headerFactory.createToHeader(toAddress, null);

        // CSeq:
        cseqHeader = headerFactory.createCSeqHeader(1, "MESSAGE");

        // Call-ID:
        callIdCounter++;
        callIdHeader =
            (CallIdHeader)
                headerFactory.createCallIdHeader("nist-sip-im-message-callId" + callIdCounter);
      }

      // Content-Type:
      ContentTypeHeader contentTypeHeader = headerFactory.createContentTypeHeader("text", "plain");
      contentTypeHeader.setParameter("charset", "UTF-8");

      Request request =
          messageFactory.createRequest(
              requestURI,
              "MESSAGE",
              callIdHeader,
              cseqHeader,
              fromHeader,
              toHeader,
              viaList,
              maxForwardsHeader,
              contentTypeHeader,
              text);

      // Contact header:
      SipURI sipURI = addressFactory.createSipURI(null, imUA.getIMAddress());
      sipURI.setPort(imUA.getIMPort());
      sipURI.setTransportParam(imUA.getIMProtocol());
      Address contactAddress = addressFactory.createAddress(sipURI);
      ContactHeader contactHeader = headerFactory.createContactHeader(contactAddress);
      request.setHeader(contactHeader);

      // ProxyAuthorization header if not null:
      ProxyAuthorizationHeader proxyAuthHeader = imUA.getProxyAuthorizationHeader();
      if (proxyAuthHeader != null) request.setHeader(proxyAuthHeader);

      ClientTransaction clientTransaction = sipProvider.getNewClientTransaction(request);

      if (chatSession.isEstablishedSession()) {
        dialog.sendRequest(clientTransaction);
        DebugIM.println(
            "IMessageProcessing, sendMessage(), MESSAGE sent" + " using the dialog:\n" + request);
      } else {
        clientTransaction.sendRequest();
        DebugIM.println(
            "IMessageProcessing, sendMessage(), MESSAGE sent"
                + " using a new client transaction:\n"
                + request);
      }

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }