Exemplo n.º 1
0
  /** Process the ACK request. Send the bye and complete the call flow. */
  public void processAck(RequestEvent requestEvent, ServerTransaction serverTransaction) {
    SipProvider sipProvider = (SipProvider) requestEvent.getSource();
    try {
      // System.out.println("*** shootme: got an ACK "
      // + requestEvent.getRequest());
      if (serverTransaction == null) {
        System.out.println("null server transaction -- ignoring the ACK!");
        return;
      }
      Dialog dialog = serverTransaction.getDialog();
      this.createdCount++;
      System.out.println(
          "Dialog Created = "
              + dialog.getDialogId()
              + " createdCount "
              + this.createdCount
              + " Dialog State = "
              + dialog.getState());

      if (this.dialogIds.contains(dialog.getDialogId())) {
        System.out.println("OOPS ! I already saw " + dialog.getDialogId());
      } else {
        this.dialogIds.add(dialog.getDialogId());
      }

      Request byeRequest = dialog.createRequest(Request.BYE);
      ClientTransaction tr = sipProvider.getNewClientTransaction(byeRequest);
      // System.out.println("shootme: got an ACK -- sending bye! ");
      dialog.sendRequest(tr);

    } catch (Exception ex) {
      ex.printStackTrace();
      System.exit(0);
    }
  }
Exemplo n.º 2
0
  /**
   * Creates and sends a SUBSCRIBE request to the subscription <tt>Address</tt>/Request URI of a
   * specific <tt>Subscription</tt> in order to request receiving event notifications and adds the
   * specified <tt>Subscription</tt> to the list of subscriptions managed by this instance. The
   * added <tt>Subscription</tt> may later receive notifications to process the <tt>Request</tt>s
   * and/or <tt>Response</tt>s which constitute the signaling session associated with it. If the
   * attempt to create and send the SUBSCRIBE request fails, the specified <tt>Subscription</tt> is
   * not added to the list of subscriptions managed by this instance.
   *
   * @param subscription a <tt>Subscription</tt> which specifies the properties of the SUBSCRIBE
   *     request to be created and sent, to be added to the list of subscriptions managed by this
   *     instance
   * @throws OperationFailedException if we fail constructing or sending the subscription request.
   */
  public void subscribe(Subscription subscription) throws OperationFailedException {
    Dialog dialog = subscription.getDialog();

    if ((dialog != null) && DialogState.TERMINATED.equals(dialog.getState())) dialog = null;

    // create the subscription
    ClientTransaction subscribeTransaction = null;
    try {
      subscribeTransaction =
          (dialog == null)
              ? createSubscription(subscription, subscriptionDuration)
              : createSubscription(subscription, dialog, subscriptionDuration);
    } catch (OperationFailedException ex) {
      ProtocolProviderServiceSipImpl.throwOperationFailedException(
          "Failed to create the subscription", OperationFailedException.INTERNAL_ERROR, ex, logger);
    }

    // we register the contact to find him when the OK will arrive
    CallIdHeader callIdHeader =
        (CallIdHeader) subscribeTransaction.getRequest().getHeader(CallIdHeader.NAME);
    String callId = callIdHeader.getCallId();
    addSubscription(callId, subscription);

    // send the message
    try {
      if (dialog == null) subscribeTransaction.sendRequest();
      else dialog.sendRequest(subscribeTransaction);
    } catch (SipException ex) {
      // this contact will never been accepted or rejected
      removeSubscription(callId, subscription);

      ProtocolProviderServiceSipImpl.throwOperationFailedException(
          "Failed to send the subscription", OperationFailedException.NETWORK_FAILURE, ex, logger);
    }
  }
    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());

      } catch (Exception ex) {
        fail("Unexpected exception");
      }
    }
Exemplo n.º 4
0
 /** Process the ACK request, forward it to the other leg. */
 public void processAck(RequestEvent requestEvent, ServerTransaction serverTransaction) {
   try {
     Dialog dialog = serverTransaction.getDialog();
     System.out.println("b2bua: got an ACK! ");
     System.out.println("Dialog State = " + dialog.getState());
     Dialog otherDialog = (Dialog) dialog.getApplicationData();
     Request request = otherDialog.createAck(otherDialog.getLocalSeqNumber());
     otherDialog.sendAck(request);
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
 /** Process the ACK request. Send the bye and complete the call flow. */
 public void processAck(RequestEvent requestEvent, ServerTransaction serverTransaction) {
   try {
     System.out.println("shootme: got an ACK! ");
     System.out.println("Dialog State = " + dialog.getState());
     SipProvider provider = (SipProvider) requestEvent.getSource();
     if (!callerSendsBye) {
       Request byeRequest = dialog.createRequest(Request.BYE);
       ClientTransaction ct = provider.getNewClientTransaction(byeRequest);
       dialog.sendRequest(ct);
     }
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
    /** Process the ACK request. Send the bye and complete the call flow. */
    public void processAck(RequestEvent requestEvent, ServerTransaction serverTransaction) {
      try {
        System.out.println("shootme: got an ACK! ");
        System.out.println("Dialog State = " + dialog.getState());
        //                SipProvider provider = (SipProvider) requestEvent.getSource();
        // stopping the node
        //                Collection<Dialog>
        // dialogs=((SipStackImpl)sipStack).getDialogs(DialogState.CONFIRMED);
        stop();
        //                shootmeRecoveryNode.init();

        // if (!callerSendsBye && !byeTaskRunning) {
        // byeTaskRunning = true;
        // new Timer().schedule(new ByeTask(dialog), 4000) ;
        // }
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
Exemplo n.º 7
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);
    }
  }
Exemplo n.º 8
0
 /** Process the ACK request. Send the bye and complete the call flow. */
 public void processAck(RequestEvent requestEvent, ServerTransaction serverTransaction) {
   System.out.println("shootme: got an ACK! ");
   System.out.println("Dialog State = " + dialog.getState());
 }
    public void processResponse(ResponseEvent responseReceivedEvent) {
      System.out.println("Got a response");
      Response response = (Response) responseReceivedEvent.getResponse();
      ClientTransaction tid = responseReceivedEvent.getClientTransaction();
      CSeqHeader cseq = (CSeqHeader) response.getHeader(CSeqHeader.NAME);

      System.out.println(
          "Response received : Status Code = " + response.getStatusCode() + " " + cseq);

      if (tid == null) {

        // RFC3261: MUST respond to every 2xx
        if (ackRequest != null && dialog != null) {
          System.out.println("re-sending ACK");
          try {
            dialog.sendAck(ackRequest);
          } catch (SipException se) {
            se.printStackTrace();
            fail("Unxpected exception ");
          }
        }
        return;
      }
      // If the caller is supposed to send the bye
      if (callerSendsBye && !byeTaskRunning) {
        byeTaskRunning = true;
        new Timer().schedule(new ByeTask(dialog), 4000);
      }
      System.out.println("transaction state is " + tid.getState());
      System.out.println("Dialog = " + tid.getDialog());
      System.out.println("Dialog State is " + tid.getDialog().getState());

      assertSame("Checking dialog identity", tid.getDialog(), this.dialog);

      try {
        if (response.getStatusCode() == Response.OK) {
          if (cseq.getMethod().equals(Request.INVITE)) {
            System.out.println("Dialog after 200 OK  " + dialog);
            System.out.println("Dialog State after 200 OK  " + dialog.getState());
            Request ackRequest = dialog.createAck(cseq.getSeqNumber());
            System.out.println("Sending ACK");
            dialog.sendAck(ackRequest);

            // JvB: test REFER, reported bug in tag handling
            //                      Request referRequest = dialog.createRequest("REFER");
            //                      //simulating a balancer that will forward the request to the
            // recovery node
            //                      SipURI referRequestURI = addressFactory.createSipURI(null,
            // "127.0.0.1:5080");
            //                      referRequest.setRequestURI(referRequestURI);
            //                      dialog.sendRequest(
            // sipProvider.getNewClientTransaction(referRequest));
            //
          } else if (cseq.getMethod().equals(Request.CANCEL)) {
            if (dialog.getState() == DialogState.CONFIRMED) {
              // oops cancel went in too late. Need to hang up the
              // dialog.
              System.out.println("Sending BYE -- cancel went in too late !!");
              Request byeRequest = dialog.createRequest(Request.BYE);
              ClientTransaction ct = sipProvider.getNewClientTransaction(byeRequest);
              dialog.sendRequest(ct);
            }

          } else if (cseq.getMethod().equals(Request.BYE)) {
            okToByeReceived = true;
          }
        }
      } catch (Exception ex) {
        ex.printStackTrace();
        System.exit(0);
      }
    }
Exemplo n.º 10
0
  /** 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();
      }
    }
  }
  /**
   * @param originalRequestEvent
   * @param response
   * @param serviceUnit
   */
  @Override
  public void sendResponse(
      RequestEvent originalRequestEvent, Response response, ServiceUnit serviceUnit, String toTag) {
    /** Here we need to do some specific handling specific to the type of responses being sent. */

    /**
     * If it is a 180 RINGING response, then we need to set the To tag to the same to tag generated
     * when creating the associated B2BSession and B2BDialog.
     */
    if (isDialogCreating(response.getStatusCode())) {
      logger.fine("Sending a ringing response...");
      /** Copy the Local Tag from the B2BDialog to the SipResponse */
      logger.info("Setting the To Dialog of the response to be sent to : " + toTag);
      SIPResponse sipResponse = (SIPResponse) response;
      sipResponse.setToTag(toTag);
    }
    logger.info(
        "Sending Response for the request associated with ServiceUnit: " + serviceUnit.getName());
    /** Conveying the response sending to the UserAgent */
    logger.info("Sending Response: " + response.getReasonPhrase());
    Dialog sipDialog = userAgent.sendResponse(originalRequestEvent, response, serviceUnit);
    if (sipDialog == null) {
      logger.info(
          "The sent response " + response.getReasonPhrase() + " did not resulted in any dialog...");
    } else {
      logger.info(
          "The sent response "
              + response.getReasonPhrase()
              + " has created a new Dialog with ID: "
              + sipDialog.getDialogId());
    }
    /**
     * Set the underlying SIP Dialog of the B2BDialog for Dialog creating responses as well as the
     * local seq number and the current state of the dialog.
     */
    if (isDialogCreating(response.getStatusCode())) {
      B2BSession b2BSessions[] =
          RuntimeComponentContext.getInstance().getB2BSessions(serviceUnit.getName());
      for (B2BSession b2BSession : b2BSessions) {
        B2BDialogImpl b2BDialogImpl = null;
        if (sipDialog != null) {
          b2BDialogImpl =
              (B2BDialogImpl) b2BSession.getB2BDialog(sipDialog.getDialogId(), true, null);
        }
        if (b2BDialogImpl != null) {
          logger.info(
              "Setting the underlying SIP Dialog property of the B2BDialog: "
                  + b2BDialogImpl.getDialogId());
          b2BDialogImpl.setUnderlyingSipDialog(sipDialog);
          b2BDialogImpl.setLocalSeqNumber(sipDialog.getLocalSeqNumber());
          b2BDialogImpl.setState(sipDialog.getState().toString());
          logger.info(
              "Setting the Dialog status with ID: "
                  + b2BDialogImpl.getDialogId()
                  + " to "
                  + sipDialog.getState().toString());
          break;
        } else {
          logger.info("Unable to locate a B2BDialog with ID " + sipDialog.getDialogId());
        }
      }
    }
  }