Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package examples.refer;
  
  import javax.sip.*;
  import javax.sip.header.*;
  
  import java.util.*;
 
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
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;
 
 
     private int port;
 
     protected SipProvider udpProvider;
 
     protected Dialog dialog;
 
     private static Logger logger = Logger.getLogger(Referee.class) ;
 
     private EventHeader referEvent;
 
     protected static final String usageString = "java "
             + "examples.shootist.Shootist \n"
             + ">>>> is your class path set to the root?";
 
     private static void usage() {
         .info();
         System.exit(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() );
         .inforequest.toString() );
         if (request.getMethod().equals(.)) {
             try {
                 processRefer(requestEventserverTransactionId);
             } catch (Exception e) {
                 e.printStackTrace();
             }
         }
 
     }

    
 
     public void processRefer(RequestEvent requestEvent,
             ServerTransaction serverTransactionthrows ParseExceptionSipExceptionInvalidArgumentException {
         SipProvider sipProvider = (SipProviderrequestEvent.getSource();
         Request refer = requestEvent.getRequest();
 
             ..println("referee: got an REFER sending Accepted");
             ..println("referee:  " + refer.getMethod() );
             ..println("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 );
                 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
            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();
            // REFER dialogs do not terminate on bye.
            this..terminateOnBye(false);
            if ( != null) {
                ..println("Dialog " + );
                ..println("Dialog state " + .getState());
                ..println"local tag=" + .getLocalTag() );
                ..println"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("udp").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 );
            /*
             * JvB: The REFER MUST be answered first.
             */
            st.sendResponse(response);
            // 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) );
            sendNotify."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("udp").getPort() );
            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();
        ..println("Response received with client transaction id "
                + tid + ":\n" + response );
        CSeqHeader cseq = (CSeqHeaderresponse.getHeader. );
        if (cseq.getMethod().equals(.)) {
            try {
                sendNotifyresponse.getStatusCode(), response.getReasonPhrase() );
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            if (response.getStatusCode() >= 200 && response.getStatusCode() < 300) {
                try {
                    Request ack = tid.getDialog().createAckcseq.getSeqNumber() );
                    tid.getDialog().sendAckack );
                    // kill it right away
                    Request bye = tid.getDialog().createRequest. );
                    tid.getDialog().sendRequest.getNewClientTransaction(bye) );
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    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 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();
            // Get transport
            String transport = requestURI.getTransportParam();
            if (transport==nulltransport = "udp";
            ListeningPoint lp = .getListeningPoint(transport);
            // Create ViaHeaders
            ArrayList viaHeaders = new ArrayList();
            ViaHeader viaHeader = .createViaHeader("127.0.0.1",
                    lp.getPort(), transportnull);
            // 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. (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.setTransportParamtransport );
            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);
            ..println("Invite Dialog = " + inviteTid.getDialog());
            // send the request out.
            inviteTid.sendRequest();
        } catch (Throwable ex) {
            .info(ex.getMessage());
            ex.printStackTrace();
            usage();
        }
    }
    private static void initFactories () throws Exception {
        SipFactory sipFactory = SipFactory.getInstance();
        sipFactory.setPathName("gov.nist");
        Properties properties = new Properties();
        .addAppender(new FileAppender
            ( new SimpleLayout(),"refereeoutputlog.txt" ));
        properties.setProperty("javax.sip.STACK_NAME""referee" );
        // You need 16 for logging traces. 32 for debug + traces.
        // Your code will limp at 32 but it is best for debugging.
        // JvB note: debug level may impact order of messages!
        properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL""32");
        properties.setProperty("gov.nist.javax.sip.DEBUG_LOG",
                "refereedebug.txt");
        properties.setProperty("gov.nist.javax.sip.SERVER_LOG",
                "refereelog.txt");
        try {
            // Create SipStack object
             = sipFactory.createSipStack(properties);
            .info("sipStack = " + );
        } catch (PeerUnavailableException e) {
            // could not find
            // gov.nist.jain.protocol.ip.sip.SipStackImpl
            // in the classpath
            e.printStackTrace();
            ..println(e.getMessage());
            if (e.getCause() != null)
                e.getCause().printStackTrace();
            System.exit(0);
        }
        try {
             = sipFactory.createHeaderFactory();
             = sipFactory.createAddressFactory();
             = sipFactory.createMessageFactory();
        } catch  (Exception ex) {
            ex.printStackTrace();
            System.exit(0);
        }
    }
    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();
            usage();
        }
    }
    public Refereeint port ) {
        this. = port;
    }
    public static void main(String args[]) throws Exception {
        initFactories();
        Referee notifier = new Referee( 5065 );
        notifier.createProvider( );
        notifier.udpProvider.addSipListener(notifier);
    }
    public void processIOException(IOExceptionEvent exceptionEvent) {
        ..println"processIOEx:" + exceptionEvent );
    }
    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