Advertisement
sebp

CometClient.java

Jan 4th, 2012
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 12.46 KB | None | 0 0
  1. package essai;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.io.UnsupportedEncodingException;
  7. import java.util.ArrayList;
  8. import java.util.Hashtable;
  9. //import java.util.regex.Matcher;
  10. //import java.util.regex.Pattern;
  11.  
  12. import org.apache.http.HttpResponse;
  13. import org.apache.http.client.ClientProtocolException;
  14. import org.apache.http.client.HttpClient;
  15. import org.apache.http.client.methods.HttpPost;
  16. import org.apache.http.conn.ClientConnectionManager;
  17. import org.apache.http.conn.scheme.PlainSocketFactory;
  18. import org.apache.http.conn.scheme.Scheme;
  19. import org.apache.http.conn.scheme.SchemeRegistry;
  20. import org.apache.http.entity.StringEntity;
  21. import org.apache.http.impl.client.DefaultHttpClient;
  22. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
  23. import org.apache.http.params.BasicHttpParams;
  24. import org.apache.http.params.HttpParams;
  25. import org.json.JSONArray;
  26. import org.json.JSONException;
  27. import org.json.JSONObject;
  28.  
  29. public class CometClient {
  30.  
  31.     private int             requestId;
  32.     private String              cometUri;
  33.     private String              clientId;
  34.     private HttpClient          httpClient;
  35.     private HttpPost            httpPost;
  36.     private HttpParams          httpParams;
  37.     private HttpResponse            httpResponse;
  38.     private SchemeRegistry          schemeRegistry;
  39.     private ClientConnectionManager     clientConnectionManager;
  40.     private InputStreamReader       inputStreamReader;
  41.     private InputStreamHandler      inputStreamHandler;
  42.  
  43.     public  enum                ConnectionStatus {
  44.         DISCONNECTED, HANDSHAKE_ERROR, HANDSHAKE_OK, CONNECTING, CONNECTION_ERROR, CONNECTED
  45.     };
  46.    
  47.     public CometClient(String uri) {
  48.         this.cometUri   = uri + "/cometd";
  49.         this.requestId  = 1;
  50.        
  51.         this.httpParams = new BasicHttpParams();
  52.         this.schemeRegistry = new SchemeRegistry();
  53.         this.schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
  54.         this.clientConnectionManager = new ThreadSafeClientConnManager( this.schemeRegistry);
  55.         this.httpClient = new DefaultHttpClient(this.clientConnectionManager, this.httpParams);
  56.         this.httpPost   = new HttpPost(cometUri);
  57.         this.httpPost.setHeader("Content-Type","application/json; charset=UTF-8");
  58.  
  59.     }
  60.    
  61.     public String getClientId() {
  62.         return this.clientId;
  63.     }
  64.    
  65.     public int getRequestId() {
  66.         return this.requestId;
  67.     }
  68.    
  69.     public InputStreamReader getInputStreamReader() {
  70.         return this.inputStreamReader;
  71.     }
  72.    
  73.     public boolean handshake() {
  74.        
  75.         JSONArray       jsonRequest;
  76.         JSONArray       jsonResponse;
  77.         JSONObject      jsonHandshake;
  78.  
  79.         String          request;
  80.         String          result;
  81.         BufferedReader  buffer;
  82.        
  83.         // Build JSON handshake request
  84.         System.out.print("handshake(): building JSON handshake request... ");
  85.         try {
  86.  
  87.             ArrayList<String> jsonSCT = new ArrayList<String>(1);
  88.             jsonSCT.add("streaming");
  89.  
  90.             Hashtable<String, String> jsonEXT = new Hashtable<String,String>();
  91.  
  92.             // Replace with valid values before use:
  93.             jsonEXT.put("mac","xx:xx:xx:xx:xx:xx");
  94.             jsonEXT.put("rev","x");
  95.             jsonEXT.put("uuid","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
  96.  
  97.             jsonHandshake = new JSONObject()
  98.                 .put("channel","/meta/handshake")
  99.                 .put("ext", jsonEXT)
  100.                 .put("supportedConnectionTypes", jsonSCT)
  101.                 .put("version","1.0");
  102.  
  103.             jsonRequest = new JSONArray()
  104.                 .put(jsonHandshake);
  105.            
  106.             request = jsonRequest.toString();
  107.             System.out.println("done.\n\t" + request);
  108.            
  109.         } catch (JSONException e) {
  110.  
  111.             System.out.println("FAILED!");
  112.             e.printStackTrace();
  113.             return(false);
  114.         }
  115.  
  116.         // Post JSON handshake request
  117.         System.out.print("handshake(): posting request... ");
  118.         try {
  119.                        
  120.             this.httpPost.setEntity(new StringEntity(request,"UTF-8"));
  121.             this.httpResponse = this.httpClient.execute(this.httpPost);
  122.             System.out.println("done.");
  123.            
  124.         } catch(UnsupportedEncodingException e) {
  125.             System.out.println("FAILED!");
  126.             e.printStackTrace();
  127.             return(false);             
  128.            
  129.         } catch(ClientProtocolException e) {
  130.             System.out.println("FAILED!");
  131.             e.printStackTrace();
  132.             return(false);             
  133.            
  134.         } catch(IOException e) {
  135.             System.out.println("FAILED!");
  136.             e.printStackTrace();
  137.             return(false);             
  138.            
  139.         }
  140.        
  141.         // Get Cometd server's response
  142.         System.out.print("handshake(): awaiting response... ");
  143.         try {  
  144.             buffer = new BufferedReader(new InputStreamReader(this.httpResponse.getEntity().getContent(),"UTF-8"));
  145.             result = buffer.readLine();
  146.             System.out.println("done.\n\t" + result);
  147.         } catch(UnsupportedEncodingException e) {
  148.             System.out.println("FAILED!");
  149.             e.printStackTrace();
  150.             return(false);             
  151.            
  152.         } catch(IOException e) {
  153.             System.out.println("FAILED!");
  154.             e.printStackTrace();
  155.             return(false);             
  156.            
  157.         }
  158.    
  159.         // Parse response
  160.         System.out.print("handshake(): parsing response...");
  161.         try {
  162.             jsonResponse = new JSONArray(result);
  163.             jsonHandshake = jsonResponse.getJSONObject(0);
  164.             System.out.println("done");
  165.         } catch ( JSONException e ) {
  166.             System.out.println("FAILED!");
  167.             e.printStackTrace();
  168.             return(false);
  169.         }
  170.  
  171.         // Check response
  172.         System.out.println("handshake(): checking response:");
  173.         try {
  174.             System.out.print("- channel: ");
  175.             System.out.print(jsonHandshake.getString("channel") + " ");
  176.             if( jsonHandshake.getString("channel").equals("/meta/handshake") ) {
  177.                 System.out.println("OK");
  178.             } else {
  179.                 System.out.println("ERROR: Unexpected channel!");
  180.                 return(false);
  181.             }
  182.  
  183.             System.out.print("- successful: ");
  184.             System.out.print(jsonHandshake.getBoolean("successful") + " ");
  185.             if( jsonHandshake.getBoolean("successful") == true ) {
  186.                 System.out.println("OK");
  187.             } else {
  188.                 System.out.println("ERROR: Unexpected result!");
  189.                 return(false);
  190.             }
  191.  
  192.             System.out.print("- clientId: ");
  193.             System.out.print(jsonHandshake.getString("clientId") + " ");
  194.             this.clientId = jsonHandshake.getString("clientId");
  195.             System.out.println("OK");
  196.  
  197.         } catch ( JSONException e ) {
  198.             System.out.println("FAILED!");
  199.             e.printStackTrace();
  200.             return(false);             
  201.         }
  202.            
  203.         // So far, so good!
  204.         System.out.println("handshake(): successfuly completed.\n");
  205.         return(true);
  206.     }
  207.    
  208.    
  209.     public boolean connect() {
  210.  
  211.         JSONArray       jsonRequest;
  212.         JSONObject      jsonConnect;
  213.         String          request;
  214.  
  215.         // Build JSON connect request
  216.         System.out.print("connect(): building JSON connect request... ");
  217.         try {
  218.  
  219.  
  220.             jsonConnect = new JSONObject()
  221.                 .put("channel","/meta/connect")
  222.                 .put("clientId", this.clientId)
  223.                 .put("connectionType", "streaming");
  224.  
  225.             jsonRequest = new JSONArray()
  226.                 .put(jsonConnect);
  227.            
  228.             request = jsonRequest.toString();
  229.             System.out.println("done.\n\t" + request);
  230.            
  231.         } catch (JSONException e) {
  232.  
  233.             System.out.println("FAILED!");
  234.             e.printStackTrace();
  235.             return(false);
  236.         }
  237.  
  238.         // Post JSON connect request
  239.         System.out.print("connect(): posting request... ");
  240.         try {
  241.                        
  242.             this.httpPost.setEntity(new StringEntity(request,"UTF-8"));
  243.             this.httpResponse = this.httpClient.execute(this.httpPost);
  244.             System.out.println("done.");
  245.            
  246.         } catch(UnsupportedEncodingException e) {
  247.             System.out.println("FAILED!");
  248.             e.printStackTrace();
  249.             return(false);             
  250.            
  251.         } catch(ClientProtocolException e) {
  252.             System.out.println("FAILED!");
  253.             e.printStackTrace();
  254.             return(false);             
  255.            
  256.         } catch(IOException e) {
  257.             System.out.println("FAILED!");
  258.             e.printStackTrace();
  259.             return(false);             
  260.            
  261.         }
  262.  
  263.         // Get Cometd server's response
  264.         System.out.print("connect(): dispatching response... ");
  265.         try {
  266.             this.inputStreamReader  = new InputStreamReader(this.httpResponse.getEntity().getContent(),"UTF-8");
  267.             this.inputStreamHandler = new InputStreamHandler(this);
  268.             this.inputStreamHandler.start();
  269.             System.out.println("done.");
  270.            
  271.         } catch( IllegalStateException e) {
  272.             System.out.println("FAILED!");
  273.             e.printStackTrace();
  274.             return(false);             
  275.            
  276.         } catch(IOException e) {
  277.             System.out.println("FAILED!");
  278.             e.printStackTrace();
  279.             return(false);             
  280.            
  281.         }
  282.        
  283.         // So far, so good
  284.         System.out.println("connect(): successfuly completed.\n");
  285.         return true;
  286.     }
  287.  
  288.  
  289.     public boolean subscribe(JSONObject jsonDATA) {
  290.         JSONArray       jsonRequest;
  291.         JSONObject      jsonSubscribe;
  292.         String          request;
  293.  
  294.         // Build JSON connect request
  295.         System.out.print("subscribe(): building JSON subscribe request... ");
  296.         try {
  297.            
  298.             jsonSubscribe = new JSONObject()
  299.                 .put("channel","/slim/subscribe")
  300.                 .put("data", jsonDATA)
  301.                 .put("id", this.requestId++);
  302.            
  303.             jsonRequest = new JSONArray()
  304.                 .put(jsonSubscribe);
  305.                        
  306.             request = jsonRequest.toString();
  307.             System.out.println("done.\n\t" + request);
  308.            
  309.         } catch (JSONException e) {
  310.  
  311.             System.out.println("FAILED!");
  312.             e.printStackTrace();
  313.             return(false);
  314.         }
  315.        
  316.         // Post JSON subscribe request
  317.         System.out.print("subscribe(): posting request... ");
  318.         try {
  319.                        
  320.             this.httpPost.setEntity(new StringEntity(request,"UTF-8"));
  321.             this.httpClient.execute(this.httpPost);
  322.             this.inputStreamReader  = new InputStreamReader(this.httpResponse.getEntity().getContent(),"UTF-8");
  323.             System.out.println("done.");
  324.            
  325.         } catch(UnsupportedEncodingException e) {
  326.             System.out.println("FAILED!");
  327.             e.printStackTrace();
  328.             return(false);             
  329.            
  330.         } catch(ClientProtocolException e) {
  331.             System.out.println("FAILED!");
  332.             e.printStackTrace();
  333.             return(false);             
  334.            
  335.         } catch(IllegalStateException e) {
  336.             System.out.println("FAILED!");
  337.             e.printStackTrace();
  338.             return(false);             
  339.  
  340.         } catch(IOException e) {
  341.             System.out.println("FAILED!");
  342.             e.printStackTrace();
  343.             return(false);             
  344.            
  345.         }
  346.        
  347.         // So far, so good
  348.         System.out.println();
  349.         return true;
  350.     }
  351.  
  352.    
  353.     class InputStreamHandler extends Thread {
  354.        
  355.         private CometClient         parent;
  356.        
  357.         public InputStreamHandler(CometClient parent) {
  358.             this.parent = parent;
  359.         }
  360.        
  361.         public void run() {
  362.            
  363.             StringBuilder   result = new StringBuilder();
  364.             int n = 0;
  365.            
  366.             try {
  367.                     while( n >= 0 ) {
  368.                    
  369.                         char[] buffer = new char[1024];
  370.                    
  371.                         n = this.parent.getInputStreamReader().read(buffer, 0, buffer.length);
  372.                         if( n > 0 ) {
  373.                             result.append(buffer,0,n);
  374.                        
  375.                             if( buffer[n] == '\0' ) {
  376.                                 System.out.println("InputStreamHandler thread: got response :\n\t" + result);
  377.                                
  378.                                 // Parse response
  379.                                 JSONArray   jsonResponse;
  380.                                 System.out.print("InputStreamHandler(): parsing response... ");
  381.                                 try {
  382.                                     jsonResponse = new JSONArray(result.toString());
  383.                                     System.out.println("done.");
  384.                                    
  385.                                 } catch ( JSONException e ) {
  386.                                     System.out.println("FAILED!");
  387.                                     e.printStackTrace();
  388.                                     return;
  389.                                 }
  390.  
  391.                                 // Extract objects
  392.                                 System.out.println("InputStreamHandler(): extracting " + jsonResponse.length() + " objects:");
  393.                                 for( int i=0; i<jsonResponse.length(); i++) {
  394.                                     JSONObject jsonObject;
  395.                                     try {
  396.                                         jsonObject = jsonResponse.getJSONObject(i);
  397.                                         System.out.println("  jsonObject["+i+"]: " + jsonObject.toString());
  398.                                        
  399.                                         String channel = jsonObject.getString("channel");
  400.                                         if( channel.equals("/meta/connect") ) {
  401.                                             if( jsonObject.getBoolean("successful") == true ) {
  402.                                                 System.out.println("InputStreamHandler(): connection successfully completed.");
  403.                                                 result.delete(0, result.length());
  404.                                                 System.out.println("InputStreamHandler(): subscribing to 'serverstatus' now...");
  405.                                                 JSONObject jsonDATA = new JSONObject("{\"request\":[\"\",[\"serverstatus\",0,50,\"subscribe:30\"]],\"response\":\"/" + this.parent.getClientId() + "/slim/serverstatus\"}");
  406.                                                 this.parent.subscribe(jsonDATA);
  407.                                                 System.out.println("InputStreamHandler(): back in town.");
  408.                                             } else {
  409.                                                 System.out.println("InputStreamHandler(): connection failed!");
  410.                                             }
  411.                                         } else if( channel.equals("/slim/subscribe") ) {
  412.                                             System.out.println("InputStreamHandler(): subscription update.");
  413.                                         }
  414.                                     } catch (JSONException e) {
  415.                                         // TODO Auto-generated catch block
  416.                                         e.printStackTrace();
  417.                                     }
  418.                                 }
  419.                            
  420.  
  421.                             }
  422.                         } else {
  423.                             System.out.println("InputStreamHandler thread: input stream is NOT ready.");
  424.                         }
  425.                         Thread.sleep(1000);
  426.                     }
  427.             } catch (IOException e) {
  428.                 // TODO Auto-generated catch block
  429.                 e.printStackTrace();
  430.             } catch (InterruptedException e) {
  431.                 // TODO Auto-generated catch block
  432.                 e.printStackTrace();
  433.             }
  434.         }
  435.        
  436.     }
  437.    
  438. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement