Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
  * Conditions Of Use
  *
  * This software was developed by employees of the National Institute of
  * Standards and Technology (NIST), and others.
  * This software is has been contributed to the public domain.
  * As a result, a formal license is not needed to use the software.
  *
  * This software is provided "AS IS."
 * NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
 * OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
 * AND DATA ACCURACY.  NIST does not warrant or make any representations
 * regarding the use of the software or the results thereof, including but
 * not limited to the correctness, accuracy, reliability or usefulness of
 * the software.
 *
 *
 */
 package test.tck.msgflow.callflows.subsnotify;
 
 import javax.sip.*;
 
 
 
 import java.util.*;

This class is a Subscriber template. The subscriber handles upstream forking by a proxy server. The stack is set up to expect forking of this event type. The test checks that exactly two distinct dialogs are created. This code is released to domain.

Author(s):
M. Ranganathan
 
 
 public class Subscriber implements SipListener {
 
     private SipProvider sipProvider;
 
     private static AddressFactory addressFactory;
 
     private static MessageFactory messageFactory;
 
     private static HeaderFactory headerFactory;
 
     private static SipStack sipStack;
 
     private ContactHeader contactHeader;
 
     private static String transport;
 
     private int count;
 
     private HashSet dialogs;
 
     private static Logger logger = Logger.getLogger(Subscriber.class);
 
     static {
         try {
             .setLevel(.);
             .addAppender(new FileAppender(new SimpleLayout(),
                     "logs/subscriberoutputlog.txt"));
         } catch (Exception ex) {
             .info(ex.getMessage(), ex);
             TestHarness.fail("Failed to initialize Subscriber, because of " + ex.getMessage());
         }
     }
 
     private ClientTransaction subscribeTid;
 
     private ListeningPoint listeningPoint;
 
     private int port;
 
     private Dialog subscriberDialog;
 
     private Dialog forkedDialog;
 
     public Subscriber(ProtocolObjects protObjects) {
          = protObjects.addressFactory;
          = protObjects.messageFactory;
          = protObjects.headerFactory;
          = protObjects.sipStack;
          = protObjects.transport;
         this. = new HashSet();
     }
 
    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 void processNotify(RequestEvent requestEvent,
            ServerTransaction serverTransactionId) {
        SipProvider provider = (SipProviderrequestEvent.getSource();
        AbstractSubsnotifyTestCase.assertTrue("provider must be the same as my provider "provider == this.);
        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();
            AbstractSubsnotifyTestCase.assertTrue("subscriberDialog" != null);
            AbstractSubsnotifyTestCase.assertTrue("Dialog should not be null"dialog != null);
            if ( dialog !=  ) {
                if ( == null) {
                     = dialog;
                } else  {
                    AbstractSubsnotifyTestCase.assertTrue("Dialog should be either the subscriber dialog ",
                              == dialog);
                }
            }
            this..add(dialog);
            .info("Dialog State = " + dialog.getState());
            AbstractSubsnotifyTestCase.assertTrue("Dialog state should be confirmed "dialog.getState() == .);
            Response response = .createResponse(200, notify);
            // SHOULD add a Contact
            ContactHeader contact = (ContactHeader.clone();
            ((SipURI)contact.getAddress().getURI()).setParameter"id""sub" );
            response.addHeadercontact );
            .info("Transaction State = " + serverTransactionId.getState());
            AbstractSubsnotifyTestCase.assertTrue("transaction state should be trying",
                    serverTransactionId.getState() == .);
            serverTransactionId.sendResponse(response);
            .info("Dialog State = " + dialog.getState());
            SubscriptionStateHeader subscriptionState = (SubscriptionStateHeadernotify
                    .getHeader(.);
            // Subscription is terminated?
            String state = subscriptionState.getState();
            if (state.equalsIgnoreCase(.)) {
                dialog.delete();
            } else if (state.equalsIgnoreCase(.)) {
                .info("Subscriber: sending unSUBSCRIBE");
                // Else we end it ourselves
                Request unsubscribe = dialog.createRequest(.);
                .info"dialog created:" + unsubscribe );
                // SHOULD add a Contact (done by dialog), lets mark it to test updates
                ((SipURIdialog.getLocalParty().getURI()).setParameter"id""unsub" );
                ExpiresHeader expires = .createExpiresHeader(0);
                unsubscribe.addHeader(expires);
                // JvB note : stack should do this!
                unsubscribe.addHeader(notify.getHeader(.)); // copy
                                            // event
                                            // header
                .info("Sending Unsubscribe : " + unsubscribe);
                .info("unsubscribe dialog  " + dialog);
                ClientTransaction ct = .getNewClientTransaction(unsubscribe);
                AbstractSubsnotifyTestCase.assertTrue"Dialog mismatch " + ct.getDialog() + " dialog " + dialogct.getDialog() == dialog );
                dialog.sendRequest(ct);
            } else {
                .info("Subscriber: state now " + state);// pending
                // usually
                AbstractSubsnotifyTestCase.assertTrue("State should be pending was "
                        + statestate.equalsIgnoreCase(. ));
            }
        } catch (Exception ex) {
            .error("Unexpected exception",ex);
            TestHarness.fail("Failed to process Notify, because of " + ex.getMessage());
        }
    }
    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) {
            .warn("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());
        if ( tid.getDialog() != null ) this..add(tid.getDialog());
    }
    public SipProvider createProvider(int newPort) {
        try {
             = newPort;
             = .createListeningPoint("127.0.0.1",
                    this.);
            this. = .createSipProvider();
            this..setAutomaticDialogSupportEnabled(true);
            .info("udp provider " + );
        } catch (Exception ex) {
            .info(ex.getMessage(), ex);
            TestHarness.fail("Failed to create SIP Provider on port " + newPort + ", because of " + ex.getMessage());
             = null;
        }
        return ;
    }

    
when notifierPort is 5065, sends subscription to the forker. when notifierPort is 5070, sends subscription directly to the notifier.

Parameters:
notifierPort
    public void sendSubscribe(int notifierPort) {
        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(fromName,
                    fromSipAddress);
            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(toNameAddress,
                    null);
            // create Request URI
            SipURI requestURI = .createSipURI(toUser,
                    toSipAddress);
            // Create ViaHeaders
            ArrayList viaHeaders = new ArrayList();
            int port = .getListeningPoint().getPort();
            ViaHeader viaHeader = .createViaHeader("127.0.0.1",
                    portnull);
            // add via headers
            viaHeaders.add(viaHeader);
            // Create a new CallId header
            CallIdHeader callIdHeader = .getNewCallId();
            // JvB: Make sure that the implementation matches the messagefactory
            callIdHeader = .createCallIdHeadercallIdHeader.getCallId() );
            // Create a new Cseq header
            CSeqHeader cSeqHeader = .createCSeqHeader(1L,
                    .);
            // Create a new MaxForwardsHeader
            MaxForwardsHeader maxForwards = 
                    .createMaxForwardsHeader(70);
            // Create the request.
            Request request = .createRequest(requestURI,
                    .callIdHeadercSeqHeaderfromHeader,
                    toHeaderviaHeadersmaxForwards);
            // 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!
                    .createAddress("<sip:127.0.0.1:" + notifierPort
                            + ";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.
            this. = .getDialog();
            this..add();
            .sendRequest();
            } catch (Throwable ex) {
            .info(ex.getMessage(), ex);
            TestHarness.fail("Failed to send Subscribe to notifier port" + notifierPort + ", because of " + ex.getMessage());
        }
    }
    public void processIOException(IOExceptionEvent exceptionEvent) {
        .info("io exception event recieved");
    }
    public void processTransactionTerminated(
            TransactionTerminatedEvent transactionTerminatedEvent) {
        .info("transaction terminated");
    }
    public void processDialogTerminated(
            DialogTerminatedEvent dialogTerminatedEvent) {
        .info("dialog terminated event recieved");
    }
    public void processTimeout(javax.sip.TimeoutEvent timeoutEvent) {
        .info("Transaction Time out");
    }
    public void checkState() {
        // AbstractSubsnotifyTestCase.assertTrue("Should have two distinct dialogs", this.dialogs.size() == 2);
    }
New to GrepCode? Check out our FAQ X