Advertisement
Guest User

sip test

a guest
Nov 26th, 2015
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 18.21 KB | None | 0 0
  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package edu.upf;
  6.  
  7. import java.net.InetAddress;
  8. import java.util.ArrayList;
  9. import java.util.Properties;
  10. import java.util.Random;
  11. import javax.sip.*;
  12. import javax.sip.address.Address;
  13. import javax.sip.address.AddressFactory;
  14. import javax.sip.header.CSeqHeader;
  15. import javax.sip.header.CallIdHeader;
  16. import javax.sip.header.ContactHeader;
  17. import javax.sip.header.FromHeader;
  18. import javax.sip.header.HeaderFactory;
  19. import javax.sip.header.MaxForwardsHeader;
  20. import javax.sip.header.ToHeader;
  21. import javax.sip.header.ViaHeader;
  22. import javax.sip.message.MessageFactory;
  23. import javax.sip.message.Request;
  24. import javax.sip.message.Response;
  25. import javax.swing.*;
  26.  
  27. /**
  28.  *
  29.  * @author Alex
  30.  */
  31. public class SipClient extends JFrame implements SipListener {
  32.    
  33.     private long cseq = 1L;
  34.  
  35.     // Objects used to communicate to the JAIN SIP API.
  36.     SipFactory sipFactory;          // Used to access the SIP API.
  37.     SipStack sipStack;              // The SIP stack.
  38.     SipProvider sipProvider;        // Used to send SIP messages.
  39.     MessageFactory messageFactory;  // Used to create SIP message factory.
  40.     HeaderFactory headerFactory;    // Used to create SIP headers.
  41.     AddressFactory addressFactory;  // Used to create SIP URIs.
  42.     ListeningPoint listeningPoint;  // SIP listening IP address/port.
  43.     Properties properties;          // Other properties.
  44.  
  45. // Objects keeping local configuration.
  46.     String ip;                      // The local IP address.
  47.     int port = 6060;                // The local port.
  48.     String protocol = "udp";        // The local protocol (UDP).
  49.     int tag = (new Random()).nextInt(); // The local tag.
  50.     Address contactAddress;         // The contact address.
  51.     ContactHeader contactHeader;    // The contact header.
  52.  
  53.     /**
  54.      * Creates new form SipClient
  55.      */
  56.     public SipClient() {
  57.         initComponents();
  58.     }
  59.  
  60.     /**
  61.      * This method is called from within the constructor to initialize the form.
  62.      * WARNING: Do NOT modify this code. The content of this method is always
  63.      * regenerated by the Form Editor.
  64.      */
  65.     @SuppressWarnings("unchecked")
  66.     // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  67.     private void initComponents() {
  68.  
  69.         scrollPane = new javax.swing.JScrollPane();
  70.         textArea = new javax.swing.JTextArea();
  71.         buttonRegisterStateless = new javax.swing.JButton();
  72.         buttonRegisterStatefull = new javax.swing.JButton();
  73.         buttonInvite = new javax.swing.JButton();
  74.         buttonBye = new javax.swing.JButton();
  75.         textField = new javax.swing.JTextField();
  76.  
  77.         setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  78.         setTitle("SIP Client");
  79.         setLocationByPlatform(true);
  80.         addWindowListener(new java.awt.event.WindowAdapter() {
  81.             public void windowOpened(java.awt.event.WindowEvent evt) {
  82.                 onOpen(evt);
  83.             }
  84.         });
  85.  
  86.         textArea.setEditable(false);
  87.         textArea.setColumns(20);
  88.         textArea.setRows(5);
  89.         scrollPane.setViewportView(textArea);
  90.  
  91.         buttonRegisterStateless.setText("Reg (SL)");
  92.         buttonRegisterStateless.setEnabled(false);
  93.         buttonRegisterStateless.addActionListener(new java.awt.event.ActionListener() {
  94.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  95.                 onRegisterStateless(evt);
  96.             }
  97.         });
  98.  
  99.         buttonRegisterStatefull.setText("Reg (SF)");
  100.         buttonRegisterStatefull.setEnabled(false);
  101.         buttonRegisterStatefull.addActionListener(new java.awt.event.ActionListener() {
  102.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  103.                 onRegisterStatefull(evt);
  104.             }
  105.         });
  106.  
  107.         buttonInvite.setText("Invite");
  108.         buttonInvite.setEnabled(false);
  109.         buttonInvite.addActionListener(new java.awt.event.ActionListener() {
  110.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  111.                 onInvite(evt);
  112.             }
  113.         });
  114.  
  115.         buttonBye.setText("Bye");
  116.         buttonBye.setEnabled(false);
  117.         buttonBye.addActionListener(new java.awt.event.ActionListener() {
  118.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  119.                 onBye(evt);
  120.             }
  121.         });
  122.  
  123.         textField.setText("sip:alice@localhost:5060");
  124.  
  125.         javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  126.         getContentPane().setLayout(layout);
  127.         layout.setHorizontalGroup(
  128.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  129.             .addGroup(layout.createSequentialGroup()
  130.                 .addContainerGap()
  131.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  132.                     .addComponent(scrollPane)
  133.                     .addGroup(layout.createSequentialGroup()
  134.                         .addComponent(buttonRegisterStateless, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
  135.                         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  136.                         .addComponent(buttonRegisterStatefull, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
  137.                         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  138.                         .addComponent(buttonInvite, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
  139.                         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  140.                         .addComponent(buttonBye, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
  141.                         .addGap(0, 2, Short.MAX_VALUE))
  142.                     .addComponent(textField))
  143.                 .addContainerGap())
  144.         );
  145.         layout.setVerticalGroup(
  146.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  147.             .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  148.                 .addContainerGap()
  149.                 .addComponent(textField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  150.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  151.                 .addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
  152.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  153.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  154.                     .addComponent(buttonRegisterStateless)
  155.                     .addComponent(buttonInvite)
  156.                     .addComponent(buttonBye)
  157.                     .addComponent(buttonRegisterStatefull))
  158.                 .addContainerGap())
  159.         );
  160.  
  161.         pack();
  162.     }// </editor-fold>                        
  163.  
  164.     private void onOpen(java.awt.event.WindowEvent evt) {                        
  165.         try {
  166.             buttonRegisterStateless.setEnabled(true);
  167.             // Get the local IP address.
  168.             this.ip = InetAddress.getLocalHost().getHostAddress();
  169.             // Create the SIP factory and set the path name.
  170.             this.sipFactory = SipFactory.getInstance();
  171.             this.sipFactory.setPathName("gov.nist");
  172.             // Create and set the SIP stack properties.
  173.             this.properties = new Properties();
  174.             this.properties.setProperty("javax.sip.STACK_NAME", "stack");
  175.             // Create the SIP stack.
  176.             this.sipStack = this.sipFactory.createSipStack(this.properties);
  177.             // Create the SIP message factory.
  178.             this.messageFactory = this.sipFactory.createMessageFactory();
  179.             // Create the SIP header factory.
  180.             this.headerFactory = this.sipFactory.createHeaderFactory();
  181.             // Create the SIP address factory.
  182.             this.addressFactory = this.sipFactory.createAddressFactory();
  183.             // Create the SIP listening point and bind it to the local IP address, port and protocol.
  184.             this.listeningPoint = this.sipStack.createListeningPoint(this.ip, this.port, this.protocol);
  185.             // Create the SIP provider.
  186.             this.sipProvider = this.sipStack.createSipProvider(this.listeningPoint);
  187.             // Add our application as a SIP listener.
  188.             this.sipProvider.addSipListener(this);
  189.             // Create the contact address used for all SIP messages.
  190.             this.contactAddress = this.addressFactory.createAddress("sip:" + 1000 + ":" + this.port);
  191.             // Create the contact header used for all SIP messages.
  192.             this.contactHeader = this.headerFactory.createContactHeader(contactAddress);
  193.  
  194.             // Display the local IP address and port in the text area.
  195.             this.textArea.append("Local address: " + this.ip + ":" + this.port + "\n");
  196.         } catch (Exception e) {
  197.             // If an error occurs, display an error message box and exit.
  198.             JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
  199.             System.exit(-1);
  200.         }
  201.     }                      
  202.  
  203.     private void onRegisterStateless(java.awt.event.ActionEvent evt) {                                    
  204.         try {
  205.             // Get the destination address from the text field.
  206.             Address addressTo = this.addressFactory.createAddress(this.textField.getText());
  207.             // Create the request URI for the SIP message.
  208.             javax.sip.address.URI requestURI = addressTo.getURI();
  209.  
  210.             // Create the SIP message headers.
  211.             // The "Via" headers.
  212.             ArrayList viaHeaders = new ArrayList();
  213.             ViaHeader viaHeader = this.headerFactory.createViaHeader(this.ip, this.port, "udp", null);
  214.             viaHeaders.add(viaHeader);
  215.             // The "Max-Forwards" header.
  216.             MaxForwardsHeader maxForwardsHeader = this.headerFactory.createMaxForwardsHeader(70);
  217.             // The "Call-Id" header.
  218.             CallIdHeader callIdHeader = this.sipProvider.getNewCallId();
  219.             // The "CSeq" header.
  220.             CSeqHeader cSeqHeader = this.headerFactory.createCSeqHeader(cseq, "REGISTER");
  221.             // The "From" header.
  222.             FromHeader fromHeader = this.headerFactory.createFromHeader(this.contactAddress, String.valueOf(this.tag));
  223.             // The "To" header.
  224.             ToHeader toHeader = this.headerFactory.createToHeader(addressTo, null);
  225.  
  226.             // Create the REGISTER request.
  227.             Request request = this.messageFactory.createRequest(
  228.                     requestURI,
  229.                     "REGISTER",
  230.                     callIdHeader,
  231.                     cSeqHeader,
  232.                     fromHeader,
  233.                     toHeader,
  234.                     viaHeaders,
  235.                     maxForwardsHeader);
  236.             // Add the "Contact" header to the request.
  237.             request.addHeader(contactHeader);
  238.  
  239.             // Send the request statelessly through the SIP provider.
  240.             this.sipProvider.sendRequest(request);
  241.  
  242.             // Display the message in the text area.
  243.             this.textArea.append(
  244.                     "Request sent:\n" + request.toString() + "\n\n");
  245.         } catch (Exception e) {
  246.             // If an error occurred, display the error.
  247.             this.textArea.append("Request sent failed: " + e.getMessage() + "\n");
  248.         }
  249.     }                                    
  250.  
  251.     private void onRegisterStatefull(java.awt.event.ActionEvent evt) {                                    
  252.         // A method called when you click on the "Reg (SF)" button.
  253.     }                                    
  254.  
  255.     private void onInvite(java.awt.event.ActionEvent evt) {                          
  256.         // A method called when you click on the "Invite" button.
  257.     }                        
  258.  
  259.     private void onBye(java.awt.event.ActionEvent evt) {                      
  260.         // A method called when you click on the "Bye" button.
  261.     }                      
  262.  
  263.     /**
  264.      * @param args the command line arguments
  265.      */
  266.     public static void main(String args[]) {
  267.         /* Set the Nimbus look and feel */
  268.         //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  269.         /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  270.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
  271.          */
  272.         try {
  273.             for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  274.                 if ("Nimbus".equals(info.getName())) {
  275.                     javax.swing.UIManager.setLookAndFeel(info.getClassName());
  276.                     break;
  277.                 }
  278.             }
  279.         } catch (ClassNotFoundException ex) {
  280.             java.util.logging.Logger.getLogger(SipClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  281.         } catch (InstantiationException ex) {
  282.             java.util.logging.Logger.getLogger(SipClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  283.         } catch (IllegalAccessException ex) {
  284.             java.util.logging.Logger.getLogger(SipClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  285.         } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  286.             java.util.logging.Logger.getLogger(SipClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  287.         }
  288.         //</editor-fold>
  289.  
  290.         /* Create and display the form */
  291.         java.awt.EventQueue.invokeLater(new Runnable() {
  292.             @Override
  293.             public void run() {
  294.                 new SipClient().setVisible(true);
  295.             }
  296.         });
  297.     }
  298.     // Variables declaration - do not modify                    
  299.     private javax.swing.JButton buttonBye;
  300.     private javax.swing.JButton buttonInvite;
  301.     private javax.swing.JButton buttonRegisterStatefull;
  302.     private javax.swing.JButton buttonRegisterStateless;
  303.     private javax.swing.JScrollPane scrollPane;
  304.     private javax.swing.JTextArea textArea;
  305.     private javax.swing.JTextField textField;
  306.     // End of variables declaration                  
  307.  
  308.     @Override
  309.     public void processRequest(RequestEvent requestEvent) {
  310.         // A method called when you receive a SIP request.
  311.     }
  312.  
  313.     @Override
  314.     public void processResponse(ResponseEvent responseEvent) {
  315.         // Get the response.
  316.         Response response = responseEvent.getResponse();
  317. // Display the response message in the text area.
  318.         this.textArea.append("\nReceived response: " + response.toString());
  319.     }
  320.  
  321.     @Override
  322.     public void processTimeout(TimeoutEvent timeoutEvent) {
  323.         // A method called when a SIP operation times out.
  324.     }
  325.  
  326.     @Override
  327.     public void processIOException(IOExceptionEvent exceptionEvent) {
  328.         // A method called when a SIP operation results in an I/O error.
  329.     }
  330.  
  331.     @Override
  332.     public void processTransactionTerminated(TransactionTerminatedEvent transactionTerminatedEvent) {
  333.         // A method called when a SIP transaction terminates.
  334.     }
  335.  
  336.     @Override
  337.     public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) {
  338.         // A method called when a SIP dialog terminates.
  339.     }
  340.  
  341.     public void register(Response response) {
  342.         try {
  343.             cseq++;
  344.             ArrayList viaHeaders = new ArrayList();
  345.             ViaHeader viaHeader = this.headerFactory.createViaHeader(this.ip,
  346.                     this.port, "udp", null);
  347.             viaHeaders.add(viaHeader);
  348. // The &amp;quot;Max-Forwards&amp;quot; header.
  349.             MaxForwardsHeader maxForwardsHeader = this.headerFactory
  350.                     .createMaxForwardsHeader(70);
  351. // The &amp;quot;Call-Id&amp;quot; header.
  352.             CallIdHeader callIdHeader = this.sipProvider.getNewCallId();
  353. // The &amp;quot;CSeq&amp;quot; header.
  354.             CSeqHeader cSeqHeader = this.headerFactory.createCSeqHeader(cseq,
  355.                      "REGISTER");
  356.  
  357.             Address fromAddress = addressFactory.createAddress( "sip:" + username + '@' +
  358.             );
  359.  
  360. FromHeader fromHeader = this.headerFactory.createFromHeader(
  361.                     fromAddress, String.valueOf(this.tag));
  362. // The &amp;quot;To&amp;quot; header.
  363.             ToHeader toHeader = this.headerFactory.createToHeader(fromAddress,
  364.                     null);
  365.  
  366. // this.contactHeader = this.headerFactory
  367. // .createContactHeader(contactAddress);
  368.             request = this.messageFactory.createRequest( & amp;quot;
  369.             REGISTER sip:&amp;quot;
  370.             +server + & amp;quot;SIP / 2.0\r\n\r\n & amp;quot;);
  371.             request.addHeader(callIdHeader);
  372.             request.addHeader(cSeqHeader);
  373.             request.addHeader(fromHeader);
  374.             request.addHeader(toHeader);
  375.             request.addHeader(maxForwardsHeader);
  376.             request.addHeader(viaHeader);
  377.             request.addHeader(contactHeader);
  378.             if (response != null) {
  379.                 retry = true;
  380.                 AuthorizationHeader authHeader = Utils.makeAuthHeader(headerFactory, response,
  381.                         request, username, password);
  382.                 request.addHeader(authHeader);
  383.             }
  384.             inviteTid = sipProvider.getNewClientTransaction(request);
  385. // send the request out.
  386.             inviteTid.sendRequest();
  387.             this.dialog = inviteTid.getDialog();
  388. // Send the request statelessly through the SIP provider.
  389. //            this.sipProvider.sendRequest(request);
  390.  
  391. // Display the message in the text area.
  392.             logger.debug( & amp;quot;
  393.             Request sent:\n & amp;quot;+request.toString() + & amp;quot;\n\n & amp;quot;);
  394.         } catch (Exception e) {
  395. // If an error occurred, display the error.
  396.             e.printStackTrace();
  397.             logger.debug( & amp;quot;
  398.             Request sent failed:
  399.              & amp;quot;+e.getMessage() + & amp;quot;\n & amp;quot;);
  400.         }
  401.     }
  402. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement