Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package examples.reinvite;
  
  
  import javax.sip.*;
  import javax.sip.header.*;
  
 
 import java.util.*;
 
 import  junit.framework.TestCase;

This class is a UAC template. Shootist is the guy that shoots and shootme is the guy that gets shot.

Author(s):
M. Ranganathan
 
 
 public class Shootist  implements SipListener {
 
     private boolean reInviteFlag;
 
     private SipProvider provider;
 
     private int reInviteCount;
 
     private ContactHeader contactHeader;
 
     private ListeningPoint listeningPoint;
 
     private int counter;
 
     private static String PEER_ADDRESS = .;
 
     private static int PEER_PORT = .;
 
     private static String peerHostPort =  + ":" + ;
 
     // To run on two machines change these to suit.
     public static final String myAddress = "127.0.0.1";
 
     private static final int myPort = 5060;
 
     protected ClientTransaction inviteTid;
 
     private boolean okReceived;
 
     private Dialog dialog;
 
     protected static final String usageString = "java "
             + "examples.shootist.Shootist \n"
             + ">>>> is your class path set to the root?";
 
     private static Logger logger = Logger.getLogger(Shootist.class);
 
     static {
         try {
             .addAppender(new FileAppender(new SimpleLayout(),
                     . + "shootistconsolelog.txt"));
         } catch (Exception ex) {
             throw new RuntimeException("could not open shootistconsolelog.txt");
         }
     }
 
     private static void usage() {
         .info();
         System.exit(0);
 
     }
 
     public Shootist(int count) {
         this. = count;
     }
 
     private void shutDownAndRestart() {
         try {
 
             .info("nulling reference");
             checkState();
             // This will close down the stack and exit all threads
             .removeSipListener(this);
             while (true) {
                 try {
                     ..deleteSipProvider();
 
                     break;
                 } catch (ObjectInUseException ex) {
                     try {
                         Thread.sleep(2000);
                     } catch (InterruptedException e) {
                        continue;
                    }
                }
            }
            ..stop();
             = null;
             = null;
             = null;
            this. = null;
            this. = 0;
            SipProvider sipProvider = this.createSipProvider();
            sipProvider.addSipListener(this);
            ..start();
            // Redo this from the start.
            ProtocolObjects.init("shootist"true);
            this.sendInvite();
        } catch (Exception ex) {
            .error(ex);
            System.exit(0);
        }
    }
    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);
        if (request.getMethod().equals(.))
            processBye(requestserverTransactionId);
        else if (request.getMethod().equals(.))
            processInvite(requestserverTransactionId);
        else if (request.getMethod().equals(.))
            processAck(requestserverTransactionId);
    }

    
Handle an incoming INVITE request.

Parameters:
request -- request to process
st -- server tx associated with the request.
    public void processInvite(Request requestServerTransaction st) {
        try {
            ..println("Processing Re-INVITE ");
            Response response = ..createResponse(
                    .request);
            ((ToHeaderresponse.getHeader(.))
                    .setTag(((ToHeaderrequest.getHeader(.))
                            .getTag());
            response.addHeader(this.);
            st.sendResponse(response);
            TestCase.assertEquals("Re-Inivte Dialog must match "this.,st.getDialog() );
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(0);
        }
    }

    
Handle an incoming ACK.

Parameters:
request
tid
    public void processAck(Request requestServerTransaction tid) {
        try {
            .info("Got an ACK! sending bye : " + tid);
            if (tid != null) {
                Dialog dialog = tid.getDialog();
                TestCase.assertSame("Dialog mismatch",dialogthis.);
                Request bye = dialog.createRequest(.);
                .info("bye request = " + bye);
                MaxForwardsHeader mf = .
                        .createMaxForwardsHeader(10);
                bye.addHeader(mf);
                ClientTransaction ct = .getNewClientTransaction(bye);
                dialog.sendRequest(ct);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(0);
        }
    }
    public void processBye(Request request,
            ServerTransaction serverTransactionId) {
        try {
            .info("shootist:  got a bye .");
            if (serverTransactionId == null) {
                .info("shootist:  null TID.");
                return;
            }
            Dialog dialog = serverTransactionId.getDialog();
            .info("Dialog State = " + dialog.getState());
            Response response = ..createResponse(
                    200, request);
            serverTransactionId.sendResponse(response);
            .info("shootist:  Sending OK.");
            .info("Dialog State = " + dialog.getState());
            if (-- > 0)
                this.shutDownAndRestart();
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(0);
        }
    }
    /*
     * (non-Javadoc)
     * @see javax.sip.SipListener#processResponse(javax.sip.ResponseEvent)
     */
    public void processResponse(ResponseEvent responseReceivedEvent) {
        .info("Got a response");
        Response response = (ResponseresponseReceivedEvent.getResponse();
        Transaction tid = responseReceivedEvent.getClientTransaction();
        CSeqHeader cseq = (CSeqHeaderresponse.getHeader(.);
        .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());
        .info("Dialog State is " + tid.getDialog().getState());
        try {
            if (response.getStatusCode() == .
                    && ((CSeqHeaderresponse.getHeader(.))
                            .getMethod().equals(.)) {
                // Request cancel = inviteTid.createCancel();
                // ClientTransaction ct =
                // sipProvider.getNewClientTransaction(cancel);
                Dialog dialog = tid.getDialog();
                .info("dialogs = " + dialog + " thisdialog = "  + this.);
                TestCase.assertTrue("dialog mismatch",dialog == this.);
                Request ackRequest = dialog.createAckcseq.getSeqNumber() );
                .info("Ack request to send = " + ackRequest);
                .info("Sending ACK");
                dialog.sendAck(ackRequest);
                // Send a Re INVITE
                if ( == 0) {
                    .info("Sending RE-INVITE");
                    this.sendReInvite();
                    ++;
                } else {
                    this. = true;
                }
            } else if (response.getStatusCode() == .
                    && ((CSeqHeaderresponse.getHeader(.))
                            .getMethod().equals(.)) {
                if ( this. -- > 0)
                    this.shutDownAndRestart();
            }
        } catch (Exception ex) {
            .error(ex);
            System.exit(0);
        }
    }
    public void processTimeout(javax.sip.TimeoutEvent timeoutEvent) {
        .info("Transaction Time out");
        .info("TimeoutEvent " + timeoutEvent.getTimeout());
    }
    public SipProvider createSipProvider() {
        try {
                    .);
             = .
                    .createSipProvider();
            return ;
        } catch (Exception ex) {
            .error(ex);
            System.exit(0);
            return null;
        }
    }

    
Create and send a re-invitation.

Throws:
Exception
    public void sendReInvite() throws Exception {
        Request inviteRequest = .createRequest(.);
        inviteRequest.setHeader(mf);
        inviteRequest.setHeader(this.);
        ClientTransaction ct = 
                .getNewClientTransaction(inviteRequest);
        .sendRequest(ct);
    }

    
Create and send out the initial invite.
    public void sendInvite() {
        try {
            // Note that a provider has multiple listening points.
            // all the listening points must have the same IP address
            // and port but differ in their transport parameters.
            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(fromNameAddressnew Integer((int) (Math
                            .random() * .)).toString());
            // create To Header
            SipURI toAddress = ..createSipURI(
                    toUsertoSipAddress);
            Address toNameAddress = .
                    .createAddress(toAddress);
            toNameAddress.setDisplayName(toDisplayName);
            ToHeader toHeader = ..createToHeader(
                    toNameAddressnull);
            // create Request URI
            SipURI requestURI = ..createSipURI(
                    toUser);
            // Create ViaHeaders
            ArrayList viaHeaders = new ArrayList();
            int port = .getListeningPoint(.)
                    .getPort();
            ViaHeader viaHeader = .
                    .createViaHeader(port,
                            .null);
            // add via headers
            viaHeaders.add(viaHeader);
            // Create ContentTypeHeader
            ContentTypeHeader contentTypeHeader = .
                    .createContentTypeHeader("application""sdp");
            // 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.callIdHeadercSeqHeader,
                    fromHeadertoHeaderviaHeadersmaxForwards);
            // Create contact headers
            // Create the contact name address.
            SipURI contactURI = ..createSipURI(
                    fromName);
            contactURI.setPort(.getListeningPoint(
                    .).getPort());
            Address contactAddress = .
                    .createAddress(contactURI);
            // Add the contact address.
            contactAddress.setDisplayName(fromName);
             = .
                    .createContactHeader(contactAddress);
            request.addHeader();
            // Add the extension header.
            Header extensionHeader = .
                    .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";
            request.setContent(sdpDatacontentTypeHeader);
            // The following is the preferred method to route requests
            // to the peer. Create a route header and set the "lr"
            // parameter for the router header.
            Address address = .
                    .createAddress("<sip:" +  + ":" + 
                            + ">");
            // SipUri sipUri = (SipUri) address.getURI();
            // sipUri.setPort(PEER_PORT);
            RouteHeader routeHeader = .
                    .createRouteHeader(address);
            SipUri sipUri = (SipUri)address.getURI();
            sipUri.setLrParam();
            request.addHeader(routeHeader);
            extensionHeader = ..createHeader(
                    "My-Other-Header""my new header value ");
            request.addHeader(extensionHeader);
            Header callInfoHeader = ..createHeader(
                    "Call-Info""<http://www.antd.nist.gov>");
            request.addHeader(callInfoHeader);
            // Create the client transaction.
            this. = .getNewClientTransaction(request);
            // send the request out.
            this..sendRequest();
            this. = this..getDialog();
            .info("created dialog " + );
        } catch (Exception ex) {
            .error("Unexpected exception"ex);
            usage();
        }
    }
    public void checkState() {
        TestCase.assertTrue( == 1 && this.);
    }
    /*
     * (non-Javadoc)
     *
     * @see javax.sip.SipListener#processIOException(javax.sip.IOExceptionEvent)
     */
    public void processIOException(IOExceptionEvent exceptionEvent) {
        .info("IO Exception!");
        TestCase.fail("Unexpected exception");
    }
    /*
     * (non-Javadoc)
     *
     * @see javax.sip.SipListener#processTransactionTerminated(javax.sip.TransactionTerminatedEvent)
     */
    public void processTransactionTerminated(
            TransactionTerminatedEvent transactionTerminatedEvent) {
        .info("Transaction Terminated Event!");
    }
    /*
     * (non-Javadoc)
     *
     * @see javax.sip.SipListener#processDialogTerminated(javax.sip.DialogTerminatedEvent)
     */
    public void processDialogTerminated(
            DialogTerminatedEvent dialogTerminatedEvent) {
        .info("Dialog Terminated Event!");
    }
    /////////////////////////////////////////////////////////////////////////////////
    // main method
    /////////////////////////////////////////////////////////////////////////////////
    public static void main(String args[]) {
        try {
            ProtocolObjects.init("shootist"true);
            .addAppender(new ConsoleAppender(new SimpleLayout()));
            Shootist shootist = new Shootist(10);
            shootist.createSipProvider();
            shootist.provider.addSipListener(shootist);
            shootist.sendInvite();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
New to GrepCode? Check out our FAQ X