Beispiel #1
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("b2bua: got an Invite sending Trying");
      ServerTransaction st = requestEvent.getServerTransaction();
      if (st == null) {
        st = sipProvider.getNewServerTransaction(request);
      }
      Dialog dialog = st.getDialog();

      ToHeader to = (ToHeader) request.getHeader(ToHeader.NAME);
      SipURI toUri = (SipURI) to.getAddress().getURI();

      SipURI target = registrar.get(toUri.getUser());

      if (target == null) {
        System.out.println("User " + toUri + " is not registered.");
        throw new RuntimeException("User not registered " + toUri);
      } else {
        ClientTransaction otherLeg = call(target);
        otherLeg.setApplicationData(st);
        st.setApplicationData(otherLeg);
        dialog.setApplicationData(otherLeg.getDialog());
        otherLeg.getDialog().setApplicationData(dialog);
      }

    } 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 {
      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);
    }
  }
Beispiel #3
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);
    }
  }
Beispiel #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);
    }
  }
Beispiel #5
0
  /** Process the invite request. */
  public void processInvite(RequestEvent requestEvent, ServerTransaction serverTransaction) {
    SipProvider sipProvider = (SipProvider) requestEvent.getSource();
    Request request = requestEvent.getRequest();
    try {
      logger.info("shootme: got an Invite sending Trying");
      // logger.info("shootme: " + request);

      ServerTransaction st = requestEvent.getServerTransaction();

      if (st == null) {
        logger.info("null server tx -- getting a new one");
        st = sipProvider.getNewServerTransaction(request);
      }

      logger.info("getNewServerTransaction : " + st);

      String txId = ((ViaHeader) request.getHeader(ViaHeader.NAME)).getBranch();
      this.serverTxTable.put(txId, st);

      // Create the 100 Trying response.
      Response response = protocolObjects.messageFactory.createResponse(Response.TRYING, request);
      ListeningPoint lp = sipProvider.getListeningPoint(protocolObjects.transport);
      int myPort = lp.getPort();

      Address address =
          protocolObjects.addressFactory.createAddress(
              "Shootme <sip:" + myAddress + ":" + myPort + ">");

      // Add a random sleep to stagger the two OK's for the benifit of implementations
      // that may not be too good about handling re-entrancy.
      int timeToSleep = (int) (Math.random() * 1000);

      Thread.sleep(timeToSleep);

      st.sendResponse(response);

      Response ringingResponse =
          protocolObjects.messageFactory.createResponse(Response.RINGING, request);
      ContactHeader contactHeader = protocolObjects.headerFactory.createContactHeader(address);
      response.addHeader(contactHeader);
      ToHeader toHeader = (ToHeader) ringingResponse.getHeader(ToHeader.NAME);
      String toTag =
          actAsNonRFC3261UAS ? null : new Integer((int) (Math.random() * 10000)).toString();
      if (!actAsNonRFC3261UAS) toHeader.setTag(toTag); // Application is supposed to set.
      ringingResponse.addHeader(contactHeader);
      st.sendResponse(ringingResponse);
      Dialog dialog = st.getDialog();
      dialog.setApplicationData(st);

      this.inviteSeen = true;

      new Timer().schedule(new MyTimerTask(requestEvent, st /*,toTag*/), 1000);
    } catch (Exception ex) {
      ex.printStackTrace();
      System.exit(0);
    }
  }
  /**
   * Safely returns the transaction from the event if already exists. If not a new transaction is
   * created.
   *
   * @param event the request event
   * @return the server transaction
   * @throws javax.sip.TransactionAlreadyExistsException if transaction exists
   * @throws javax.sip.TransactionUnavailableException if unavailable
   */
  public static ServerTransaction getOrCreateServerTransaction(RequestEvent event)
      throws TransactionAlreadyExistsException, TransactionUnavailableException {
    ServerTransaction serverTransaction = event.getServerTransaction();

    if (serverTransaction == null) {
      SipProvider jainSipProvider = (SipProvider) event.getSource();

      serverTransaction = jainSipProvider.getNewServerTransaction(event.getRequest());
    }
    return serverTransaction;
  }
  public void processRequest(RequestEvent requestReceivedEvent) {
    Request request = requestReceivedEvent.getRequest();
    ServerTransaction serverTransactionId = requestReceivedEvent.getServerTransaction();
    String viaBranch =
        ((ViaHeader) (request.getHeaders(ViaHeader.NAME).next())).getParameter("branch");
    LOG.debug("Request: {}", request.getMethod());
    LOG.debug("Server Transaction Id: {}", serverTransactionId);
    LOG.debug("Received From Branch: {}", viaBranch);

    if (request.getMethod().equals(Request.NOTIFY)) {
      processNotify(requestReceivedEvent, serverTransactionId);
    }
  }
Beispiel #8
0
  public void processRequest(RequestEvent requestReceivedEvent) {
    Request request = requestReceivedEvent.getRequest();
    ServerTransaction serverTransactionId = requestReceivedEvent.getServerTransaction();

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

    // We are the UAC so the only request we get is the BYE.
    if (request.getMethod().equals(Request.BYE)) processBye(request, serverTransactionId);
  }
    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);
      }
    }
 /**
  * Send a simple invite request from the RI and check whether it is properly delivered by the TI
  * SipProvider
  */
 public void testReceiveRequest() {
   try {
     // create an empty invite request.
     Request invite = createRiInviteRequest(null, null, null);
     RequestEvent receivedRequestEvent = null;
     try {
       // Send using RI and collect using TI
       eventCollector.collectRequestEvent(tiSipProvider);
       riSipProvider.sendRequest(invite);
       waitForMessage();
       receivedRequestEvent = eventCollector.extractCollectedRequestEvent();
       assertNotNull("The sent request was not received at the other end!", receivedRequestEvent);
       assertNotNull(
           "The sent request was not received at the other end!",
           receivedRequestEvent.getRequest());
     } catch (TooManyListenersException ex) {
       // This time adding the listener is (sort of) part of the test
       // so we fail instead of just "throwing on" the exc
       ex.printStackTrace();
       fail(
           "A TooManyListenersException was thrown while trying to add "
               + "a SipListener to a TI SipProvider.");
     } catch (SipException ex) {
       throw new TckInternalError("The RI failed to send the request!", ex);
     }
     // question: should we compare sent and received request?
     // my opinion: finding a discrepancy while comparing requests
     // would most probably mean a parse error and parsing is not what
     // we are currently testing
     // Transaction initiating requests should not have a server transaction
     // associated with them as the application might decide to handle the
     // request statelessly
     assertNull(
         "The Tested Implementation has implicitly created a ServerTransaction "
             + "for the received request. Transactions should only be created "
             + "explicitly using the SipProvider.getNewXxxTransaction() method.",
         receivedRequestEvent.getServerTransaction());
   } catch (Throwable exc) {
     exc.printStackTrace();
     fail(exc.getClass().getName() + ": " + exc.getMessage());
   }
   assertTrue(new Exception().getStackTrace()[0].toString(), true);
 }
  /**
   * Wait for a request.
   *
   * @param method the method expected.
   * @param strict if <code>true</code>, fails if received a request with the wrong method else,
   *     ignore request with wrong method.
   * @param timeout
   * @return
   */
  public synchronized ServerTransaction waitForRequest(
      String method, boolean strict, long timeout) {

    if (!isLastRequestUncommited()) {
      try {
        wait(timeout);
      } catch (Exception e) {
      }
    }
    RequestEvent event = getLastRequest();
    if (event == null) fail("No event received");
    Request request = event.getRequest();

    if (!isLastRequestUncommited())
      fail("Response has been already sent for last request:\n" + event);

    if (strict && !request.getMethod().equals(method))
      fail("Received " + request.getMethod() + " when expected " + method);

    while (!request.getMethod().equals(method)) {
      try {
        wait(timeout);
      } catch (Exception e) {
      }
      event = getLastRequest();
      request = event.getRequest();
    }

    ServerTransaction tx = event.getServerTransaction();

    if (tx == null) {
      if (Request.ACK.equals(method)) return null;

      try {
        tx = _sipPhone.getParent().getSipProvider().getNewServerTransaction(request);
      } catch (Exception ex) {
        throw new RuntimeException(ex);
      }
    }

    return tx;
  }
Beispiel #12
0
  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();
      }
    }
  }
Beispiel #13
0
  /**
   * Processes SIP requests. The only request being handled is BYE.
   *
   * @param requestReceivedEvent the event containing the SIP request
   */
  public synchronized void processRequest(RequestEvent requestReceivedEvent) {

    // obtain request and transaction id
    Request request = requestReceivedEvent.getRequest();

    ServerTransaction st = requestReceivedEvent.getServerTransaction();

    if (request.getMethod().equals(Request.BYE)) {
      handleBye(request, st);
    } else if (request.getMethod().equals(Request.INVITE)) {
      /*
       * This is a re-Invite
       */
      handleReInvite(request, st);
    } else if (request.getMethod().equals(Request.ACK)) {
      Logger.println("Call " + cp + " got ACK");
    } else {
      // no other requests should come in other than BYE, INVITE or ACK
      Logger.writeFile("Call " + cp + " ignoring request " + request.getMethod());
    }
  }
Beispiel #14
0
  public void processRequest(RequestEvent requestEvent) {
    Request request = requestEvent.getRequest();
    ServerTransaction serverTransactionId = requestEvent.getServerTransaction();

    logger.info(
        "\n\nRequest "
            + request.getMethod()
            + " received at "
            + protocolObjects.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);
    }
  }
    public void processRequest(RequestEvent requestReceivedEvent) {
      Request request = requestReceivedEvent.getRequest();
      ServerTransaction serverTransactionId = requestReceivedEvent.getServerTransaction();

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

      // We are the UAC so the only request we get is the BYE.
      if (request.getMethod().equals(Request.BYE)) processBye(request, serverTransactionId);
      else {
        try {
          serverTransactionId.sendResponse(messageFactory.createResponse(202, request));
        } catch (Exception e) {
          e.printStackTrace();
          fail("Unxepcted exception ");
        }
      }
    }
Beispiel #16
0
  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.CANCEL)) {
      processCancel(requestEvent, serverTransactionId);
    } else if (request.getMethod().equals(Request.REGISTER)) {
      processRegister(requestEvent, serverTransactionId);
    } else {
      processInDialogRequest(requestEvent, serverTransactionId);
    }
  }
  /**
   * Requests authorization for the new sip subscription.
   *
   * @param event
   * @param aci
   * @param subscriber
   * @param subscriberDisplayName
   * @param notifier
   * @param key
   * @param expires
   * @param content
   * @param contentType
   * @param contentSubtype
   * @param entityManager
   * @param childSbb
   */
  public void authorizeNewSipSubscription(
      RequestEvent event,
      ActivityContextInterface aci,
      String subscriber,
      String subscriberDisplayName,
      Notifier notifier,
      SubscriptionKey key,
      int expires,
      String content,
      String contentType,
      String contentSubtype,
      boolean eventList,
      SubscriptionControlDataSource dataSource,
      ImplementedSubscriptionControlSbbLocalObject childSbb) {

    // ask authorization
    if (key.getEventPackage().endsWith(".winfo")) {
      // winfo package, only accept subscriptions when subscriber and
      // notifier are the same
      newSipSubscriptionAuthorization(
          event.getServerTransaction(),
          aci,
          subscriber,
          subscriberDisplayName,
          notifier,
          key,
          expires,
          (subscriber.equals(notifier.getUri()) ? Response.OK : Response.FORBIDDEN),
          eventList,
          dataSource,
          childSbb);
    } else {
      if (notifier.isPresList() && subscriber.equals(notifier.getUri())) {
        // no need to auth a subscription to subscriber's own pres list
        newSipSubscriptionAuthorization(
            event.getServerTransaction(),
            aci,
            subscriber,
            subscriberDisplayName,
            notifier,
            key,
            expires,
            Response.OK,
            eventList,
            dataSource,
            childSbb);
      } else {
        childSbb.isSubscriberAuthorized(
            subscriber,
            subscriberDisplayName,
            notifier,
            key,
            expires,
            content,
            contentType,
            contentSubtype,
            eventList,
            event.getServerTransaction());
      }
    }
  }
  /** 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 onPublishEvent(RequestEvent event, ActivityContextInterface aci) {

    if (isTraceable(TraceLevel.FINEST)) {
      finest("onPublishEvent: PublishSbb received request:\n" + event.getRequest());
    }

    Request request = event.getRequest();
    ServerTransaction st = event.getServerTransaction();
    String sipAddress =
        getCanonicalAddress(((ToHeader) request.getHeader(ToHeader.NAME)).getAddress().getURI());

    // Check that the resource identified by the request-URI is one that this server is responsible
    // for
    //  This will be achieved by checking that the resource has been registered with the Registrar
    try {
      if (getLocationService().getRegistration(sipAddress) == null) {
        sendErrorResponse(
            Response.NOT_FOUND,
            "Presentity identified by Request-URI '"
                + sipAddress
                + "' not registered with Registrar",
            st,
            request);
        return;
      }
    } catch (CreateException e) {
      warn("Error creating location service: ", e);
    }

    // Check that the event package is correct - should be 'presence'
    if (request.getHeader(EventHeader.NAME) != null) {
      String eventType = ((EventHeader) request.getHeader(EventHeader.NAME)).getEventType();
      if (!eventType.equals("presence")) {
        sendErrorResponse(
            Response.BAD_EVENT,
            "PUBLISH request received with incorrect event package, package was '"
                + eventType
                + "', expected 'presence'",
            st,
            request);
        return;
      }
    }

    // Check for and validate SIP-If-Match header
    String eTag = null;
    String newETag = (new Integer((int) (Math.random() * 10000))).toString();

    if ((SIPIfMatchHeader) request.getHeader(SIPIfMatchHeader.NAME) != null) {

      // Found a SIP-If-Match header, retrieve E-Tag
      SIPIfMatchHeader sipIfMatchHeader =
          (SIPIfMatchHeader) request.getHeader(SIPIfMatchHeader.NAME);
      eTag = sipIfMatchHeader.getETag();
      if (isTraceable(TraceLevel.FINEST)) {
        finest("onPublishEvent: found E-Tag: " + eTag);
      }
      // Check that the entity-tag matches an entity-tag stored by the server
      if (!entityTagIsKnownByServer(sipAddress, eTag)) {
        if (isTraceable(TraceLevel.FINEST)) {
          finest("onPublishEvent: E-Tag '" + eTag + "' not recognised by server");
        }
        sendErrorResponse(
            Response.CONDITIONAL_REQUEST_FAILED,
            "Entity-tag is not known to this server, value of entity-tag is: " + eTag,
            st,
            request);
        return;
      }
    }

    // Validate requested Expiry time
    long expiryTime = validateExpireTime(request);
    // Check for correct media type
    if (request.getContent() != null && request.getHeader(ContentTypeHeader.NAME) != null) {
      ContentTypeHeader contentTypeHeader =
          (ContentTypeHeader) request.getHeader(ContentTypeHeader.NAME);
      if (!contentTypeHeader.getContentType().equalsIgnoreCase("application")
          || (!contentTypeHeader.getContentSubType().equalsIgnoreCase("pidf+xml"))) {
        sendErrorResponse(Response.UNSUPPORTED_MEDIA_TYPE, "Uncrecognised media type", st, request);
        return;
      }
    }

    // Process the PUBLISH request
    String body = request.toString();
    if (expiryTime == 0) {
      // this is a request to remove all stored presence information associated with this entity-tag
      if (eTag == null) {
        // this is a mal-formed request - can't remove presence information if it was never
        // published in the first place!
        sendErrorResponse(
            Response.BAD_REQUEST,
            "Received request to remove presence information, but no entity-tag was provided",
            st,
            request);
        return;
      } else {
        updatePresenceState(
            sipAddress, newETag, eTag, body, System.currentTimeMillis(), new Long(expiryTime));
      }
    } else {
      // this is either an initial request, or a request to modify or refresh a previous publication
      // get the body of PUBLISH request, if it has one

      if (eTag == null) {
        // this an initial request, make sure there's a body containing some presence info
        if (request.getContent() != null) {
          updatePresenceState(
              sipAddress,
              newETag,
              null,
              body,
              System.currentTimeMillis(),
              System.currentTimeMillis() + (expiryTime * 1000));
        } else {
          sendErrorResponse(
              Response.BAD_REQUEST,
              "Received initial PUBLISH request, but no presence information was provided",
              st,
              request);
          return;
        }
      } else {
        // this is either a request to refresh the publication (no body), or to modify or refresh
        // the published presence info
        updatePresenceState(
            sipAddress,
            newETag,
            eTag,
            (body != null ? body.toString() : null),
            System.currentTimeMillis(),
            System.currentTimeMillis() + (expiryTime * 1000));
      }
    }

    // if this point is reached, all processing has been successfully undertaken, so return a 200 OK
    // response
    sendOkResponse(st, request, (int) expiryTime, newETag);
  }
  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();
    }
  }
  /**
   * Dispatches the event received from a JAIN-SIP <tt>SipProvider</tt> to one of our "candidate
   * recipient" listeners.
   *
   * @param event the event received for a <tt>SipProvider</tt>.
   */
  public void processRequest(RequestEvent event) {
    try {
      Request request = event.getRequest();
      if (logger.isTraceEnabled()) logger.trace("received request: " + request.getMethod());

      /*
       * Create the transaction if it doesn't exist yet. If it is a
       * dialog-creating request, the dialog will also be automatically
       * created by the stack.
       */
      if (event.getServerTransaction() == null) {
        try {
          // apply some hacks if needed on incoming request
          // to be compliant with some servers/clients
          // if needed stop further processing.
          if (applyNonConformanceHacks(event)) return;

          SipProvider source = (SipProvider) event.getSource();
          ServerTransaction transaction = source.getNewServerTransaction(request);

          /*
           * Update the event, otherwise getServerTransaction() and
           * getDialog() will still return their previous value.
           */
          event = new RequestEvent(source, transaction, transaction.getDialog(), request);
        } catch (SipException ex) {
          logger.error(
              "couldn't create transaction, please report "
                  + "this to [email protected]",
              ex);
        }
      }

      ProtocolProviderServiceSipImpl service = getServiceData(event.getServerTransaction());
      if (service != null) {
        service.processRequest(event);
      } else {
        service = findTargetFor(request);
        if (service == null) {
          logger.error("couldn't find a ProtocolProviderServiceSipImpl " + "to dispatch to");
          if (event.getServerTransaction() != null) event.getServerTransaction().terminate();
        } else {

          /*
           * Mark the dialog for the dispatching of later in-dialog
           * requests. If there is no dialog, we need to mark the
           * request to dispatch a possible timeout when sending the
           * response.
           */
          Object container = event.getDialog();
          if (container == null) container = request;
          SipApplicationData.setApplicationData(container, SipApplicationData.KEY_SERVICE, service);

          service.processRequest(event);
        }
      }
    } catch (Throwable exc) {

      /*
       * Any exception thrown within our code should be caught here so
       * that we could log it rather than interrupt stack activity with
       * it.
       */
      this.logApplicationException(DialogTerminatedEvent.class, exc);

      // Unfortunately, death can hardly be ignored.
      if (exc instanceof ThreadDeath) throw (ThreadDeath) exc;
    }
  }
  /**
   * Starts the process of handling a new sip subscription
   *
   * @param event
   * @param aci
   * @param eventPackage
   * @param eventId
   * @param expires
   * @param entityManager
   * @param childSbb
   */
  public void newSipSubscription(
      RequestEvent event,
      ActivityContextInterface aci,
      String eventPackage,
      String eventId,
      int expires,
      SubscriptionControlDataSource dataSource,
      ImplementedSubscriptionControlSbbLocalObject childSbb) {

    // get subscription data from request
    Address fromAddress = ((FromHeader) event.getRequest().getHeader(FromHeader.NAME)).getAddress();
    String subscriber = fromAddress.getURI().toString();
    String subscriberDisplayName = fromAddress.getDisplayName();

    Notifier notifier = new Notifier(event.getRequest().getRequestURI().toString());

    // get content
    String content = null;
    String contentType = null;
    String contentSubtype = null;
    ContentTypeHeader contentTypeHeader =
        (ContentTypeHeader) event.getRequest().getHeader(ContentTypeHeader.NAME);
    if (contentTypeHeader != null) {
      contentType = contentTypeHeader.getContentType();
      contentSubtype = contentTypeHeader.getContentSubType();
      content = new String(event.getRequest().getRawContent());
    }

    // create dialog if does not exists
    Dialog dialog = event.getDialog();
    if (dialog == null) {
      try {
        dialog =
            sipSubscriptionHandler.sbb.getSipProvider().getNewDialog(event.getServerTransaction());
      } catch (Exception e) {
        tracer.severe("Can't create dialog", e);
        // cleanup
        try {
          Response response =
              sipSubscriptionHandler
                  .sbb
                  .getMessageFactory()
                  .createResponse(Response.SERVER_INTERNAL_ERROR, event.getRequest());
          response = sipSubscriptionHandler.addContactHeader(response);
          event.getServerTransaction().sendResponse(response);
        } catch (Exception f) {
          tracer.severe("Can't send RESPONSE", f);
        }
        return;
      }
    }

    // if dialog id is null (cause it's a new dialog and no response was sent yet) then build it
    // manually
    String dialogId =
        dialog.getDialogId() != null
            ? dialog.getDialogId()
            : ((SIPRequest) event.getRequest()).getDialogId(true, dialog.getLocalTag());
    SubscriptionKey key = new SubscriptionKey(dialogId, eventPackage, eventId);

    if (sipSubscriptionHandler.sbb.getConfiguration().getEventListSupportOn()) {
      // we need to find out if the notifier is a resource list
      int rlsResponse =
          sipSubscriptionHandler
              .sbb
              .getEventListSubscriptionHandler()
              .validateSubscribeRequest(subscriber, notifier, eventPackage, event);

      switch (rlsResponse) {
        case Response.NOT_FOUND:
          // the notifier is not a resource list, proceed with normal authorization means
          authorizeNewSipSubscription(
              event,
              aci,
              subscriber,
              subscriberDisplayName,
              notifier,
              key,
              expires,
              content,
              contentType,
              contentSubtype,
              false,
              dataSource,
              childSbb);
          break;
        case Response.OK:
          // the notifier is a resource list
          authorizeNewSipSubscription(
              event,
              aci,
              subscriber,
              subscriberDisplayName,
              notifier,
              key,
              expires,
              content,
              contentType,
              contentSubtype,
              true,
              dataSource,
              childSbb);
          break;
        default:
          // the rls request validation returned an error
          try {
            Response response =
                sipSubscriptionHandler
                    .sbb
                    .getMessageFactory()
                    .createResponse(rlsResponse, event.getRequest());
            response = sipSubscriptionHandler.addContactHeader(response);
            response.addHeader(
                sipSubscriptionHandler.sbb.getHeaderFactory().createRequireHeader("eventlist"));
            event.getServerTransaction().sendResponse(response);
          } catch (Exception f) {
            tracer.severe("Can't send RESPONSE", f);
          }
          return;
      }
    } else {
      authorizeNewSipSubscription(
          event,
          aci,
          subscriber,
          subscriberDisplayName,
          notifier,
          key,
          expires,
          content,
          contentType,
          contentSubtype,
          false,
          dataSource,
          childSbb);
    }
  }