Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package test.unit.gov.nist.javax.sip.stack;
  
  import java.util.Random;
  
  import javax.sip.Dialog;
 
 import  junit.framework.TestCase;
 
 
 import  test.tck.msgflow.callflows.ScenarioHarness;
 
 public class CancelEventTest extends  ScenarioHarness {
 
     private static String transport = "udp";
     private static String unexpectedException = "Unexpected Exception ";
 
     private static String host = "127.0.0.1";
 
     private static int port = 6050;
 
     private static int peerPort = 6060;
 
     private static Logger logger = Logger.getLogger("test.tck");
 
     static {
         if (!.isAttached(console))
             .addAppender(console);
     }
 
     public CancelEventTest() {
         super("CanceEventTest",true);
     }
 
 
     class Shootist implements SipListener {
 
         private SipProvider sipProvider;
 
         private ContactHeader contactHeader;
 
         private ListeningPoint listeningPoint;
 
         private String peerHost = "127.0.0.1";
 
         private ClientTransaction inviteTid;
 
         private Dialog dialog;
 
         private boolean cancelOk = false;
         private boolean cancelSent = false;
         private boolean cancelTxTerm = false;
         private boolean inviteTxTerm = false;
         private boolean dialogTerminated = false;
 
 
 
         AddressFactory addressFactory;
 
         MessageFactory messageFactory;
 
         HeaderFactory headerFactory;
 
         SipStack sipStack;
 
         int logLevel = 32;
        String logFileDirectory = "logs/";
        Shootist() {
            SipFactory sipFactory = null;
            sipFactory = SipFactory.getInstance();
            sipFactory.setPathName("gov.nist");
            Properties properties = new Properties();
            // If you want to try TCP transport change the following to
            // If you want to use UDP then uncomment this.
            String stackname = "shootist";
            properties.setProperty("javax.sip.STACK_NAME"stackname);
            // The following properties are specific to nist-sip
            // and are not necessarily part of any other jain-sip
            // implementation.
            properties.setProperty("gov.nist.javax.sip.DEBUG_LOG",
                     + this.getClass().getName()  + ".debug.txt");
            properties.setProperty("gov.nist.javax.sip.SERVER_LOG",
                     + stackname + "log.txt");
            // 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",
                    new Integer().toString());
            try {
                // Create SipStack object
                 = sipFactory.createSipStack(properties);
                ..println("createSipStack " + );
            } catch (Exception e) {
                // could not find
                // gov.nist.jain.protocol.ip.sip.SipStackImpl
                // in the classpath
                e.printStackTrace();
                ..println(e.getMessage());
                throw new RuntimeException("Stack failed to initialize");
            }
            try {
                 = sipFactory.createHeaderFactory();
                 = sipFactory.createAddressFactory();
                 = sipFactory.createMessageFactory();
            } catch (SipException ex) {
                ex.printStackTrace();
                throw new RuntimeException(ex);
            }
        }
        public void destroy() {
            .stop();
        }
        public void start() throws Exception {
            .start();
        }
        public void processRequest(RequestEvent requestReceivedEvent) {
            Request request = requestReceivedEvent.getRequest();
            ServerTransaction serverTransactionId = requestReceivedEvent
                    .getServerTransaction();
            .info("\n\nRequest " + request.getMethod() + " received at "
                    + .getStackName() + " with server transaction id "
                    + serverTransactionId);
        }
        public void processResponse(ResponseEvent responseReceivedEvent) {
            Response response = (ResponseresponseReceivedEvent.getResponse();
            .info("Got a response"
                    + ((CSeqHeaderresponse.getHeader(.))
                            .getMethod());
            ClientTransaction tid = responseReceivedEvent
                    .getClientTransaction();
            CSeqHeader cseq = (CSeqHeaderresponse.getHeader(.);
            .info("Response received : Status Code = "
                    + response.getStatusCode() + " " + cseq);
            if (tid == null) {
                .info("Stray response -- dropping ");
                return;
            }
            .info("transaction state is " + tid.getState());
            .info("Dialog = " + tid.getDialog());
            .info("Dialog State is " + tid.getDialog().getState());
            if ( == null) {
                .info("SETTING DIALOG SINCE IT WAS NULL!!!!!!");
                 = tid.getDialog();
            }
            if (response.getStatusCode() == 180) {
                sendCancel();
            } else if (response.getStatusCode() == 200)// more checks?
            {
                 = true;
            } else {
                .info("Got weird response:" + response);
            }
        }
        public void processTimeout(javax.sip.TimeoutEvent timeoutEvent) {
            Transaction transaction = null;
            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");
            fail("Timeout Shouldnt happen on UAC side!!!");
        }
        private void sendCancel() {
            try {
                .info("Sending cancel");
                Request cancelRequest = .createCancel();
                ClientTransaction cancelTid = 
                        .getNewClientTransaction(cancelRequest);
                cancelTid.sendRequest();
                 = true;
            } catch (Exception ex) {
                ex.printStackTrace();
                .error(ex);
                fail();
            }
        }
        public SipProvider createSipProvider() {
            try {
                 = .createListeningPoint(,
                        );
                 = .createSipProvider();
                return ;
            } catch (Exception ex) {
                .error(ex);
                fail();
                return null;
            }
        }
        public void sendInvite() {
            String fromName = "BigGuy";
            // String fromSipAddress = "here.com";
            String fromDisplayName = "The Master Blaster";
            // String toSipAddress = "there.com";
            String toUser = "LittleGuy";
            String toDisplayName = "The Little Blister";
            String localAddress = .getListeningPoint("udp")
                    .getIPAddress();
            int localPort = .getListeningPoint("udp").getPort();
            String localTransport = .getListeningPoint("udp")
                    .getTransport();
            ContactHeader contactHeader = null;
            ToHeader toHeader = null;
            FromHeader fromHeader = null;
            CSeqHeader cseqHeader = null;
            ViaHeader viaHeader = null;
            CallIdHeader callIdHeader = null;
            MaxForwardsHeader maxForwardsHeader = null;
            ContentTypeHeader contentTypeHeader = null;
            RouteHeader routeHeader = null;
            // LETS CREATEOUR HEADERS
            try {
                cseqHeader = .createCSeqHeader(1L, .);
                viaHeader = .createViaHeader(localAddress,
                        localPortlocalTransportnull);
                Address fromAddres = 
                        .createAddress("sip:SimpleSIPPing@" + localAddress
                                + ":" + localPort);
                // Address
                // toAddress=addressFactory.createAddress("sip:pingReceiver@"+peerAddres+":"+peerPort);
                Address toAddress = .createAddress("sip:"
                        + this. + ":" + );
                contactHeader = .createContactHeader(fromAddres);
                toHeader = .createToHeader(toAddressnull);
                fromHeader = .createFromHeader(fromAddres, Integer
                        .toString(new Random().nextInt()));
                callIdHeader = .getNewCallId();
                maxForwardsHeader = .createMaxForwardsHeader(70);
                contentTypeHeader = .createContentTypeHeader(
                        "text""plain");
                Address routeAddress = .createAddress("sip:"
                        + this. + ":" + );
                routeHeader = .createRouteHeader(routeAddress);
                // LETS CREATE OUR REQUEST AND
                ArrayList list = new ArrayList();
                list.add(viaHeader);
                URI requestURI = null;
                Request request = null;
                Request cancel = null;
                Request inviteRequest = null;
                requestURI = .createURI("sip:" + localAddress);
                inviteRequest = request = .createRequest(
                        requestURI.callIdHeadercseqHeader,
                        fromHeadertoHeaderlistmaxForwardsHeader,
                        contentTypeHeader"CANCEL".getBytes());
                request.addHeader(routeHeader);
                request.addHeader(contactHeader);
                // ClientTransaction CTInvite = null;
                // ClientTransaction CTCancel = null;
                 = .getNewClientTransaction(request);
                .sendRequest();
                 = .getDialog();
                .info("SET DIALOG TO[" +  + "]");
            } catch (Exception e) {
                .error("Unexpected exception"e);
                fail("Unexpected exception");
            }
        }
        public void processIOException(IOExceptionEvent exceptionEvent) {
            .info("Got an IO Exception");
            fail("unexpected event");
        }
        public void processTransactionTerminated(
                TransactionTerminatedEvent transactionTerminatedEvent) {
            if (!transactionTerminatedEvent.isServerTransaction()) {
                ClientTransaction clientTx = transactionTerminatedEvent
                        .getClientTransaction();
                String method = clientTx.getRequest().getMethod();
                .info("Server Tx : " + method + " terminated ");
                if (method.equals("INVITE")) {
                     = true;
                } else if (method.equals("CANCEL")) {
                     = true;
                } else {
                    fail("Unexpected transaction has ended!!![" + method + "]");
                }
            }
        }
        public void processDialogTerminated(
                DialogTerminatedEvent dialogTerminatedEvent) {
            .info("Got a dialog terminated event");
            if ( == dialogTerminatedEvent.getDialog()) {
                .info("Dialog matches dialog created before");
                 = true;
            }
        }
        public boolean conditionMet() {
            ..println("cancelOK = " + );
            ..println("cancelTerm = " + );
            ..println("inviteTxTerm = " + );
            ..println("dialogTerminated = " + );
            return  &&  &&  && ;
        }
        public String[] conditionsState() {
            String[] result = new String[5];
            result[0] = "[" +  + "] - OK received for CANCEL Req";
            result[1] = "[" +  + "] - CANCEL STX terminated";
            result[2] = "[" +  + "] - INVITE STX terminated";
            // echhh
            String state = null;
            if ( == null)
                state = "DIALOG IS NULL";
            else
                state = .getState().toString();
            result[3] = "[" +  + "] - Dialog terminated state["
                    + state + "]";
            result[4] = "[" +  + "] - CANCEL sent";
            return result;
        }
    }
    class Shootme  implements SipListener {
        private static final String myAddress = "127.0.0.1";
        private int myPort = ;
        private ServerTransaction inviteTid;
        private SipProvider sipProvider;
        private Dialog dialog;
        private boolean cancelOk = false;
        private boolean cancelTxTerm = false;
        private boolean inviteTxTerm = false;
        private boolean dialogTerminated = false;
        private int dteCount = 0;
        private static final String unexpectedException = "Unexpected Exception ";
        SipStack sipStack;
        int logLevel = 32;
        String logFileDirectory = "logs/";
		private boolean dialogOnCancelTx = true;
        Shootme () {
            SipFactory sipFactory = null;
            String stackname = "shootme";
            sipFactory = SipFactory.getInstance();
            sipFactory.setPathName("gov.nist");
            Properties properties = new Properties();
            // If you want to try TCP transport change the following to
            // If you want to use UDP then uncomment this.
            properties.setProperty("javax.sip.STACK_NAME"stackname);
            // The following properties are specific to nist-sip
            // and are not necessarily part of any other jain-sip
            // implementation.
            properties.setProperty("gov.nist.javax.sip.DEBUG_LOG",
                     + this.getClass().getName() + ".debug.txt");
            properties.setProperty("gov.nist.javax.sip.SERVER_LOG",
                     + stackname + "log.txt");
            // 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",
                    new Integer().toString());
            try {
                // Create SipStack object
                 = sipFactory.createSipStack(properties);
                ..println("createSipStack " + );
            } catch (Exception e) {
                // could not find
                // gov.nist.jain.protocol.ip.sip.SipStackImpl
                // in the classpath
                e.printStackTrace();
                ..println(e.getMessage());
                throw new RuntimeException("Stack failed to initialize");
            }
            try {
                 = sipFactory.createHeaderFactory();
                 = sipFactory.createAddressFactory();
                 = sipFactory.createMessageFactory();
            } catch (SipException ex) {
                ex.printStackTrace();
                throw new RuntimeException(ex);
            }
        }
        public void destroy() {
            .stop();
        }
        public void start() throws Exception {
            .start();
        }
        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);
            if (request.getMethod().equals(.)) {
                processInvite(requestEventserverTransactionId);
            } else if (request.getMethod().equals(.)) {
                processCancel(requestEventserverTransactionId);
            }
        }
        public void processResponse(ResponseEvent responseEvent) {
        }

        
Process the invite request.
        public void processInvite(RequestEvent requestEvent,
                ServerTransaction serverTransaction) {
            SipProvider sipProvider = (SipProviderrequestEvent.getSource();
            Request request = requestEvent.getRequest();
            try {
                .info("shootme: got an Invite sending RINGING");
                // logger.info("shootme: " + request);
                Response response = .createResponse(180, request);
                ToHeader toHeader = (ToHeaderresponse
                        .getHeader(.);
                toHeader.setTag("4321"); // Application is supposed to set.
                Address address = .createAddress("Shootme <sip:"
                        +  + ":" +  + ">");
                ContactHeader contactHeader = 
                        .createContactHeader(address);
                response.addHeader(contactHeader);
                ServerTransaction st = requestEvent.getServerTransaction();
                if (st == null) {
                    st = sipProvider.getNewServerTransaction(request);
                    .info("Created a new server transaction for "
                            + request.getMethod() + " serverTransaction = "
                            + st);
                }
                 = st;
                 = st.getDialog();
                st.sendResponse(response);
            } catch (Exception ex) {
                .error(ex);
                fail();
            }
        }
        public void processCancel(RequestEvent requestEvent,
                ServerTransaction serverTransactionId) {
            Request request = requestEvent.getRequest();
            try {
                .info("shootme:  got a cancel.");
                if (serverTransactionId == null) {
                    .info("shootme:  null tid.");
                    return;
                }
                TestCase.assertTrue( != serverTransactionId);
                Response response = .createResponse(200, request);
                serverTransactionId.sendResponse(response);
                Request inviteRequest = .getRequest();
                if (.getState() != .) {
                    response = .createResponse(
                            .inviteRequest);
                    .sendResponse(response);
                }
                 = true;
                if(serverTransactionId.getDialog() == null) {
                	 = false;
                }
            } catch (Exception ex) {
                // logger.error(ex);
                ex.printStackTrace();
                fail();
            }
        }
        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");
            fail("Timeout Shouldnt happen on UAS side!!!");
        }
        public SipProvider createProvider() {
            try {
                ListeningPoint lp = .createListeningPoint(,
                        );
                 = .createSipProvider(lp);
                .info("udp provider " + );
                return ;
            } catch (Exception ex) {
                .error(ex);
                fail();
                return null;
            }
        }
        public void processIOException(IOExceptionEvent exceptionEvent) {
            // TODO Auto-generated method stub
        }
        public void processTransactionTerminated(
                TransactionTerminatedEvent transactionTerminatedEvent) {
            if (transactionTerminatedEvent.isServerTransaction()) {
                ServerTransaction serverTx = transactionTerminatedEvent
                        .getServerTransaction();
                String method = serverTx.getRequest().getMethod();
                .info("Server Tx : " + method + " terminated ");
                if (method.equals("INVITE")) {
                     = true;
                } else if (method.equals("CANCEL")) {
                     = true;
                } else {
                    fail("Unexpected transaction has ended!!![" + method + "]");
                }
            }
        }
        public void processDialogTerminated(
                DialogTerminatedEvent dialogTerminatedEvent) {
             = true;
            ++;
        }
        public boolean conditionMet() {
             ..println("cancelOK = " + );
             ..println("cancelTerm = " + );
             ..println("inviteTxTerm = " + );
             ..println("dialogTerminated = " + );
             ..println("dialogOnCancelTx = " + );
             return  &&  &&  &&  && ;
        }
        public String[] conditionsState() {
            String[] result = new String[4];
            result[0] = "[" +  + "] - OK sent for CANCEL Req";
            result[1] = "[" +  + "] - CANCEL STX terminated";
            result[2] = "[" +  + "] - INVITE STX terminated";
            // echhh
            String state = null;
            if ( == null)
                state = "DIALOG IS NULL";
            else
                state = .getState().toString();
            result[3] = "[" +  + "] - Dialog terminated state["
                    + state + "] count [" +  + "]";
            return result;
        }
    }
    public void setUp() throws Exception {
         = new Shootist();
        .createSipProvider();
         = new Shootme();
        .createProvider();
    }
    public void testCancelEvent() throws Exception {
        .sendInvite();
        Thread.sleep(40000);
        assertTrue ( .conditionMet());
        assertTrue ( .conditionMet());
    }
    public void tearDown() {
        .destroy();
        .destroy();
    }
New to GrepCode? Check out our FAQ X