Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package test.unit.gov.nist.javax.sip.stack;
  
  
  import javax.sip.Dialog;
 
 import  junit.framework.TestCase;
 
 
 public class DeliverNotifyBefore202Test extends TestCase {
     private static Logger logger = Logger.getLogger(DeliverNotifyBefore202Test.class);
     private static AddressFactory addressFactory;
 
     private static MessageFactory messageFactory;
 
     private static HeaderFactory headerFactory;
     private static SipFactory sipFactory;
 
     private Notifier notifier;
     private Subscriber subscriber;
    
     
     static {
         try {
              = SipFactory.getInstance();
             .setPathName("gov.nist");
             .setLevel(.);
             .addAppender(new ConsoleAppender(new SimpleLayout()));
             .addAppender(new FileAppender(new SimpleLayout(), "subscriberoutputlog.txt"));
 
           
             .setPathName("gov.nist");
              = .createHeaderFactory();
              = .createAddressFactory();
              = .createMessageFactory();
 
         } catch (Exception ex) {
             throw new RuntimeException(ex);
         }
 
     }

    
The Subscriber.
 
 
     class Subscriber implements SipListener {
 
         private SipProvider udpProvider;
 
         private SipStack sipStack;
 
         private ContactHeader contactHeader;
 
         private int notifierPort;
 
         private String transport = "udp";
 
         private int count;
 
        
        private ClientTransaction subscribeTid;
        private ListeningPoint listeningPoint;
        private int port;
        private boolean notifySeen;
        public void processRequest(RequestEvent requestReceivedEvent) {
            Request request = requestReceivedEvent.getRequest();
            ServerTransaction serverTransactionId = requestReceivedEvent.getServerTransaction();
            String viaBranch = ((ViaHeader) (request.getHeaders(.).next()))
                    .getParameter("branch");
            .info("\n\nRequest " + request.getMethod() + " received at "
                    + .getStackName() + " with server transaction id "
                    + serverTransactionId + " branch ID = " + viaBranch);
            if (request.getMethod().equals(.))
                processNotify(requestReceivedEventserverTransactionId);
        }
        public synchronized void processNotify(RequestEvent requestEvent,
                ServerTransaction serverTransactionId) {
            SipProvider provider = (SipProviderrequestEvent.getSource();
            Request notify = requestEvent.getRequest();
            try {
                .info("subscriber:  got a notify count  " + this.++);
                if (serverTransactionId == null) {
                    .info("subscriber:  null TID.");
                    serverTransactionId = provider.getNewServerTransaction(notify);
                }
                Dialog dialog = serverTransactionId.getDialog();
                .info("Dialog = " + dialog);
                if (dialog != null) {
                    .info("Dialog State = " + dialog.getState());
                }
                Response response = .createResponse(200, notify);
                // SHOULD add a Contact
                ContactHeader contact = (ContactHeader.clone();
                ((SipURIcontact.getAddress().getURI()).setParameter("id""sub");
                response.addHeader(contact);
                .info("Transaction State = " + serverTransactionId.getState());
                serverTransactionId.sendResponse(response);
                if (dialog != null) {
                    .info("Dialog State = " + dialog.getState());
                }
                SubscriptionStateHeader subscriptionState = (SubscriptionStateHeadernotify
                        .getHeader(.);
                // Subscription is terminated?
                String state = subscriptionState.getState();
                if (state.equalsIgnoreCase(.)) {
                    dialog.delete();
                } else {
                    .info("Subscriber: state now " + state);
                }
                this. = true;
            } catch (Exception ex) {
                ex.printStackTrace();
                .error("Unexpected exception"ex);
                fail("Unexpected exception");
            }
        }
        public void processResponse(ResponseEvent responseReceivedEvent) {
            .info("Got a response");
            Response response = (ResponseresponseReceivedEvent.getResponse();
            Transaction tid = responseReceivedEvent.getClientTransaction();
            .info("Response received with client transaction id " + tid + ":\n"
                    + response.getStatusCode());
            if (tid == null) {
                .info("Stray response -- dropping ");
                return;
            }
            .info("transaction state is " + tid.getState());
            .info("Dialog = " + tid.getDialog());
            if (tid.getDialog() != null)
                .info("Dialog State is " + tid.getDialog().getState());
        }
        public void createProvider() throws Exception {
            this. = .createListeningPoint("127.0.0.1");
        }
        public void sendSubscribe() {
            try {
                String fromName = "BigGuy";
                String fromSipAddress = "here.com";
                String fromDisplayName = "The Master Blaster";
                String toSipAddress = "there.com";
                String toUser = "LittleGuy";
                String toDisplayName = "The Little Blister";
                // create >From Header
                SipURI fromAddress = .createSipURI(fromNamefromSipAddress);
                Address fromNameAddress = .createAddress(fromAddress);
                fromNameAddress.setDisplayName(fromDisplayName);
                FromHeader fromHeader = .createFromHeader(fromNameAddress"12345");
                // create To Header
                SipURI toAddress = .createSipURI(toUsertoSipAddress);
                Address toNameAddress = .createAddress(toAddress);
                toNameAddress.setDisplayName(toDisplayName);
                ToHeader toHeader = .createToHeader(toNameAddressnull);
                // create Request URI
                SipURI requestURI = .createSipURI(toUsertoSipAddress);
                // Create ViaHeaders
                ArrayList viaHeaders = new ArrayList();
                int port = .getListeningPoint().getPort();
                ViaHeader viaHeader = .createViaHeader("127.0.0.1"port,
                        null);
                // add via headers
                viaHeaders.add(viaHeader);
                // Create a new CallId header
                CallIdHeader callIdHeader = .getNewCallId();
                // Create a new Cseq header
                CSeqHeader cSeqHeader = .createCSeqHeader(1L, .);
                // Create a new MaxForwardsHeader
                MaxForwardsHeader maxForwards = .createMaxForwardsHeader(70);
                // Create the request.
                Request request = .createRequest(requestURI.,
                        callIdHeadercSeqHeaderfromHeadertoHeaderviaHeadersmaxForwards);
                // Create contact headers
                String host = .getIPAddress();
                SipURI contactUrl = .createSipURI(fromNamehost);
                contactUrl.setPort(.getPort());
                // Create the contact name address.
                SipURI contactURI = .createSipURI(fromNamehost);
                contactURI.setTransportParam();
                contactURI.setPort(.getListeningPoint().getPort());
                Address contactAddress = .createAddress(contactURI);
                // Add the contact address.
                contactAddress.setDisplayName(fromName);
                 = .createContactHeader(contactAddress);
                request.addHeader();
                // JvB: To test forked SUBSCRIBEs, send it via the Forker
                // Note: BIG Gotcha: Need to do this before creating the
                // ClientTransaction!
                RouteHeader route = .createRouteHeader(
                        .createAddress("<sip:127.0.0.1:" +  + ";transport="
                                +  + ";lr>"));
                request.addHeader(route);
                // JvB end added
                // Create the client transaction.
                 = .getNewClientTransaction(request);
                // Create an event header for the subscription.
                EventHeader eventHeader = .createEventHeader("foo");
                eventHeader.setEventId("foo");
                request.addHeader(eventHeader);
                .info("Subscribe Dialog = " + .getDialog());
                
                // send the request out.
                .sendRequest();
            } catch (Throwable ex) {
                .info(ex.getMessage());
                ex.printStackTrace();
                fail("Unexpected exception");
            }
        }
        public void processIOException(IOExceptionEvent exceptionEvent) {
            .info("io exception event recieved");
            fail ("unexpected event -- IOException");
        }
        public void processTransactionTerminated(
                TransactionTerminatedEvent transactionTerminatedEvent) {
        }
        public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) {
            .info("dialog terminated event    recieved");
        }
        public void processTimeout(javax.sip.TimeoutEvent timeoutEvent) {
            .info("Transaction Time out");
            fail ("Unexpected event -- timeout");
        }
        
        public Subscriber(int notifierPortint portthrows Exception {
            this. = notifierPort;
            this. = port;
            .addAppender(new FileAppender(new SimpleLayout(), "subscriberoutputlog_" + port
                    + ".txt"));
            
            Properties properties = new Properties();
            properties.setProperty("javax.sip.STACK_NAME""subscriber" + 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""subscriberdebug_" + port
                    + ".txt");
            properties.setProperty("gov.nist.javax.sip.SERVER_LOG""subscriberlog_" + port
                    + ".txt");
            // Create SipStack object
             = .createSipStack(properties);
            .info("sipStack = " + );
            this.createProvider( );
            this..addSipListener(this);
            
        }
        
        public void tearDown() {
            this..stop();
        }
        public boolean checkNotify() {
             return this.;
        }
    }

    
The Notifier
    class Notifier implements SipListener {
        private SipStack sipStack;
        private int port;
        private SipProvider udpProvider;
        private Dialog dialog;
        protected int notifyCount = 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: got an Subscribe sending OK");
                .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
                boolean isInitial = requestEvent.getDialog() == null;
                if (isInitial) {
                    // JvB: need random tags to test forking
                    String toTag = Integer.toHexString((int) (Math.random() * .));
                    response = .createResponse(202, request);
                    ToHeader toHeader = (ToHeaderresponse.getHeader(.);
                    // Sanity check: to header should not ahve a tag. Else the dialog
                    // should have matched
                    if (toHeader.getTag() != null) {
                        .
                                .println("####ERROR: To-tag!=null but no dialog match! My dialog="
                                        + .getState());
                    }
                    toHeader.setTag(toTag); // Application is supposed to set.
                    this. = st.getDialog();
                    // subscribe dialogs do not terminate on bye.
                    this..terminateOnBye(false);
                    if ( != null) {
                        .info("Dialog " + );
                        .info("Dialog state " + .getState());
                    }
                } else {
                    response = .createResponse(200, request);
                }
                // Both 2xx response to SUBSCRIBE and NOTIFY need a Contact
                Address address = .createAddress("Notifier <sip:127.0.0.1>");
                ((SipURIaddress.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.addHeader(expires);
                /*
                 * 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.
                 */
                Address fromAddress = ((ToHeaderresponse.getHeader(.)).getAddress();
                String fromTag = ((ToHeaderresponse.getHeader(.)).getTag();
                FromHeader fromHeader = .createFromHeader(fromAddressfromTag);
                
                Address toAddress = ((FromHeaderresponse.getHeader(.)).getAddress();
                String toTag = ((FromHeaderresponse.getHeader(.)).getTag();
                ToHeader toHeader = .createToHeader(toAddresstoTag);
                
                
                
                CallIdHeader callId = (CallIdHeaderresponse.getHeader(.);
                ContactHeader requestContact = (ContactHeaderrequest
                        .getHeader(.);
                SipURI notifyRuri = (SipURIrequestContact.getAddress().getURI();
                CSeqHeader cSeq = .createCSeqHeader(1L, .);
                String ipAddress = sipProvider.getListeningPoint("udp").getIPAddress();
                int port = sipProvider.getListeningPoint("udp").getPort();
                ViaHeader viaHeader = .createViaHeader(ipAddressport"udp"null);
                LinkedList llist = new LinkedList<ViaHeader>();
                llist.add(viaHeader);
                MaxForwardsHeader maxForwards = .createMaxForwardsHeader(70);
                Request notifyRequest = .createRequest(notifyRuri.,
                        callIdcSeqfromHeadertoHeaderllistmaxForwards);
                notifyRequest.addHeader(contactHeader);
                // Mark the contact header, to check that the remote contact is updated
                ((SipURIcontactHeader.getAddress().getURI()).setParameter("id""not");
                // Initial state is pending, second time we assume terminated (Expires==0)
                SubscriptionStateHeader sstate = 
                        .createSubscriptionStateHeader(isInitial ? .
                                : .);
                // 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);
                /*
                 * We deliberately send the NOTIFY first before the 202 is sent.
                 */
                ct.sendRequest();
                .info("NOTIFY Branch ID "
                        + ((ViaHeaderrequest.getHeader(.)).getParameter("branch"));
                .info("Dialog " + );
                .info("Dialog state after pending NOTIFY: " + .getState());
                /*
                 * Now send the NOTIFY.
                 */
                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");
        }
        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();
            }
        }
        public Notifier(int portthrows Exception {
            this. = port;
            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");
            // Create SipStack object
             = .createSipStack(properties);
            .info("sipStack = " + );
            this.createProvider( );
            this..addSipListener(this);
        }
        public void processIOException(IOExceptionEvent exceptionEvent) {
        }
        public void processTransactionTerminated(
                TransactionTerminatedEvent transactionTerminatedEvent) {
        }
        public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) {
            // TODO Auto-generated method stub
        }
        
        public void tearDown() {
            this..stop();
        }
    }
     
    public void setUp() throws Exception  {
        this. = new Notifier(5090);
        this. = new Subscriber(5090,5092);
        
    }
    public void testDeliverNotifyBefore202() {
        this..sendSubscribe();
        try {
           Thread.sleep(2000);
        } catch (Exception ex) {
            
        }
        if ( ! this..checkNotify() ) {
            fail("Notify not received");
        }
    }
    
    public void tearDown() {
        this..tearDown();
        this..tearDown();
    }
New to GrepCode? Check out our FAQ X