Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package examples.ims;
  
  
  import javax.sip.*;
  import javax.sip.header.*;
 import java.util.*;

This class is a UAS template.

Exemplifies the creation and parsing of the SIP P-Headers for IMS

based on examples.simplecallsetup, by M. Ranganathan

issued by Miguel Freitas (IT) PT-Inovacao

 
 
 public class Shootme implements SipListener {
 
     private static AddressFactory addressFactory;
 
     private static MessageFactory messageFactory;
 
     private static HeaderFactory headerFactory;
 
     private static SipStack sipStack;
 
     private static final String myAddress = "127.0.0.1";
 
     private static final int myPort = 5070;
 
     protected ServerTransaction inviteTid;
 
     private Response okResponse;
 
     private Request inviteRequest;
 
     private Dialog dialog;
 
     public static final boolean callerSendsBye = true;
 
     class MyTimerTask extends TimerTask {
         Shootme shootme;
 
         public MyTimerTask(Shootme shootme) {
             this. = shootme;
 
         }
 
         public void run() {
             .sendInviteOK();
         }
 
     }
 
     protected static final String usageString = "java "
             + "examples.shootist.Shootist \n"
             + ">>>> is your class path set to the root?";
 
     private static void usage() {
         ..println();
         System.exit(0);
 
     }
 
     public void processRequest(RequestEvent requestEvent) {
         Request request = requestEvent.getRequest();
         ServerTransaction serverTransactionId = requestEvent
                 .getServerTransaction();
 
         ..println("\n\nRequest " + request.getMethod()
                 + " received at " + .getStackName()
                 + " with server transaction id " + serverTransactionId);
 
         if (request.getMethod().equals(.)) {
             processInvite(requestEventserverTransactionId);
         } else if (request.getMethod().equals(.)) {
             processAck(requestEventserverTransactionId);
         } else if (request.getMethod().equals(.)) {
             processBye(requestEventserverTransactionId);
         } else if (request.getMethod().equals(.)) {
             processCancel(requestEventserverTransactionId);
         }
 
     }
 
     public void processResponse(ResponseEvent responseEvent) {
     }

    
Process the ACK request. Send the bye and complete the call flow.
 
     public void processAck(RequestEvent requestEvent,
             ServerTransaction serverTransaction) {
         try {
             ..println("shootme: got an ACK! ");
             ..println("Dialog State = " + .getState());
            SipProvider provider = (SipProviderrequestEvent.getSource();
            if (!) {
                Request byeRequest = .createRequest(.);
                ClientTransaction ct = provider
                        .getNewClientTransaction(byeRequest);
                .sendRequest(ct);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    
Process the invite request.
    public void processInvite(RequestEvent requestEvent,
            ServerTransaction serverTransaction) {
        SipProvider sipProvider = (SipProviderrequestEvent.getSource();
        Request request = requestEvent.getRequest();
        /* ++++++++++++++++++++++++++++++++++++++++++++
         *                IMS headers
         * ++++++++++++++++++++++++++++++++++++++++++++
         */
        // work-around for IMS headers
        //HeaderFactoryImpl headerFactoryImpl = new HeaderFactoryImpl();
        HeaderFactoryImpl headerFactoryImpl = (HeaderFactoryImpl);
        // check headers Allow, Require and Supported
        // Allow header
        ListIterator li = null;
        AllowHeader allow = null;
        String allowMethods = new String();         // all the methods in Allow Header
        li = request.getHeaders(.);  // get all the allow methods
        // creates an Allow header for each method
        try {
            while(li.hasNext()) // concatenate the method of each Allow header in one string
            {
                allow = (AllowHeaderli.next();
                allowMethods = allowMethods.concat(allow.getMethod()).concat(" ");
            }
        }catch (Exception ex)
        {
            ..println("\n(!) Exception getting Allow header! - " + ex);
        }
        /*
        // Allow: PRACK ??
        if (allowMethods.indexOf(Request.PRACK) != -1)
            System.out.println("\n*** UAC allows PRACK method ");
        else
            System.out.println("\n*** UAC does NOT allow PRACK method ");
        */
        // Require header
        RequireHeader require = null;
        String requireOptionTags = new String();
        li = null;
        li = request.getHeaders(.);
        try {
            while(li.hasNext())
            {
                require = (RequireHeaderli.next();
                requireOptionTags = requireOptionTags
                    .concatrequire.getOptionTag())
                    .concat(" ");
            }
        }
        catch (Exception ex)
        {
            ..println("\n(!) Exception getting Require header! - " + ex);
        }
        /*
        // Require: 100rel ??
        if (requireOptionTags.indexOf("100rel") != -1)
            System.out.println("\n*** UAC requires \"100rel\"");
        else
            System.out.println("\n*** UAC does NOT require \"100rel\"");
        // Require: precondition ??
        if (requireOptionTags.indexOf("precondition") != -1)
            System.out.println("\n*** UAC requires \"precondition\"");
        else
            System.out.println("\n*** UAC does NOT require \"precondition\"");
        // Require: sec-agree ??
        if (requireOptionTags.indexOf("sec-agree") != -1)
            System.out.println("\n*** UAC requires \"sec-agree\"");
        else
            System.out.println("\n*** UAC does NOT require \"sec-agree\"");
        */
        // Supported header
        SupportedHeader supported = null;
        String supportedOptionTags = new String();
        li = request.getHeaders(.);
        try {
            while(li.hasNext())
            {
                supported = (SupportedHeaderli.next();
                supportedOptionTags = supportedOptionTags
                    .concatsupported.getOptionTag())
                    .concat(" ");
            }
        }
        catch (NullPointerException ex)
        {
            ..println("\n(!) Exception getting Supported header! - " + ex);
        }
        /*
        // Supported: 100rel ??
        if (supportedOptionTags.indexOf("100rel") != -1)
            System.out.println("\n*** UAC supports \"100rel\"");
        else
            System.out.println("\n*** UAC does NOT support \"100rel\"");
        // Supported: precondition ??
        if (supportedOptionTags.indexOf("precondition") != -1)
            System.out.println("\n*** UAC supports \"precondition\"");
        else
            System.out.println("\n*** UAC does NOT support \"precondition\"");
        */
        // check P-Headers
        // check P-Called-Party-ID
        PCalledPartyIDHeader calledParty;
        try {
            calledParty = (PCalledPartyIDHeader)
                request.getHeader(.);
            if (calledParty != null)
            {
                ..println(".: P-Called-Party-ID = "
                    + calledParty.getAddress().toString());
            }
            else
                ..println(".: NOT received P-Called-Party-ID ! ");
        }
        catch (Exception ex)
        {
            ..println("(!) Exception getting P-Called-Party-ID header! - " + ex);
        }
        // check P-Associated-URI
        ListIterator associatedURIList;
        try {
            associatedURIList = request.getHeaders(.);
            if (associatedURIList != null)
            {
                ..print(".: P-Associated-URI = ");
                while (associatedURIList.hasNext())
                {
                    PAssociatedURIHeader associatedURI = (PAssociatedURIHeaderassociatedURIList.next();
                    ..print(associatedURI.getAssociatedURI().toString());
                    if (associatedURIList.hasNext())
                        ..print(", ");
                }
            }
            else
                ..println(".: NOT received P-Associated-URI ! ");
            ..print("\n");
        }
        catch (Exception ex)
        {
            ..println("(!) Exception getting P-Associated-URI header! - " + ex);
        }
        // check P-Access-Network-Info
        PAccessNetworkInfoHeader accessInfo = null;
        try {
            accessInfo = (PAccessNetworkInfoHeader)
                request.getHeader(.);
            if (accessInfo != null)
            {
                ..print(".: P-Access-Network-Info: Access Type = "
                    + accessInfo.getAccessType());
                if (accessInfo.getAccessType()
                        .equalsIgnoreCase(
                                .)) // 3GPP-UTRAN-TDD
                    ..print(" - Cell ID = "
                            + accessInfo.getUtranCellID3GPP());
            }
            else
                ..println(".: NOT received P-Access-Network-Info ! ");
            ..println("");
        }
        catch (Exception ex)
        {
            ..println("(!) Exception getting P-Access-Network-Info header! - " + ex);
        }
        // check if .clone() and .equals() is working
        if (accessInfo != null)
        {
            PAccessNetworkInfo accessInfoClone =
                (PAccessNetworkInfoaccessInfo.clone();
            ..println("--> clone = " + accessInfoClone.toString());
            ..println("--> equals? " + accessInfoClone.equals(accessInfo));
        }
        // check P-Visited-Network-ID
        ListIterator visitedNetList;
        try {
            visitedNetList = request.getHeaders(.);
            if (visitedNetList != null)
            {
                ..print(".: P-Visited-Network-ID = ");
                while (visitedNetList.hasNext())
                {
                    PVisitedNetworkIDHeader visitedID =
                        (PVisitedNetworkIDHeadervisitedNetList.next();
                    ..print(visitedID.getVisitedNetworkID());
                    if (visitedNetList.hasNext())
                        ..print(", ");
                }
                ..print("\n");
            }
            else
                ..print(".: NOT received P-Visited-Network-ID ! ");
        }
        catch (Exception ex)
        {
            ..println("(!) Exception getting P-Visited-Network-ID header! - " + ex);
        }
        // check Privacy
        ListIterator privacyList;
        try {
            privacyList = request.getHeaders(.);
            if (privacyList != null && privacyList.hasNext())
            {
                ..print(".: Privacy = ");
                while (privacyList.hasNext())
                {
                    PrivacyHeader privacy =
                        (PrivacyHeaderprivacyList.next();
                    ..print(privacy.getPrivacy());
                    if (privacyList.hasNext())
                        ..print("; ");
                }
                ..println("");
            }
            else
                ..println(".: NOT received Privacy ! ");
        }
        catch (Exception ex)
        {
            ..println("(!) Exception getting Privacy header! - " + ex);
        }
        // check P-Preferred-Identity
        PPreferredIdentityHeader preferredID;
        try {
            preferredID = (PPreferredIdentityHeader)
                request.getHeader(.);
            if (preferredID != null)
            {
                ..println(".: P-Preferred-Identity = " + preferredID.getAddress().toString());
            }
            else
                ..println(".: NOT received P-Preferred-Identity ! ");
        }
        catch (Exception ex)
        {
            ..println("(!) Exception getting P-Preferred-Identity header! - " + ex);
        }
        /*
         * TEST
         */
        // this is only to illustrate the usage of this headers
        // P-Asserted-Identity
        ListIterator assertedIDList;
        try {
            assertedIDList =
                request.getHeaders(.);
            if (assertedIDList != null && assertedIDList.hasNext())
            {
                ..print(".: P-Asserted-Identity = ");
                while (assertedIDList.hasNext())
                {
                    PAssertedIdentityHeader assertedID =
                        (PAssertedIdentityHeaderassertedIDList.next();
                    ..print(assertedID.getAddress().toString());
                    if (assertedIDList.hasNext())
                        ..print(", ");
                }
                ..println("");
            }
            else
                ..println(".: NOT received P-Asserted-Identity... ");
        }
        catch (Exception ex)
        {
            ..println("(!) Exception getting P-Asserted-Identity header! - " + ex);
        }
        // P-Charging-Function-Addresses
        PChargingFunctionAddressesHeader chargAddr;
        try {
            chargAddr = (PChargingFunctionAddressesHeader)
                request.getHeader(.);
            if (chargAddr != null)
            {
                Iterator param = chargAddr.getParameterNames();
                ..print(".: P-Charging-Function-Addresses = ");
                if (param != null) {
                    while (param.hasNext()) {
                        String paramName = (String)param.next();
                        ..printparamName + "=" + chargAddr.getParameter(paramName));
                        if (param.hasNext())
                            ..print(", ");
                    }
                }
                ..println("");
            }
            else
                ..println(".: NOT containing P-Charging-Function-Addresses... ");
        }
        catch (Exception ex)
        {
            ..println("(!) Exception getting P-Charging-Function-Addresses header! - " + ex);
        }
        // P-Charging-Vector
        PChargingVectorHeader chargVect;
        try {
            chargVect = (PChargingVectorHeader)
                request.getHeader(.);
            if (chargVect != null)
            {
                Iterator param = chargVect.getParameterNames();
                ..print(".: P-Charging-Vector = ");
                if (param != null && param.hasNext()) {
                    while (param.hasNext()) {
                        String paramName = (String)param.next();
                        ..printparamName + "="
                                + chargVect.getParameter(paramName));
                        if (param.hasNext())
                            ..print(", ");
                    }
                }
                ..println("");
            }
            else
                ..println(".: NOT containing P-Charging-Vector... ");
        }
        catch (Exception ex)
        {
            ..println("(!) Exception getting P-Charging-Vector header! - " + ex);
        }
        // P-Media-Authorization
        ListIterator mediaAuthList;
        try {
            mediaAuthList = request.getHeaders(.);
            if (mediaAuthList != null)
            {
                ..print(".: P-Media-Authorization = ");
                while (mediaAuthList.hasNext())
                {
                    PMediaAuthorizationHeader mediaAuth =
                        (PMediaAuthorizationHeadermediaAuthList.next();
                    ..print(mediaAuth.getToken());
                    if (mediaAuthList.hasNext())
                        ..print(", ");
                }
                ..println("");
            }
            else
                ..println(".: NOT containing P-Media-Authorization... ");
        }
        catch (Exception ex)
        {
            ..println("(!) Exception getting P-Media-Authorization header! - " + ex);
        }
        // Security-Client header
        ListIterator secClientList;
        try {
            secClientList = request.getHeaders(.);
            if (secClientList != null)
            {
                while (secClientList.hasNext())
                {
                    ..println(".: "
                            + ((SecurityClientHeader)secClientList.next()).toString());
                }
            }
            else
                ..println(".: NOT containing Security-Client header... ");
        }
        catch (Exception ex)
        {
            ..println("(!) Exception getting Security-Client header! - " + ex);
        }
        // this is only to illustrate the usage of this headers
        // send Security-Server if Require: sec-agree
        SecurityServerList secServerList = null;
        if (requireOptionTags.indexOf("sec-agree") != -1)
        {
            secServerList = new SecurityServerList();
            try {
                SecurityServerHeader secServer1 =
                    headerFactoryImpl.createSecurityClientHeader();
                secServer1.setSecurityMechanism("ipsec-3gpp");
                secServer1.setAlgorithm("hmac-md5-96");
                secServer1.setEncryptionAlgorithm("des-cbc");
                secServer1.setSPIClient(10000);
                secServer1.setSPIServer(10001);
                secServer1.setPortClient(5063);
                secServer1.setPortServer(4166);
                secServer1.setPreference(0.1f);
                SecurityServerHeader secServer2 =
                    headerFactoryImpl.createSecurityClientHeader();
                secServer2.setSecurityMechanism("ipsec-3gpp");
                secServer2.setAlgorithm("hmac-md5-96");
                secServer2.setEncryptionAlgorithm("des-cbc");
                secServer2.setSPIClient(20000);
                secServer2.setSPIServer(20001);
                secServer2.setPortClient(5073);
                secServer2.setPortServer(4286);
                secServer2.setPreference(0.5f);
                request.addHeader(secServer1);
                request.addHeader(secServer2);
            }
            catch (Exception ex)
            {
                ..println("(!) Exception adding Security-Server header : " + ex);
            }
        }
        // check Path header
        ListIterator<HeaderpathList = (ListIterator<Header>)request.getHeaders(.);
        if (pathList != null && pathList.hasNext())
        {
            ..print(".: Path received : ");
            while (pathList.hasNext())
            {
                PathHeader path = (PathHeader)pathList.next();
                if (path != null)
                    ..print(path.getAddress().toString());
                if (pathList.hasNext())
                    ..print(", ");
            }
            ..println("");
        }
        /////////////////////////////////////////
        try {
            ..println("shootme: got an Invite sending Trying");
            // System.out.println("shootme: " + request);
            Response response = .createResponse(.,
                    request);
            ServerTransaction st = requestEvent.getServerTransaction();
            if (st == null) {
                st = sipProvider.getNewServerTransaction(request);
            }
             = st.getDialog();
            st.sendResponse(response);
            this. = .createResponse(.,
                    request);
            Address address = .createAddress("Shootme <sip:"
                    +  + ":" +  + ">");
            ContactHeader contactHeader = 
                    .createContactHeader(address);
            response.addHeader(contactHeader);
            ToHeader toHeader = (ToHeader.getHeader(.);
            toHeader.setTag("4321"); // Application is supposed to set.
            .addHeader(contactHeader);
            this. = st;
            // Defer sending the OK to simulate the phone ringing.
            // Answered in 1 second ( this guy is fast at taking calls)
            this. = request;
            // add Security-Server header
            if (secServerList != null && !secServerList.isEmpty())
            {
                RequireHeader requireHeader = .createRequireHeader("sec-agree");
                this..setHeader(requireHeader);
                this..setHeader(secServerList);
            }
            new Timer().schedule(new MyTimerTask(this), 1000);
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(0);
        }
    }
    private void sendInviteOK() {
        try {
            if (.getState() != .) {
                ..println("shootme: Dialog state before 200: "
                        + .getDialog().getState());
                .sendResponse();
                ..println("shootme: Dialog state after 200: "
                        + .getDialog().getState());
            }
        } catch (SipException ex) {
            ex.printStackTrace();
        } catch (InvalidArgumentException ex) {
            ex.printStackTrace();
        }
    }

    
Process the bye request.
    public void processBye(RequestEvent requestEvent,
            ServerTransaction serverTransactionId) {
        SipProvider sipProvider = (SipProviderrequestEvent.getSource();
        Request request = requestEvent.getRequest();
        Dialog dialog = requestEvent.getDialog();
        ..println("local party = " + dialog.getLocalParty());
        try {
            ..println("shootme:  got a bye sending OK.");
            Response response = .createResponse(200, request);
            serverTransactionId.sendResponse(response);
            ..println("Dialog State is "
                    + serverTransactionId.getDialog().getState());
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(0);
        }
    }
    public void processCancel(RequestEvent requestEvent,
            ServerTransaction serverTransactionId) {
        SipProvider sipProvider = (SipProviderrequestEvent.getSource();
        Request request = requestEvent.getRequest();
        try {
            ..println("shootme:  got a cancel.");
            if (serverTransactionId == null) {
                ..println("shootme:  null tid.");
                return;
            }
            Response response = .createResponse(200, request);
            serverTransactionId.sendResponse(response);
            if (.getState() != .) {
                response = .createResponse(
                        .);
                .sendResponse(response);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(0);
        }
    }
    public void processTimeout(javax.sip.TimeoutEvent timeoutEvent) {
        Transaction transaction;
        if (timeoutEvent.isServerTransaction()) {
            transaction = timeoutEvent.getServerTransaction();
        } else {
            transaction = timeoutEvent.getClientTransaction();
        }
        ..println("state = " + transaction.getState());
        ..println("dialog = " + transaction.getDialog());
        ..println("dialogState = "
                + transaction.getDialog().getState());
        ..println("Transaction Time out");
    }
    public void init() {
        SipFactory sipFactory = null;
         = null;
        sipFactory = SipFactory.getInstance();
        sipFactory.setPathName("gov.nist");
        Properties properties = new Properties();
        properties.setProperty("javax.sip.STACK_NAME""shootme");
        // 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""32");
        properties.setProperty("gov.nist.javax.sip.DEBUG_LOG",
                "shootmedebug.txt");
        properties.setProperty("gov.nist.javax.sip.SERVER_LOG",
                "shootmelog.txt");
        try {
            // Create SipStack object
             = sipFactory.createSipStack(properties);
            ..println("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();
            ListeningPoint lp = .createListeningPoint("127.0.0.1",
                    "udp");
            Shootme listener = this;
            SipProvider sipProvider = .createSipProvider(lp);
            ..println("udp provider " + sipProvider);
            sipProvider.addSipListener(listener);
        } catch (Exception ex) {
            ..println(ex.getMessage());
            ex.printStackTrace();
            usage();
        }
    }
    public static void main(String args[]) {
        new Shootme().init();
    }
    public void processIOException(IOExceptionEvent exceptionEvent) {
        ..println("IOException");
    }
    public void processTransactionTerminated(
            TransactionTerminatedEvent transactionTerminatedEvent) {
        if (transactionTerminatedEvent.isServerTransaction())
            ..println("Transaction terminated event recieved"
                    + transactionTerminatedEvent.getServerTransaction());
        else
            ..println("Transaction terminated "
                    + transactionTerminatedEvent.getClientTransaction());
    }
    public void processDialogTerminated(
            DialogTerminatedEvent dialogTerminatedEvent) {
        ..println("Dialog terminated event recieved");
        Dialog d = dialogTerminatedEvent.getDialog();
        ..println("Local Party = " + d.getLocalParty());
    }
New to GrepCode? Check out our FAQ X