public void start() throws IllegalStateException {

      SipFactory sipFactory = null;
      sipStack = null;

      Properties properties = new Properties();
      properties.setProperty("javax.sip.RETRANSMISSION_FILTER", "true");
      properties.setProperty("javax.sip.STACK_NAME", "StatelessForwarder");
      properties.setProperty("javax.sip.AUTOMATIC_DIALOG_SUPPORT", "off");
      // You need 16 for logging traces. 32 for debug + traces.
      // Your code will limp at 32 but it is best for debugging.
      properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "32");
      properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", "./logs/statelessforwarderdebug.txt");
      properties.setProperty("gov.nist.javax.sip.SERVER_LOG", "./logs/statelessforwarderlog.xml");

      try {
        // Create SipStack object
        sipFactory = SipFactory.getInstance();
        sipFactory.setPathName("gov.nist");
        sipStack = sipFactory.createSipStack(properties);

        headerFactory = sipFactory.createHeaderFactory();
        addressFactory = sipFactory.createAddressFactory();
        messageFactory = sipFactory.createMessageFactory();

        ListeningPoint lp = sipStack.createListeningPoint(myHost, myPort, ListeningPoint.UDP);
        sipProvider = sipStack.createSipProvider(lp);
        sipProvider.addSipListener(this);

        sipStack.start();
      } catch (Exception ex) {
        throw new IllegalStateException(
            "Cant create sip objects and lps due to[" + ex.getMessage() + "]", ex);
      }
    }
  public void init() throws Exception {
    SipFactory sipFactory = null;
    sipStack = null;
    sipFactory = SipFactory.getInstance();
    sipFactory.setPathName("gov.nist");
    Properties properties = new Properties();
    properties.setProperty("javax.sip.IP_ADDRESS", myIP);
    properties.setProperty("javax.sip.OUTBOUND_PROXY", peerIP + ":" + peerPort + "/udp");
    properties.setProperty("javax.sip.STACK_NAME", "conferencemonitor");
    properties.setProperty("javax.sip.RETRANSMISSION_FILTER", "on");
    //		properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", "conferencemonitordebug.txt");
    //		properties.setProperty("gov.nist.javax.sip.SERVER_LOG", "conferencemonitorlog.txt");
    properties.setProperty("gov.nist.javax.sip.CACHE_CLIENT_CONNECTIONS", "false");
    // Set to 0 in your production code for max speed.
    // You need  16 for logging traces. 32 for debug + traces.
    // Your code will limp at 32 but it is best for debugging.
    //		properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "32");

    // Create SipStack object
    sipStack = sipFactory.createSipStack(properties);

    headerFactory = sipFactory.createHeaderFactory();
    addressFactory = sipFactory.createAddressFactory();
    messageFactory = sipFactory.createMessageFactory();
    ListeningPoint udpListeningPoint = sipStack.createListeningPoint(myPort, "udp");
    sipProvider = sipStack.createSipProvider(udpListeningPoint);
    sipProvider.addSipListener(this);

    if (logger.isDebugEnabled()) logger.debug("init() " + sipProvider);
  }
Example #3
0
  public void destroy() {
    HashSet hashSet = new HashSet();

    for (Iterator it = sipStack.getSipProviders(); it.hasNext(); ) {

      SipProvider sipProvider = (SipProvider) it.next();
      hashSet.add(sipProvider);
    }

    for (Iterator it = hashSet.iterator(); it.hasNext(); ) {
      SipProvider sipProvider = (SipProvider) it.next();

      for (int j = 0; j < 5; j++) {
        try {
          sipStack.deleteSipProvider(sipProvider);
        } catch (ObjectInUseException ex) {
          try {
            Thread.sleep(1000);
          } catch (Exception e) {
          }
        }
      }
    }

    sipStack.stop();
  }
Example #4
0
  public void init() {
    this.dialogIds = new HashSet();
    this.transactionIDs = new HashMap();
    SipFactory sipFactory = null;
    sipStack = null;
    sipFactory = SipFactory.getInstance();
    sipFactory.setPathName("gov.nist");
    Properties properties = new Properties();

    properties.setProperty("javax.sip.STACK_NAME", "shootme");
    // You need 16 for logging traces. 32 for debug + traces.
    // Your code will limp at 32 but it is best for debugging.
    properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "32");
    properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", "shootmedebuglog.txt");
    properties.setProperty("gov.nist.javax.sip.SERVER_LOG", "shootmelog.txt");
    // Guard against starvation.
    properties.setProperty("gov.nist.javax.sip.READ_TIMEOUT", "1000");
    // properties.setProperty("gov.nist.javax.sip.MAX_MESSAGE_SIZE",
    // "4096");
    properties.setProperty("gov.nist.javax.sip.CACHE_SERVER_CONNECTIONS", "false");

    try {
      // Create SipStack object
      sipStack = sipFactory.createSipStack(properties);
      System.out.println("sipStack = " + sipStack);
    } catch (PeerUnavailableException e) {
      // could not find
      // gov.nist.jain.protocol.ip.sip.SipStackImpl
      // in the classpath
      e.printStackTrace();
      System.err.println(e.getMessage());
      if (e.getCause() != null) e.getCause().printStackTrace();
      System.exit(0);
    }

    try {
      headerFactory = sipFactory.createHeaderFactory();
      addressFactory = sipFactory.createAddressFactory();
      messageFactory = sipFactory.createMessageFactory();
      ListeningPoint lp = sipStack.createListeningPoint(myAddress, 5070, "udp");
      ListeningPoint lp1 = sipStack.createListeningPoint(myAddress, 5070, "tcp");

      Shootme listener = this;

      SipProvider sipProvider = sipStack.createSipProvider(lp);
      System.out.println("udp provider " + sipProvider);
      sipProvider.addSipListener(listener);
      sipProvider = sipStack.createSipProvider(lp1);
      System.out.println("tcp provider " + sipProvider);
      sipProvider.addSipListener(listener);

    } catch (Exception ex) {
      System.out.println(ex.getMessage());
      ex.printStackTrace();
      usage();
    }
  }
Example #5
0
  public void init() {

    ConsoleAppender console = new ConsoleAppender(); // create appender
    // configure the appender
    String PATTERN = "%d [%p|%c|%C{1}] %m%n";
    console.setLayout(new PatternLayout(PATTERN));
    console.setThreshold(Level.DEBUG);
    console.activateOptions();
    // add appender to any Logger (here is root)
    Logger.getRootLogger().addAppender(console);
    SipFactory sipFactory = null;
    sipStack = null;
    sipFactory = SipFactory.getInstance();
    sipFactory.setPathName("gov.nist");
    Properties properties = new Properties();
    properties.setProperty("javax.sip.STACK_NAME", "shootme");
    // You need 16 for logging traces. 32 for debug + traces.
    // Your code will limp at 32 but it is best for debugging.
    properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "LOG4J");
    properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", "shootmedebug.txt");
    properties.setProperty("gov.nist.javax.sip.SERVER_LOG", "shootmelog.txt");
    properties.setProperty(
        "gov.nist.javax.sip.MESSAGE_PROCESSOR_FACTORY", NioMessageProcessorFactory.class.getName());

    try {
      // Create SipStack object
      sipStack = sipFactory.createSipStack(properties);
      System.out.println("sipStack = " + sipStack);
    } catch (PeerUnavailableException e) {
      // could not find
      // gov.nist.jain.protocol.ip.sip.SipStackImpl
      // in the classpath
      e.printStackTrace();
      System.err.println(e.getMessage());
      if (e.getCause() != null) e.getCause().printStackTrace();
      System.exit(0);
    }

    try {
      headerFactory = sipFactory.createHeaderFactory();
      addressFactory = sipFactory.createAddressFactory();
      messageFactory = sipFactory.createMessageFactory();
      this.listeningPoint = sipStack.createListeningPoint("127.0.0.1", myPort, transport);

      B2BUA listener = this;

      sipProvider = sipStack.createSipProvider(listeningPoint);
      System.out.println("ws provider " + sipProvider);
      sipProvider.addSipListener(listener);

    } catch (Exception ex) {
      System.out.println(ex.getMessage());
      ex.printStackTrace();
    }
  }
Example #6
0
 public ViaHeader getStackViaHeader() {
   try {
     ListeningPoint lp = (ListeningPoint) sipStack.getListeningPoints().next();
     String host = sipStack.getIPAddress();
     int port = lp.getPort();
     String transport = lp.getTransport();
     // branch id is assigned by the transaction layer.
     return headerFactory.createViaHeader(host, port, transport, null);
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }
Example #7
0
  public void init(String transport) {
    if (transport == null) {
      transport = ListeningPoint.UDP;
    }
    SipFactory sipFactory = null;
    sipStack = null;
    sipFactory = SipFactory.getInstance();
    sipFactory.setPathName("gov.nist");
    Properties properties = new Properties();
    properties.setProperty("javax.sip.STACK_NAME", "cutme");
    // You need 16 for logging traces. 32 for debug + traces.
    // Your code will limp at 32 but it is best for debugging.
    properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "32");
    properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", "logs/cutmedebug.txt");
    properties.setProperty("gov.nist.javax.sip.SERVER_LOG", "logs/cutmelog.xml");

    try {
      // Create SipStack object
      sipStack = sipFactory.createSipStack(properties);
      System.out.println("sipStack = " + sipStack);
    } catch (PeerUnavailableException e) {
      // could not find
      // gov.nist.jain.protocol.ip.sip.SipStackImpl
      // in the classpath
      e.printStackTrace();
      System.err.println(e.getMessage());
      if (e.getCause() != null) e.getCause().printStackTrace();
      System.exit(0);
    }

    try {
      messageFactory = sipFactory.createMessageFactory();
      ListeningPoint lp =
          sipStack.createListeningPoint(
              "" + System.getProperty("org.mobicents.testsuite.testhostaddr") + "",
              myPort,
              transport);

      Cutme listener = this;

      SipProvider sipProvider = sipStack.createSipProvider(lp);
      System.out.println("udp provider " + sipProvider);
      sipProvider.addSipListener(listener);

    } catch (Exception ex) {
      System.out.println(ex.getMessage());
      ex.printStackTrace();
    }
  }
    public void init() {
      SipFactory sipFactory = null;
      sipStack = null;
      sipFactory = SipFactory.getInstance();
      sipFactory.setPathName("gov.nist");
      Properties properties = new Properties();
      properties.setProperty("javax.sip.STACK_NAME", "shootme");
      // You need 16 for logging traces. 32 for debug + traces.
      // Your code will limp at 32 but it is best for debugging.
      properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "32");
      properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", "shootmedebug.txt");
      properties.setProperty("gov.nist.javax.sip.SERVER_LOG", "shootmelog.txt");
      if (System.getProperty("enableNIO") != null
          && System.getProperty("enableNIO").equalsIgnoreCase("true")) {
        properties.setProperty(
            "gov.nist.javax.sip.MESSAGE_PROCESSOR_FACTORY",
            NioMessageProcessorFactory.class.getName());
      }
      try {
        // Create SipStack object
        sipStack = sipFactory.createSipStack(properties);
        System.out.println("sipStack = " + sipStack);
      } catch (PeerUnavailableException e) {
        // could not find
        // gov.nist.jain.protocol.ip.sip.SipStackImpl
        // in the classpath
        e.printStackTrace();
        System.err.println(e.getMessage());
        if (e.getCause() != null) e.getCause().printStackTrace();
        System.exit(0);
      }

      try {
        headerFactory = sipFactory.createHeaderFactory();
        addressFactory = sipFactory.createAddressFactory();
        messageFactory = sipFactory.createMessageFactory();
        ListeningPoint lp = sipStack.createListeningPoint("127.0.0.1", myPort, "udp");

        Shootme listener = this;

        SipProvider sipProvider = sipStack.createSipProvider(lp);
        System.out.println("udp provider " + sipProvider);
        sipProvider.addSipListener(listener);

      } catch (Exception ex) {
        ex.printStackTrace();
        fail("Unexpected exception");
      }
    }
 public void setOff(SipStack mySipStack) {
   /// System.out.println("=> BUNDLE: br.ufes.inf.ngn.televoto.client.logic | CLASS: LogicListener
   // | METOD: setOff ");//By Ju
   try {
     mySipProvider.removeSipListener(this);
     mySipProvider.removeListeningPoint(myListeningPoint);
     mySipStack.deleteListeningPoint(myListeningPoint);
     mySipStack.deleteSipProvider(mySipProvider);
     myListeningPoint = null;
     mySipProvider = null;
     mySipStack = null;
     // myRingTool=null;
     myTimer.cancel();
     System.out.println("Finalizado...");
   } catch (Exception e) {
   }
 }
Example #10
0
  public ContactHeader getStackContactHeader() {
    try {
      ListeningPoint lp = (ListeningPoint) sipStack.getListeningPoints().next();
      String host = sipStack.getIPAddress();
      int port = lp.getPort();
      String transport = lp.getTransport();

      SipURI sipURI = addressFactory.createSipURI(null, host);
      sipURI.setPort(port);
      sipURI.setTransportParam(transport);
      Address contactAddress = addressFactory.createAddress(sipURI);

      return headerFactory.createContactHeader(contactAddress);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
Example #11
0
 private void shutDown() {
   try {
     try {
       Thread.sleep(2000);
     } catch (InterruptedException e) {
     }
     System.out.println("nulling reference");
     sipStack.deleteListeningPoint(tcpListeningPoint);
     sipStack.deleteListeningPoint(udpListeningPoint);
     // This will close down the stack and exit all threads
     tcpProvider.removeSipListener(this);
     udpProvider.removeSipListener(this);
     while (true) {
       try {
         sipStack.deleteSipProvider(udpProvider);
         sipStack.deleteSipProvider(tcpProvider);
         break;
       } catch (ObjectInUseException ex) {
         try {
           Thread.sleep(2000);
         } catch (InterruptedException e) {
           continue;
         }
       }
     }
     sipStack = null;
     tcpProvider = null;
     udpProvider = null;
     this.contactHeader = null;
     addressFactory = null;
     headerFactory = null;
     messageFactory = null;
     this.udpListeningPoint = null;
     this.tcpListeningPoint = null;
     this.reInviteCount = 0;
     System.gc();
     // Redo this from the start.
     if (counter < 10) this.init();
     else counter++;
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
Example #12
0
  /** Exit the proxy, throws Exception that which can be caught by the upper application */
  public void exit() throws Exception {
    Iterator sipProviders = sipStack.getSipProviders();
    if (sipProviders != null) {
      while (sipProviders.hasNext()) {
        SipProvider sp = (SipProvider) sipProviders.next();
        sp.removeSipListener(this);
        sipStack.deleteSipProvider(sp);
        sipProviders = sipStack.getSipProviders();
        System.out.println("One sip Provider removed!");
      }
    } else {
      ProxyDebug.println("WARNING, STOP_PROXY, The proxy " + " has no sip Provider to remove!");
    }

    Iterator listeningPoints = sipStack.getListeningPoints();
    if (listeningPoints != null) {
      while (listeningPoints.hasNext()) {
        ListeningPoint lp = (ListeningPoint) listeningPoints.next();
        sipStack.deleteListeningPoint(lp);
        listeningPoints = sipStack.getListeningPoints();
        System.out.println("One listening point removed!");
      }
    } else {
      ProxyDebug.println("WARNING, STOP_PROXY, The proxy " + " has no listening points to remove!");
    }
    ProxyDebug.println("Proxy exit.........................");
    configuration.listeningPoints.clear();
    registrar.clean();
  }
Example #13
0
  /**
   * Stop the proxy, this method has to be called after the start method throws Exception that which
   * can be caught by the upper application
   */
  public void stop() throws Exception {
    if (sipStack == null) return;
    this.presenceServer.stop();

    Iterator sipProviders = sipStack.getSipProviders();
    if (sipProviders != null) {
      while (sipProviders.hasNext()) {
        SipProvider sp = (SipProvider) sipProviders.next();
        sp.removeSipListener(this);
        sipStack.deleteSipProvider(sp);
        sipProviders = sipStack.getSipProviders();
        System.out.println("One sip Provider removed!");
      }
    } else {
      ProxyDebug.println("WARNING, STOP_PROXY, The proxy " + " has no sip Provider to remove!");
    }

    Iterator listeningPoints = sipStack.getListeningPoints();
    if (listeningPoints != null) {
      while (listeningPoints.hasNext()) {
        ListeningPoint lp = (ListeningPoint) listeningPoints.next();
        sipStack.deleteListeningPoint(lp);
        listeningPoints = sipStack.getListeningPoints();
        System.out.println("One listening point removed!");
      }
    } else {
      ProxyDebug.println("WARNING, STOP_PROXY, The proxy " + " has no listening points to remove!");
    }
    registrar.clean();
  }
  public static void stopSipStack(SipStack sipStack, SipListener listener) {
    Iterator<SipProvider> sipProviderIterator = sipStack.getSipProviders();
    try {
      while (sipProviderIterator.hasNext()) {
        SipProvider sipProvider = sipProviderIterator.next();
        ListeningPoint[] listeningPoints = sipProvider.getListeningPoints();
        for (ListeningPoint listeningPoint : listeningPoints) {
          sipProvider.removeListeningPoint(listeningPoint);
          sipStack.deleteListeningPoint(listeningPoint);
          listeningPoints = sipProvider.getListeningPoints();
        }
        sipProvider.removeSipListener(listener);
        sipStack.deleteSipProvider(sipProvider);
        sipProviderIterator = sipStack.getSipProviders();
      }
    } catch (Exception e) {
      throw new IllegalStateException("Cant remove the listening points or sip providers", e);
    }

    sipStack.stop();
    sipStack = null;
  }
Example #15
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 synchronized boolean init() {
   if (initialized == true) return true;
   initialized = true;
   logger.info("Starting the reaper stack...");
   try {
     SipStack sipStack;
     Configuration configuration;
     configuration = new Configuration();
     configuration.setStackName(STACK_NAME);
     SipFactory.getInstance().setPathName("gov.nist");
     sipStack = SipFactory.getInstance().createSipStack(configuration);
     RequestMessage.initFactory(SipFactory.getInstance(), configuration);
     ListeningPoint reaperTcp =
         sipStack.createListeningPoint("127.0.0.1", configuration.getReadPort(), "tcp");
     reaperProvider = sipStack.createSipProvider(reaperTcp);
     reaperProvider.addSipListener(new ReaperListener());
     reaperProvider.setAutomaticDialogSupportEnabled(false);
     logger.info("Reaper SIP stack initialized successfully");
   } catch (Exception e) {
     logger.error("Error initializing stack: ", e);
     return false;
   }
   return true;
 }
    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);
      }
    }
Example #18
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();
      }
    }
  }
    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 ");
        }
      }
    }
Example #20
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);
    }
  }
    public void init() {
      SipFactory sipFactory = null;
      sipStack = null;
      sipFactory = SipFactory.getInstance();
      sipFactory.setPathName("org.mobicents.ha");
      Properties properties = new Properties();
      properties.setProperty("javax.sip.STACK_NAME", stackName);
      // properties.setProperty("javax.sip.OUTBOUND_PROXY", Integer
      //                .toString(BALANCER_PORT));
      // You need 16 for logging traces. 32 for debug + traces.
      // Your code will limp at 32 but it is best for debugging.
      properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "32");
      properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", "logs/" + stackName + "debug.txt");
      properties.setProperty("gov.nist.javax.sip.SERVER_LOG", "logs/" + stackName + "log.xml");

      try {
        // Create SipStack object
        sipStack = sipFactory.createSipStack(properties);
        System.out.println("sipStack = " + sipStack);
      } catch (PeerUnavailableException e) {
        // could not find
        // gov.nist.jain.protocol.ip.sip.SipStackImpl
        // in the classpath
        e.printStackTrace();
        System.err.println(e.getMessage());
        if (e.getCause() != null) e.getCause().printStackTrace();
        System.exit(0);
      }

      try {
        headerFactory = sipFactory.createHeaderFactory();
        addressFactory = sipFactory.createAddressFactory();
        messageFactory = sipFactory.createMessageFactory();
        ListeningPoint lp = sipStack.createListeningPoint(myAddress, myPort, ListeningPoint.UDP);

        Shootme listener = this;

        sipProvider = sipStack.createSipProvider(lp);
        System.out.println("udp provider " + sipProvider);
        sipProvider.addSipListener(listener);
        //                if(dialogs != null) {
        //                    Collection<Dialog> serializedDialogs =
        // simulateDialogSerialization(dialogs);
        //                    for (Dialog dialog : serializedDialogs) {
        //                        ((SIPDialog)dialog).setSipProvider((SipProviderImpl)sipProvider);
        //                        ((SipStackImpl)sipStack).putDialog((SIPDialog)dialog);
        //                    }
        //                    this.dialog = (SIPDialog)serializedDialogs.iterator().next();
        //                }
        sipStack.start();
        if (!callerSendsBye && this.dialog != null) {
          try {
            Request byeRequest = this.dialog.createRequest(Request.BYE);
            ClientTransaction ct = sipProvider.getNewClientTransaction(byeRequest);
            System.out.println("sending BYE " + byeRequest);
            dialog.sendRequest(ct);
          } catch (Exception ex) {
            ex.printStackTrace();
            fail("Unexpected exception ");
          }
        }
      } catch (Exception ex) {
        System.out.println(ex.getMessage());
        ex.printStackTrace();
        fail("Unexpected exception");
      }
    }
    public void init() {
      SipFactory sipFactory = null;
      sipStack = null;
      sipFactory = SipFactory.getInstance();
      sipFactory.setPathName("gov.nist");
      Properties properties = new Properties();
      // If you want to try TCP transport change the following to
      String transport = "udp";
      String peerHostPort = "127.0.0.1:5070";
      properties.setProperty("javax.sip.OUTBOUND_PROXY", peerHostPort + "/" + transport);
      // If you want to use UDP then uncomment this.
      properties.setProperty("javax.sip.STACK_NAME", "shootist");

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

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

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

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

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

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

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

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

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

        // Create ViaHeaders

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

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

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

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

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

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

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

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

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

        Address contactAddress = addressFactory.createAddress(contactURI);

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

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

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

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

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

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

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

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

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

        dialog = inviteTid.getDialog();

      } catch (Exception ex) {
        fail("cannot create or send initial invite");
      }
    }
Example #23
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();
      }
    }
  }
Example #24
0
  /**
   * Start the proxy, this method has to be called after the init method throws Exception that which
   * can be caught by the upper application
   */
  public void start() throws Exception {
    if (configuration != null && configuration.isValidConfiguration()) {
      Properties properties = new Properties();
      // LOGGING property:

      if (configuration.enableDebug) {
        ProxyDebug.debug = true;
        ProxyDebug.setProxyOutputFile(configuration.outputProxy);
        ProxyDebug.println("DEBUG properties set!");
        if (configuration.badMessageLogFile != null)
          properties.setProperty(
              "gov.nist.javax.sip.BAD_MESSAGE_LOG", configuration.badMessageLogFile);
        if (configuration.debugLogFile != null) {
          properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", configuration.debugLogFile);
        }
        if (configuration.serverLogFile != null)
          properties.setProperty("gov.nist.javax.sip.SERVER_LOG", configuration.serverLogFile);
        if (configuration.debugLogFile != null)
          properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "32");
        else if (configuration.serverLogFile != null)
          properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "16");
        else properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "0");

      } else {
        System.out.println("DEBUG properties not set!");
      }
      registrar.setExpiresTime(configuration.expiresTime);

      // STOP TIME
      if (configuration.stopTime != null) {
        try {
          long stopTime = Long.parseLong(configuration.stopTime);
          StopProxy stopProxy = new StopProxy(this);
          Timer timer = new Timer();
          timer.schedule(stopProxy, stopTime);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }

      sipStack = null;

      SipFactory sipFactory = SipFactory.getInstance();
      sipFactory.setPathName("gov.nist");

      headerFactory = sipFactory.createHeaderFactory();
      addressFactory = sipFactory.createAddressFactory();
      messageFactory = sipFactory.createMessageFactory();

      // Create SipStack object

      properties.setProperty("javax.sip.IP_ADDRESS", configuration.stackIPAddress);

      // We have to add the IP address of the proxy for the domain:
      configuration.domainList.addElement(configuration.stackIPAddress);
      ProxyDebug.println("The proxy is responsible for the domain:" + configuration.stackIPAddress);

      properties.setProperty("javax.sip.STACK_NAME", configuration.stackName);
      if (configuration.check(configuration.outboundProxy))
        properties.setProperty("javax.sip.OUTBOUND_PROXY", configuration.outboundProxy);
      if (configuration.check(configuration.routerPath))
        properties.setProperty("javax.sip.ROUTER_PATH", configuration.routerPath);
      if (configuration.check(configuration.extensionMethods))
        properties.setProperty("javax.sip.EXTENSION_METHODS", configuration.extensionMethods);
      // This has to be hardcoded to true. for the proxy.
      properties.setProperty("javax.sip.RETRANSMISSION_FILTER", "on");

      if (configuration.check(configuration.maxConnections))
        properties.setProperty("gov.nist.javax.sip.MAX_CONNECTIONS", configuration.maxConnections);
      if (configuration.check(configuration.maxServerTransactions))
        properties.setProperty(
            "gov.nist.javax.sip.MAX_SERVER_TRANSACTIONS", configuration.maxServerTransactions);
      if (configuration.check(configuration.threadPoolSize))
        properties.setProperty("gov.nist.javax.sip.THREAD_POOL_SIZE", configuration.threadPoolSize);

      if (configuration.domainList != null)
        for (int j = 0; j < configuration.domainList.size(); j++) {
          String domain = (String) configuration.domainList.elementAt(j);
          ProxyDebug.println("Here is one domain to take care of:" + domain);
        }
      else ProxyDebug.println("No domain to take care of...");

      if (configuration.accessLogViaRMI) {
        properties.setProperty("gov.nist.javax.sip.ACCESS_LOG_VIA_RMI", "true");

        properties.setProperty("gov.nist.javax.sip.RMI_PORT", configuration.logRMIPort);

        if (configuration.check(configuration.logLifetime))
          properties.setProperty("gov.nist.javax.sip.LOG_LIFETIME", configuration.logLifetime);
      }

      sipStack = sipFactory.createSipStack(properties);

      // Authentication part:
      if (configuration.enableAuthentication) {
        authentication = new Authentication(this);
        try {

          Class authMethodClass = Class.forName(configuration.classFile);
          AuthenticationMethod authMethod = (AuthenticationMethod) authMethodClass.newInstance();
          authMethod.initialize(configuration.passwordsFile);

          authentication.setAuthenticationMethod(authMethod);

        } catch (Exception e) {
          ProxyDebug.println("ERROR, authentication process stopped, exception raised:");
          e.printStackTrace();
        }
      }

      // We create the Listening points:
      Vector lps = configuration.getListeningPoints();

      for (int i = 0; lps != null && i < lps.size(); i++) {
        Association a = (Association) lps.elementAt(i);
        try {
          System.out.println("transport  " + a.transport);
          System.out.println("port  " + Integer.valueOf(a.port).intValue());
          ListeningPoint lp =
              sipStack.createListeningPoint(Integer.valueOf(a.port).intValue(), a.transport);
          this.listeningPoints.add(lp);
          SipProvider sipProvider = sipStack.createSipProvider(lp);
          if (this.defaultProvider == null) this.defaultProvider = sipProvider;
          sipProvider.addSipListener(this);
        } catch (Exception e) {
          e.printStackTrace();
          ProxyDebug.println("ERROR: listening point not created ");
        }
      }
      // Export the registry for polling by the responder.

      if (configuration.exportRegistry)
        // initialize the registrar for RMI.
        this.registrar.initRMIBindings();

      // Parse static configuration for registrar.
      if (configuration.enableRegistrations) {
        String value = configuration.registrationsFile;
        ProxyDebug.println("Parsing the XML registrations file: " + value);
        if (value == null || value.trim().equals(""))
          ProxyDebug.println("You have to set the registrations file...");
        else registrar.parseXMLregistrations(value);
      } else ProxyDebug.println("No registrations to parse...");

      // Register to proxies if any:
      registrar.registerToProxies();

    } else {
      System.out.println(
          "ERROR: the configuration file is not correct!" + " Correct the errors first.");
    }
  }
  public void setup() {
    /// System.out.println("=> BUNDLE: br.ufes.inf.ngn.televoto.client.logic | CLASS: LogicListener
    // | METOD: setup ");//By Ju
    try {
      // String log4jConfPath = "//etc//osgi//log4j.properties"; //comentei
      // PropertyConfigurator.configure(log4jConfPath);
      if (!Unregistring) { // Se é um registro
        Object parametros[] = new Object[9];
        parametros = getArguments();
        myDataSource = Activator.ds;
        myServer = (String) parametros[3];
        destination = (String) parametros[6];
        dialTimes = (Integer) parametros[7];
        useQueue = (String) parametros[8];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      // logger.info(myRegisterRequest.toString());
      // System.out.println(">>> " + myRegisterRequest.toString());
      status = REGISTERING;
    } catch (Exception e) {
      e.printStackTrace();
    }
  }