Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package test.tck.msgflow.callflows.refer;
  
  
  import javax.sip.Dialog;
 
 
This example shows an out-of-dialog REFER scenario: referer sends REFER to referee, with Refer-To set to Shootme referee sends INVITE to Shootme, and NOTIFYs to referer about call progress This is the referee

Author(s):
Jeroen van Bemmel
Ivelin Ivanov
See also:
RFC3515 http://www.ietf.org/rfc/rfc3515.txt
 
 public class Referee implements SipListener {
 
     private static AddressFactory addressFactory;
 
     private static MessageFactory messageFactory;
 
     private static HeaderFactory headerFactory;
 
     private static SipStack sipStack;
 
     public static final int myPort = 5070;
 
     protected SipProvider mySipProvider;
 
     protected Dialog dialog;
 
     private static Logger logger = Logger.getLogger(Referee.class) ;
 
     private boolean tryingSent;
 
     private EventHeader referEvent;
 
     private String transport;
 
     static {
         try {
             .setLevel(.);
             .addAppender(new FileAppender(new SimpleLayout(),
                     "logs/refereeoutputlog.txt"));
         } catch (Exception ex) {
             throw new RuntimeException(ex);
        }
    }
    public Referee(ProtocolObjects protObjects) {
         = protObjects.addressFactory;
         = protObjects.messageFactory;
         = protObjects.headerFactory;
         = protObjects.sipStack;
         = protObjects.transport;
    }
    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() );
        .inforequest.toString() );
        if (request.getMethod().equals(.)) {
            try {
                processRefer(requestEventserverTransactionId);
            } catch (Exception e) {
                .info("Referee failed processing REFER, because of " + e.getMessage(), e);
                TestHarness.fail("Referee failed processing REFER, because of " + e.getMessage());
            }
        } else TestHarness.fail"Not a REFER request but:" + request.getMethod() );
    }

    
    public void processRefer(RequestEvent requestEvent,
        ServerTransaction serverTransactionthrows ParseExceptionSipExceptionInvalidArgumentException {
        SipProvider sipProvider = (SipProviderrequestEvent.getSource();
        Request refer = requestEvent.getRequest();
            .info("referee: got an REFER sending Accepted");
            .info("referee:  " + refer.getMethod() );
             = requestEvent.getDialog();
            .info("referee : dialog = " + requestEvent.getDialog());
            // Check that it has a Refer-To, if not bad request
            ReferToHeader refTo = (ReferToHeaderrefer.getHeader. );
            if (refTo==null) {
                Response bad = .createResponse(.refer);
                bad.setReasonPhrase"Missing Refer-To" );
                sipProvider.sendResponsebad );
                TestHarness.fail("Bad REFER request. Missing Refer-To.");
            }
            // New test: first time, only send 100 Trying, to test that retransmission
            // continues for non-INVITE requests (using UDP)
            // before(!) creating a ServerTransaction! Else retransmissions are filtered
            if (! && "udp".equalsIgnoreCase()) {
                 = true;
                sipProvider.sendResponse.createResponse(100, refer) );
                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(refer);
            }
            // Check if it is an initial SUBSCRIBE or a refresh / unsubscribe
            String toTag = Integer.toHexString( (int) (Math.random() * .) );
            response = .createResponse(202, refer);
            ToHeader toHeader = (ToHeaderresponse.getHeader(.);
            // Sanity check: to header should not have a tag. Else the dialog
            // should have matched
            TestHarness.assertNull("To-tag!=null but no dialog match! My dialog=" + toHeader.getTag());
            toHeader.setTag(toTag); // Application is supposed to set.
            this. = st.getDialog();
            // REFER dialogs do not terminate on bye.
            this..terminateOnBye(false);
            if ( != null) {
                .info("Dialog " + );
                .info("Dialog state " + .getState());
                .info"local tag=" + .getLocalTag() );
                .info"remote tag=" + .getRemoteTag() );
            }
            // Both 2xx response to SUBSCRIBE and NOTIFY need a Contact
            Address address = .createAddress("Referee <sip:127.0.0.1>");
            ((SipURI)address.getURI()).setPort.getListeningPoint().getPort() );
            ContactHeader contactHeader = .createContactHeader(address);
            response.addHeader(contactHeader);
            // Expires header is mandatory in 2xx responses to REFER
            ExpiresHeader expires = (ExpiresHeaderrefer.getHeader. );
            if (expires==null) {
                expires = .createExpiresHeader(30);// rather short
            }
            response.addHeaderexpires );
            /*
             * The REFER MUST be answered first.
             */
            TestHarness.assertNull.getState() );
            st.sendResponse(response);
            TestHarness.assertEquals..getState() );
            // NOTIFY MUST have "refer" event, possibly with id
             = .createEventHeader("refer");
            // Not necessary, but allowed: id == cseq of REFER
            long id = ((CSeqHeaderrefer.getHeader("CSeq")).getSeqNumber();
            .setEventId( Long.toString(id) );
            // JvB: do this after receiving 100 response
            // sendNotify( Response.TRYING, "Trying" );
            // Then call the refer-to
            sendInviterefTo );
        }
        private void sendNotifyint codeString reason )
            throws SipExceptionParseException
        {
            /*
             * 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.
             */
            Request notifyRequest = .createRequest"NOTIFY" );
            // Initial state is pending, second time we assume terminated (Expires==0)
            String state = .;
            if (code>100 && code<200) {
                state = .;
            } else if (code>=200) {
                state = .;
            }
            SubscriptionStateHeader sstate = .createSubscriptionStateHeaderstate );
            if (state == .) {
                sstate.setReasonCode("noresource");
            }
            notifyRequest.addHeader(sstate);
            notifyRequest.setHeader();
            Address address = .createAddress("Referee <sip:127.0.0.1>");
            ((SipURI)address.getURI()).setPort.getListeningPoint().getPort() );
            ((SipURI)address.getURI()).setTransportParam();
            ContactHeader contactHeader = .createContactHeader(address);
            notifyRequest.setHeader(contactHeader);
            // notifyRequest.setHeader(routeHeader);
            ClientTransaction ct2 = .getNewClientTransaction(notifyRequest);
            ContentTypeHeader ct = .createContentTypeHeader("message","sipfrag");
            ct.setParameter"version""2.0" );
            notifyRequest.setContent"SIP/2.0 " + code + ' ' + reasonct );
            // Let the other side know that the tx is pending acceptance
            //
            .sendRequest(ct2);
            .info("NOTIFY Branch ID " +
                ((ViaHeader)notifyRequest.getHeader(.)).getParameter("branch"));
            .info("Dialog " + );
            .info("Dialog state after NOTIFY: " + .getState());
    }
    public void processResponse(ResponseEvent responseReceivedEvent) {
        .info("Got a response");
        Response response = (ResponseresponseReceivedEvent.getResponse();
        Transaction tid = responseReceivedEvent.getClientTransaction();
        if(tid != null) {
	        .info("Response received with client transaction id "
	                + tid + ":\n" + response.getStatusCode() +
	                " cseq = " + response.getHeader(.) + 
	                " dialog " + tid.getDialog());
        } else {
        	.info("Response received with client transaction id "
	                + tid + ":\n" + response.getStatusCode() +
	                " cseq = " + response.getHeader(.) + 
	                " dialog " + responseReceivedEvent.getDialog());
        }
        CSeqHeader cseq = (CSeqHeaderresponse.getHeader. );
        if (cseq.getMethod().equals(.)) {
            try {
                sendNotifyresponse.getStatusCode(), response.getReasonPhrase() );
            } catch (Exception e1) {
                TestHarness.fail("Failed to send notify, because of " + e1.getMessage());
            }
            if (response.getStatusCode() == 200 ) {
                try {
                    Request ack = tid.getDialog().createAckcseq.getSeqNumber() );
                    tid.getDialog().sendAckack );
                    // kill it right away
                    if ( tid.getDialog().getState() != . ) {
                    	Request bye = tid.getDialog()
                    }
                } catch (Exception e) {
                	.error("Caught exception",e);
                    TestHarness.fail("Failed to send BYE request, because of " + e.getMessage());
                }
            }
        }
    }
    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");
        TestHarness.fail"Transaction timeout" );
    }
    public void sendInviteReferToHeader to ) {
        try {
            String fromName = "Referee";
            String fromSipAddress = "here.com";
            String fromDisplayName = "The Master Blaster";
            // create >From Header
            SipURI fromAddress = .createSipURI(fromName,
                    fromSipAddress);
            Address fromNameAddress = .createAddress(fromAddress);
            fromNameAddress.setDisplayName(fromDisplayName);
            FromHeader fromHeader = .createFromHeader(
                    fromNameAddress"12345");
            // create To Header
            ToHeader toHeader = .createToHeaderto.getAddress(),
                    null);
            // get Request URI
            SipURI requestURI = (SipURIto.getAddress().getURI();
            // Create ViaHeaders
            ArrayList viaHeaders = new ArrayList();
            ViaHeader viaHeader = .createViaHeader("127.0.0.1",
                    lp.getPort(), null);
            // 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. (TODO should read request type from Refer-To)
            Request request = .createRequest(requestURI,
                    .callIdHeadercSeqHeaderfromHeader,
                    toHeaderviaHeadersmaxForwards);
            // Create contact headers
            String host = lp.getIPAddress();
            SipURI contactURI = .createSipURI(fromNamehost);
            contactURI.setPort(lp.getPort());
            contactURI.setTransportParam );
            Address contactAddress = .createAddress(contactURI);
            // Add the contact address.
            contactAddress.setDisplayName(fromName);
            ContactHeader contactHeader = .createContactHeader(contactAddress);
            request.addHeader(contactHeader);
            // Create the client transaction.
            ClientTransaction inviteTid = .getNewClientTransaction(request);
            .info("Invite Dialog = " + inviteTid.getDialog());
            // send the request out.
            inviteTid.sendRequest();
        } catch (Throwable ex) {
            TestHarness.fail("Failed to send INVITE, because of " + ex);
        }
    }
    public SipProvider createProvider() throws Exception {
        ListeningPoint lp = .createListeningPoint("127.0.0.1",
                );
        this. = .createSipProvider(lp);
        .info("provider " + );
        return ;
    }
    public void processIOException(IOExceptionEvent exceptionEvent) {
        .error"processIOEx:" + exceptionEvent );
        TestHarness.fail("unexpected event");
    }
    public void processTransactionTerminated(
            TransactionTerminatedEvent tte) {
        .info("transaction terminated:" + tte );
    }
    public void processDialogTerminated(
            DialogTerminatedEvent dialogTerminatedEvent) {
        .info("dialog terminated:" + dialogTerminatedEvent );
    }
New to GrepCode? Check out our FAQ X