Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package test.unit.gov.nist.javax.sip.stack.subsnotify;
  
  
  import javax.sip.*;
  import javax.sip.header.*;
  
 import java.util.*;
 
This class is a UAC template. Shootist is the guy that shoots and notifier is the guy that gets shot.

Author(s):
M. Ranganathan
 
 
 public class Notifier implements SipListener {
 
     private static AddressFactory addressFactory;
 
     private static MessageFactory messageFactory;
 
     private static HeaderFactory headerFactory;
 
     private static SipStack sipStack;
     
     private static String toTag;
 
 
     private int port;
 
     protected SipProvider udpProvider;
 
   
     private static Logger logger = Logger.getLogger(Notifier.class) ;
 
     protected int notifyCount = 0;
 
 
 
    
     protected static final String usageString = "java "
             + "examples.shootist.Shootist \n"
             + ">>>> is your class path set to the root?";
 
     private static void usage() {
         .info();
         System.exit(0);
 
     }
 
     public void processRequest(RequestEvent requestEvent) {
         Request request = requestEvent.getRequest();
         ServerTransaction serverTransactionId = requestEvent
                 .getServerTransaction();
 
         .info("\n\nRequest " + request.getMethod()
                 + " received at " + .getStackName()
                 + " with server transaction id " + serverTransactionId
                 + " and dialog id " + requestEvent.getDialog() );
 
         if (request.getMethod().equals(.)) {
             processSubscribe(requestEventserverTransactionId);
         }
 
     }

    
Process the invite request.
 
     public void processSubscribe(RequestEvent requestEvent,
             ServerTransaction serverTransaction) {
         SipProvider sipProvider = (SipProviderrequestEvent.getSource();
         Request request = requestEvent.getRequest();
         try {
              .info("notifier:  " + request);
             .info("notifier : dialog = " + requestEvent.getDialog());
             EventHeader eventHeader = (EventHeaderrequest.getHeader(.);
             if ( eventHeader == null) {
                 .info("Cannot find event header.... dropping request.");
                 return;
             }
 
             // Always create a ServerTransaction, best as early as possible in the code
             Response response = null;
             ServerTransaction st = requestEvent.getServerTransaction();
             if (st == null) {
                 st = sipProvider.getNewServerTransaction(request);
             }
 
             // Check if it is an initial SUBSCRIBE or a refresh / unsubscribe
              = Integer.toHexString( (int) (Math.random() * .) );
             response = .createResponse(202, request);
             ToHeader toHeader = (ToHeaderresponse.getHeader(.);
             toHeader.setTag();
            // Sanity check: to header should not ahve a tag. Else the dialog
               
               
            
            // Both 2xx response to SUBSCRIBE and NOTIFY need a Contact
            Address address = .createAddress("Notifier <sip:127.0.0.1>");
            ((SipURI)address.getURI()).setPort.getListeningPoint("udp").getPort() );
            ContactHeader contactHeader = .createContactHeader(address);
            response.addHeader(contactHeader);
            // Expires header is mandatory in 2xx responses to SUBSCRIBE
            ExpiresHeader expires = (ExpiresHeaderrequest.getHeader. );
            if (expires==null) {
                expires = .createExpiresHeader(30);// rather short
            }
            response.addHeaderexpires );
         
            /*
             * NOTIFY requests MUST contain a "Subscription-State" header with a
             * value of "active", "pending", or "terminated". The "active" value
             * indicates that the subscription has been accepted and has been
             * authorized (in most cases; see section 5.2.). The "pending" value
             * indicates that the subscription has been received, but that
             * policy information is insufficient to accept or deny the
             * subscription at this time. The "terminated" value indicates that
             * the subscription is not active.
             */
            Dialog dialog = sipProvider.getNewDialog(st);
            
            Address toAddress = ((ResponseExt)response).getFromHeader().getAddress();
            String toTag = ((ResponseExt)response).getFromHeader().getTag();
            Address fromAddress = ((ResponseExtresponse).getToHeader().getAddress();
            String fromTag = ((ResponseExtresponse).getToHeader().getTag();
            FromHeader fromHeader = .createFromHeader(fromAddressfromTag);
            toHeader = .createToHeader(toAddresstoTag);
            // Create a new Cseq header
            CSeqHeader cSeqHeader = .createCSeqHeader(1L,
                    .);
            ArrayList viaHeaders = new ArrayList();
            String transport = "udp";
            int port = sipProvider.getListeningPoint(transport).getPort();
            ViaHeader viaHeader = .createViaHeader("127.0.0.1",
                    porttransportnull);
            // add via headers
            viaHeaders.add(viaHeader);
            
            MaxForwardsHeader maxForwards = .createMaxForwardsHeader(70);
            SipURI requestURI = .createSipURI(null"127.0.0.1");
            requestURI.setPort(5060);
            
            CallIdHeader callIdHeader = ((ResponseExt)response).getCallIdHeader();
            // Create the request.
            Request notifyRequest = .createRequest(requestURI,
                    .callIdHeadercSeqHeaderfromHeader,
                    toHeaderviaHeadersmaxForwards);
      
            
          
            // Mark the contact header, to check that the remote contact is updated
            ((SipURI)contactHeader.getAddress().getURI()).setParameter("id","not");
            // Initial state is pending, second time we assume terminated (Expires==0)
                    .  );
            // Need a reason for terminated
            if ( sstate.getState().equalsIgnoreCase("terminated") ) {
                sstate.setReasonCode"deactivated" );
            }
            notifyRequest.addHeader(sstate);
            notifyRequest.setHeader(eventHeader);
            notifyRequest.setHeader(contactHeader);
            // notifyRequest.setHeader(routeHeader);
            ClientTransaction ct = .getNewClientTransaction(notifyRequest);
            ct.sendRequest();
            .info("NOTIFY Branch ID " +
                ((ViaHeader)request.getHeader(.)).getParameter("branch"));
            .info("notifier: got an Subscribe sending OK");
            
             st.sendResponse(response);
             
               
          
        } catch (Throwable ex) {
            ex.printStackTrace();
            // System.exit(0);
        }
    }
    public synchronized void processResponse(ResponseEvent responseReceivedEvent) {
        Response response = (ResponseresponseReceivedEvent.getResponse();
        Transaction tid = responseReceivedEvent.getClientTransaction();
        if ( response.getStatusCode() !=  200 ) {
            this. --;
        } else {
            ..println("Notify Count = " + this.);
        }
    }
    public void processTimeout(javax.sip.TimeoutEvent timeoutEvent) {
        Transaction transaction;
        if (timeoutEvent.isServerTransaction()) {
            transaction = timeoutEvent.getServerTransaction();
        } else {
            transaction = timeoutEvent.getClientTransaction();
        }
        .info("state = " + transaction.getState());
        .info("dialog = " + transaction.getDialog());
        .info("dialogState = "
                + transaction.getDialog().getState());
        .info("Transaction Time out");
    }
    private static void initFactories ( int port ) throws Exception {
        SipFactory sipFactory = SipFactory.getInstance();
        sipFactory.setPathName("gov.nist");
        Properties properties = new Properties();
        .addAppender(new FileAppender
            ( new SimpleLayout(),"notifieroutputlog_" + port + ".txt" ));
        properties.setProperty("javax.sip.STACK_NAME""notifier" + 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",
                "notifierdebug_"+port+".txt");
        properties.setProperty("gov.nist.javax.sip.SERVER_LOG",
                "notifierlog_"+port+".txt");
        
        properties.setProperty("javax.sip.AUTOMATIC_DIALOG_SUPPORT""off");
        try {
            // Create SipStack object
             = sipFactory.createSipStack(properties);
            .info("sipStack = " + );
        } catch (PeerUnavailableException e) {
            // could not find
            // gov.nist.jain.protocol.ip.sip.SipStackImpl
            // in the classpath
            e.printStackTrace();
            ..println(e.getMessage());
            if (e.getCause() != null)
                e.getCause().printStackTrace();
            System.exit(0);
        }
        try {
             = sipFactory.createHeaderFactory();
             = sipFactory.createAddressFactory();
             = sipFactory.createMessageFactory();
        } catch  (Exception ex) {
            ex.printStackTrace();
            System.exit(0);
        }
    }
    public void createProvider() {
        try {
            ListeningPoint lp = .createListeningPoint("127.0.0.1",
                    this."udp");
            this. = .createSipProvider(lp);
            .info("udp provider " + );
        } catch (Exception ex) {
            .info(ex.getMessage());
            ex.printStackTrace();
            usage();
        }
    }
    public Notifierint port ) {
        this. = port;
    }
    public static Notifier createNotifier() throws Exception {
        int port = 5070;
        .addAppender(new ConsoleAppender(new SimpleLayout()));
        initFactoriesport );
        Notifier notifier = new Notifierport );
        notifier.createProvider( );
        notifier.udpProvider.addSipListener(notifier);
        return notifier;
    }
    public void processIOException(IOExceptionEvent exceptionEvent) {
    	
    	NotifyBefore202Test.fail("Unexpected IO Exception");
    }
    public void processTransactionTerminated(
            TransactionTerminatedEvent transactionTerminatedEvent) {
    }
    public void processDialogTerminated(
            DialogTerminatedEvent dialogTerminatedEvent) {
        // TODO Auto-generated method stub
    }
	public void tearDown() {
		this..stop();
	}
New to GrepCode? Check out our FAQ X