Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   package com.pubnub.api;
   
   import java.io.IOException;
   import java.util.Date;
   import java.util.Enumeration;
   import java.util.Hashtable;
   import java.util.Random;
   
  import  org.json.JSONArray;
  import  org.json.JSONException;
  import  org.json.JSONObject;


Pubnub object facilitates querying channels for messages and listening on channels for presence/message events

Author(s):
Pubnub
  
  
  abstract class PubnubCore {
  
      private String HOSTNAME = "pubsub";
      private int HOSTNAME_SUFFIX = 1;
      private String DOMAIN = "pubnub.com";
      private String ORIGIN_STR = null;
      protected String PUBLISH_KEY = "";
      protected String SUBSCRIBE_KEY = "";
      protected String SECRET_KEY = "";
      private String CIPHER_KEY = "";
      private String IV = null;
      private volatile String AUTH_STR = null;
      private volatile boolean CACHE_BUSTING = true;
      protected Hashtable params;
      private volatile boolean resumeOnReconnect;
  
      private boolean SSL = true;
      protected String UUID = null;
      private Subscriptions subscriptions;
  
      protected SubscribeManager subscribeManager;
      protected TimedTaskManager timedTaskManager;
      private volatile String _timetoken = "0";
      private volatile String _saved_timetoken = "0";
  
      private String PRESENCE_SUFFIX = "-pnpres";
      protected static String VERSION = "";
      private Random generator = new Random();
  
      private static Logger log = new Logger(PubnubCore.class);
  
      protected abstract String getUserAgent();
  
      private int PRESENCE_HEARTBEAT_TASK = 0;
      private int HEARTBEAT = 320;
      private volatile int PRESENCE_HB_INTERVAL = 0;

    
This method when called stops Pubnub threads
  
      public void shutdown() {
          .stop();
          .stop();
          .stop();
      }

    
This method returns the state of Resume on Reconnect setting

Returns:
Current state of Resume On Reconnect Setting
  
      public boolean isResumeOnReconnect() {
          return ;
      }

    
This method sets retry interval for subscribe. Pubnub API will make maxRetries attempts to connect to pubnub servers. These attemtps will be made at an interval of retryInterval milliseconds.

Parameters:
retryInterval Retry Interval in milliseconds
  
      public void setRetryInterval(int retryInterval) {
          .setRetryInterval(retryInterval);
      }

    
This method sets window interval for subscribe.

Parameters:
windowInterval Window Interval in milliseconds
  
     public void setWindowInterval(int windowInterval) {
         .setWindowInterval(windowInterval);
     }

    
Returns current retry interval for subscribe

Returns:
Current Retry Interval in milliseconds
 
     public int getRetryInterval() {
         return .;
     }

    
Returns current window interval for subscribe

Returns:
Current Window Interval in milliseconds
 
     public int getWindowInterval() {
         return .;
     }
 
         String channelString = .getChannelString();
 
         if (channelString.length() <= 0) {
             return null;
         }
         return new String[]{ getPubnubUrl(), "v2""presence""sub-key",
                 this."channel",
                 PubnubUtil.urlEncode(channelString), "heartbeat"
         };
     }
 
     private String getState() {
     	return (..length() > 0)?..toString():null;
     }
     
     class PresenceHeartbeatTask extends TimedTask {
         private Callback callback;
 
         PresenceHeartbeatTask(int intervalCallback callback) {
             super(interval);
             this. = callback;
         }
 
         public void run() {
 
             String[] urlComponents = getPresenceHeartbeatUrl();
             if (urlComponents == null)
                 return;
             //String[] urlComponents = { getPubnubUrl(), "time", "0"};
             
             Hashtable parameters = PubnubUtil.hashtableClone();
             if (parameters.get("uuid") == null)
                 parameters.put("uuid");
             
             String st  = getState();
             if (st != nullparameters.put("state"st);
             
             if ( > 0 &&  < 320 ) parameters.put("heartbeat", String.valueOf());
             
             HttpRequest hreq = new HttpRequest(urlComponentsparameters,
                     new ResponseHandler() {
                 public void handleResponse(HttpRequest hreqString response) {
                     JSONObject jso;
                     try {
                         jso = new JSONObject(response);
                         response = jso.getString("message");
                     } catch (JSONException e) {
                         handleError(hreq,
                                 PubnubError.getErrorObject(., 1, response));
                         return;
                     }
                     .successCallback(.getChannelString(), response);
                 }
 
                 public void handleError(HttpRequest hreqPubnubError error) {
                     .errorCallback(.getChannelString(), error);
                     return;
                 }
             });
 
             _request(hreq);
 
         }
 
     }

    
This method sets presence expiry timeout.

Parameters:
pnexpires Presence Expiry timeout in seconds
 
     public void setPnExpires(int pnexpiresCallback callback) {
     	setHeartbeat(pnexpires,callback);
     }
    
    
This method sets presence expiry timeout.

Parameters:
heartbeat Presence Heartbeat value in seconds
 
     public void setHeartbeat(int heartbeatCallback callback) {
         Callback cb = getWrappedCallback(callback);
 
          = (heartbeat > 0 && heartbeat < 5)?5:heartbeat;
          = ( - 3 >= 1)?:1;
         
         if ( == 0) {
              = .addTask("Presence-Heartbeat",
                     new PresenceHeartbeatTask(cb));
         } else if ( == 0 ||  > 320) {
         } else {
         }
          = heartbeat;
         disconnectAndResubscribe();
     }
 
     public void setPnExpires(int pnexpires) {
         setPnExpires(pnexpiresnull);
     }
     
     public void setHeartbeat(int heartbeat) {
         setHeartbeat(heartbeatnull);
     }
     
     public void setHeartbeatInterval(int heartbeatInterval) {
     	
         Callback cb = getWrappedCallback(null);
     	 = heartbeatInterval;
         if ( == 0) {
              = .addTask("Presence-Heartbeat",
                     new PresenceHeartbeatTask(cb));
         } else if ( == 0 ||  > 320) {
         } else {
         }
     	
     }
     
     public int getHeartbeatInterval() {
     	return ;
     }

    
    
Returns presence expiry timeout value

Returns:
Current presence expiry timeout value
 
     public int getPnExpires() {
         return getHeartbeat();
     }
    
    
Returns presence heartbeat value

Returns:
Current presence heartbeat value
 
     public int getHeartbeat() {
         return ;
     }

    
This methods sets maximum number of retries for subscribe. Pubnub API will make maxRetries attempts to connect to pubnub servers before timing out.

Parameters:
maxRetries Max number of retries
 
     public void setMaxRetries(int maxRetries) {
         .setMaxRetries(maxRetries);
     }

    
Returns current max retries for Subscribe

Returns:
Current max retries
 
     public int getMaxRetries() {
         return .;
     }
 
     protected String getPubnubUrl() {
 
         if ( == null) {
             // SSL On?
             if (this.) {
                  = "https://";
             } else {
                  = "http://";
             }
               += ;
               += ((!this.)?"":"-" + String.valueOf());
               += "." + ;
         }
         return ;
     }
     private Callback voidCallback = new Callback()
     {public void successCallback(String channelObject message) {}};
 
     protected Callback getWrappedCallback(Callback callback){
         if (callback == null) {
             return ;
         } else
             return callback;
     }
 
     private boolean validateInput(String nameObject inputCallback callback) {
 
         if (input == null) {
             callback.errorCallback("", PubnubError.getErrorObject(
                     ., 1, name + " cannot be null"));
             return false;
         }
 
         if (input instanceof String && ((String)input).length() == 0) {
             callback.errorCallback("", PubnubError.getErrorObject(
                     ., 2, name + " cannot be zero length"));
             return false;
         }
         return true;
     }


    
Enable/Disable Cache Busting

Parameters:
cacheBusting
 
     public void setCacheBusting(boolean cacheBusting) {
         this. = cacheBusting;
     }

    
Get Cache Busting value

Returns:
current cache busting setting
 
     public boolean getCacheBusting() {
         return this.;
     }

    
This method returns all channel names currently subscribed to in form of a comma separated String

Returns:
Comma separated string with all channel names currently subscribed
 
         String currentChannels = .getChannelString();
         return currentChannels.equals("") ? "no channels." : currentChannels;
     }

    
If Resume on Reconnect is set to true, then Pubnub catches up on reconnection after disconnection. If false, then messages sent on the channel between disconnection and reconnection are not received.

Parameters:
resumeOnReconnect True or False setting for Resume on Reconnect
 
     public void setResumeOnReconnect(boolean resumeOnReconnect) {
         this. = resumeOnReconnect;
     }

    
Returns Resume on Reconnect current setting

Returns:
Resume on Reconnect setting
 
     public boolean getResumeOnReconnect() {
         return this.;
     }

    
This method returns unique identifier.

Returns:
Unique Identifier .
 
     abstract String uuid();

    
Sets value for UUID

Parameters:
uuid UUID value for Pubnub client
 
     public void setUUID(String uuid) {
         this. = uuid;
     }

    
Gets current UUID

Returns:
uuid current UUID value for Pubnub client
 
     public String getUUID() {
         return this.;
     }

    
Constructor for Pubnub Class

Parameters:
publish_key Publish Key
subscribe_key Subscribe Key
secret_key Secret Key
cipher_key Cipher Key
ssl_on SSL enabled ?
initialization_vector Initialization vector
 
 
     public PubnubCore(String publish_keyString subscribe_key,
             String secret_keyString cipher_keyboolean ssl_onString initialization_vector) {
         this.init(publish_keysubscribe_keysecret_keycipher_keyssl_oninitialization_vector);
     }

    
Constructor for Pubnub Class

Parameters:
publish_key Publish Key
subscribe_key Subscribe Key
secret_key Secret Key
cipher_key Cipher Key
ssl_on SSL enabled ?
 
 
     public PubnubCore(String publish_keyString subscribe_key,
             String secret_keyString cipher_keyboolean ssl_on) {
         this.init(publish_keysubscribe_keysecret_keycipher_keyssl_on);
     }

    
Constructor for Pubnub Class

Parameters:
publish_key Publish Key
subscribe_key Subscribe Key
secret_key Secret Key
ssl_on SSL enabled ?
 
 
     public PubnubCore(String publish_keyString subscribe_key,
             String secret_keyboolean ssl_on) {
         this.init(publish_keysubscribe_keysecret_key""ssl_on);
     }

    
Constructor for Pubnub Class

Parameters:
publish_key Publish Key
subscribe_key Subscribe Key
 
 
     public PubnubCore(String publish_keyString subscribe_key) {
         this.init(publish_keysubscribe_key""""false);
     }

    
Constructor for Pubnub Class

Parameters:
publish_key Publish Key
subscribe_key Subscribe Key
 
 
     public PubnubCore(String publish_keyString subscribe_keyboolean ssl) {
         this.init(publish_keysubscribe_key""""ssl);
     }

    
Constructor for Pubnub Class

Parameters:
publish_key Publish Key
subscribe_key Subscribe Key
secret_key Secret Key
 
     public PubnubCore(String publish_keyString subscribe_key,
             String secret_key) {
         this.init(publish_keysubscribe_keysecret_key""false);
     }

    
Initialize PubNub Object State.

Parameters:
publish_key
subscribe_key
secret_key
cipher_key
ssl_on
 
     private void init(String publish_keyString subscribe_key,
             String secret_keyString cipher_keyboolean ssl_on) {
         this.init(publish_keysubscribe_keysecret_keycipher_keyssl_onnull);
     }


    
Initialize PubNub Object State.

Parameters:
publish_key
subscribe_key
secret_key
cipher_key
ssl_on
 
     private void init(String publish_keyString subscribe_key,
             String secret_keyString cipher_keyboolean ssl_onString initialization_vector) {
         this. = publish_key;
         this. = subscribe_key;
         this. = secret_key;
         this. = cipher_key;
         this. = ssl_on;
 
         if ( == null)
              = uuid();
 
         if ( == null)
              = new Subscriptions();
 
         if ( == null)
              = new SubscribeManager("Subscribe-Manager-"
                     + System.identityHashCode(this), 10000, 310000);
 
         if ( == null)
              = new NonSubscribeManager(
                     "Non-Subscribe-Manager-" + System.identityHashCode(this),
                     10000, 15000);
 
         if ( == null)
              = new TimedTaskManager("TimedTaskManager");
 
         if ( == null)
              = new Hashtable();
 
         .put("pnsdk"getUserAgent());
         .setHeader("V");
         .setHeader("Accept-Encoding""gzip");
         .setHeader("User-Agent"getUserAgent());
 
         .setHeader("V");
         .setHeader("Accept-Encoding""gzip");
         .setHeader("User-Agent"getUserAgent());
 
     }

    
This method sets timeout value for subscribe/presence. Default value is 310000 milliseconds i.e. 310 seconds

Parameters:
timeout Timeout value in milliseconds for subscribe/presence
 
     protected void setSubscribeTimeout(int timeout) {
         .setRequestTimeout(timeout);
         this.disconnectAndResubscribe();
     }
 
     protected int getSubscribeTimeout() {
         return .;
     }

    
This method set timeout value for non subscribe operations like publish, history, hereNow. Default value is 15000 milliseconds i.e. 15 seconds.

Parameters:
timeout Timeout value in milliseconds for Non subscribe operations like publish, history, hereNow
 
     protected void setNonSubscribeTimeout(int timeout) {
         .setRequestTimeout(timeout);
     }
 
     protected int getNonSubscribeTimeout() {
         return .;
     }

    
Send a message to a channel.

Parameters:
channel Channel name
message JSONObject to be published
callback object of sub class of Callback class
 
     public void publish(String channel, JSONObject messageCallback callback) {
         Hashtable args = new Hashtable();
         args.put("channel"channel);
         args.put("message"message);
         args.put("callback"callback);
         publish(args);
     }

    
Send a message to a channel.

Parameters:
channel Channel name
message JSONOArray to be published
callback object of sub class of Callback class
 
     public void publish(String channel, JSONArray messageCallback callback) {
         Hashtable args = new Hashtable();
         args.put("channel"channel);
         args.put("message"message);
         args.put("callback"callback);
         publish(args);
     }

    
Send a message to a channel.

Parameters:
channel Channel name
message String to be published
callback object of sub class of Callback class
 
     public void publish(String channelString messageCallback callback) {
         Hashtable args = new Hashtable();
         args.put("channel"channel);
         args.put("message"message);
         args.put("callback"callback);
         publish(args);
     }

    
Send a message to a channel.

Parameters:
channel Channel name
message Integer to be published
callback object of sub class of Callback class
 
     public void publish(String channelInteger messageCallback callback) {
         Hashtable args = new Hashtable();
         args.put("channel"channel);
         args.put("message"message);
         args.put("callback"callback);
         publish(args);
     }

    
Send a message to a channel.

Parameters:
channel Channel name
message Double to be published
callback object of sub class of Callback class
 
     public void publish(String channelDouble messageCallback callback) {
         Hashtable args = new Hashtable();
         args.put("channel"channel);
         args.put("message"message);
         args.put("callback"callback);
         publish(args);
     }

    
Send a message to a channel.

Parameters:
args Hashtable containing channel name, message.
callback object of sub class of Callback class
 
     protected void publish(Hashtable argsCallback callback) {
         args.put("callback"callback);
         publish(args);
     }

    
Send a message to a channel.

Parameters:
args Hashtable containing channel name, message, callback
 
 
     protected void publish(Hashtable args) {
 
         final String channel = (Stringargs.get("channel");
         final Object message = args.get("message");
         final Callback callback = getWrappedCallback((Callbackargs.get("callback"));
         String msgStr = message.toString();
 
 
         if (this..length() > 0) {
             // Encrypt Message
             PubnubCrypto pc = new PubnubCrypto(this.this.);
             try {
                 if (message instanceof String) {
                     msgStr = "\"" + msgStr + "\"";
                 }
                 msgStr = "\"" + pc.encrypt(msgStr) + "\"";
             } catch (DataLengthException e) {
                 callback.errorCallback(channel,
                         PubnubError.getErrorObject(., 1, msgStr));
                 return;
             } catch (IllegalStateException e) {
                 callback.errorCallback(channel,
                         PubnubError.getErrorObject(., 2, msgStr));
                 return;
             } catch (InvalidCipherTextException e) {
                 callback.errorCallback(channel,
                         PubnubError.getErrorObject(., 3, msgStr));
                 return;
             } catch (Exception e) {
                 callback.errorCallback(channel,
                         PubnubError.getErrorObject(., 4, msgStr + " : " + e.toString()));
                 return;
             }
         } else {
             if (message instanceof String) {
                 msgStr = "\"" + msgStr + "\"";
             }
         }
 
         // Generate String to Sign
         String signature = "0";
 
         if (this..length() > 0) {
             StringBuffer string_to_sign = new StringBuffer();
             string_to_sign.append(this.).append('/')
             .append(this.).append('/')
             .append(this.).append('/').append(channel)
             .append('/').append(msgStr);
 
             // Sign Message
             try {
                 signature = new String(Hex.encode(PubnubCrypto
                         .md5(string_to_sign.toString())), "UTF-8");
             } catch (UnsupportedEncodingException e) {
 
             }
         }
         String[] urlComponents = { getPubnubUrl(), "publish"this.,
                 this., PubnubUtil.urlEncode(signature),
                 PubnubUtil.urlEncode(channel), "0",
                 PubnubUtil.urlEncode(msgStr)
         };
 
         class PublishResponseHandler extends ResponseHandler {
             public void handleResponse(HttpRequest hreqString response) {
                 JSONArray jsarr;
                 try {
                     jsarr = new JSONArray(response);
                 } catch (JSONException e) {
                     handleError(hreq,
                             PubnubError.getErrorObject(., 1, response));
                     return;
                 }
                 callback.successCallback(channeljsarr);
             }
 
             public void handleError(HttpRequest hreqPubnubError error) {
                 callback.errorCallback(channelerror);
                 return;
             }
         }
         HttpRequest hreq = new HttpRequest(urlComponentsnew PublishResponseHandler());
 
         _request(hreq);
     }

    
Listen for presence of subscribers on a channel

Parameters:
channel Name of the channel on which to listen for join/leave i.e. presence events
callback object of sub class of Callback class
Throws:
PubnubException Throws PubnubException if Callback is null
 
     public void presence(String channelCallback callback)
             throws PubnubException {
         Hashtable args = new Hashtable(2);
         args.put("channel"channel + );
         args.put("callback"callback);
         subscribe(args);
     }

    
Read presence information for uuid

Parameters:
uuid UUID
callback object of sub class of Callback class
 
     public void whereNow(final String uuidCallback callback) {
         final Callback cb = getWrappedCallback(callback);
         String[] urlargs = { getPubnubUrl(), "v2""presence""sub_key",
                 this."uuid", PubnubUtil.urlEncode(uuid)
         };
 
         HttpRequest hreq = new HttpRequest(urlargs,
                 new ResponseHandler() {
             public void handleResponse(HttpRequest hreqString response) {
                 invokeCallback(""response"payload"cb, 4);
             }
 
             public void handleError(HttpRequest hreqPubnubError error) {
                 cb.errorCallback(""error);
                 return;
             }
         });
 
         _request(hreq);
     }
 
     public void whereNow(Callback callback) {
         whereNow(this.,callback);
     }
 
     public void setState(String channelString uuid, JSONObject stateCallback callback) {
 
         final Callback cb = getWrappedCallback(callback);
 
         Hashtable parameters = PubnubUtil.hashtableClone();
         String[] urlargs = { getPubnubUrl(), "v2""presence""sub-key",
                 this."channel", PubnubUtil.urlEncode(channel), "uuid", PubnubUtil.urlEncode(uuid),
                 "data"
         };
         if (state != nullparameters.put("state"state.toString());
         Channel ch = .getChannel(channel);
         if (ch != null) {
         	try {
 				..put(channelstate);
 			} catch (JSONException e) {
 
 			}
         }
         HttpRequest hreq = new HttpRequest(urlargsparameters,
                 new ResponseHandler() {
             public void handleResponse(HttpRequest hreqString response) {
                 invokeCallback(""response"payload"cb, 2 );
             }
 
             public void handleError(HttpRequest hreqPubnubError error) {
                 cb.errorCallback(""error);
                 return;
             }
         });
 
         _request(hreq);
     }
 
     protected void invokeCallback(String channelString responseString key,
             Callback callbackint extendedErrorCode) {
         invokeCallback(channelresponsekeycallbackextendedErrorCodefalse);
     }
 
     protected void invokeCallback(String channelString responseString key,
             Callback callbackint extendedErrorCodeboolean key_strict) {
         JSONObject responseJso = null;
         try {
             responseJso = new JSONObject(response);
         } catch (JSONException e) {
             callback.errorCallback(channel,
                     PubnubError.getErrorObject(.extendedErrorCoderesponse));
             return;
         }
 
         JSONObject payloadJso = null;
 
         if (key != null && key.length() > 0) {
             try {
                 payloadJso = (JSONObject) responseJso.get(key);
             } catch (JSONException e) {
                 if (!key_strict) {
                     callback.successCallback(channelresponseJso);
                 } else {
                     callback.errorCallback(channel,
                             PubnubError.getErrorObject(.extendedErrorCoderesponse));
                 }
                 return;
 
             }
             callback.successCallback(channelpayloadJso);
             return;
         }
     }
 
 
     public void getState(String channelString uuidCallback callback) {
         final Callback cb = getWrappedCallback(callback);
         String[] urlargs = { getPubnubUrl(), "v2""presence""sub-key",
                 this."channel", PubnubUtil.urlEncode(channel), "uuid", PubnubUtil.urlEncode(uuid)
         };
 
         HttpRequest hreq = new HttpRequest(urlargs,
                 new ResponseHandler() {
             public void handleResponse(HttpRequest hreqString response) {
                 invokeCallback(""response"payload"cb, 1 );
             }
 
             public void handleError(HttpRequest hreqPubnubError error) {
                 cb.errorCallback(""error);
                 return;
             }
         });
 
         _request(hreq);
     }
    
Read presence information from a channel

Parameters:
channel Channel name
callback object of sub class of Callback class
 
     public void hereNow(final String channelCallback callback) {
         hereNow(channel,false,true,callback);
     }
 
     public void hereNow(boolean stateboolean uuidsCallback callback) {
         hereNow(nullstateuuidscallback);
     }

    
Read presence information from a channel

Parameters:
channel Channel name
state state enabled ?
uuids enable / disable returning uuids in response ?
callback object of sub class of Callback class
 
     public void hereNow(final String channelboolean stateboolean uuidsCallback callback) {
 
         final Callback cb = getWrappedCallback(callback);
 
         Hashtable parameters = PubnubUtil.hashtableClone();
         String[] urlargs = null;
         if (channel != null && channel.length() > 0) {
             urlargs = new String[]{ getPubnubUrl(), "v2""presence""sub_key",
                     this."channel", PubnubUtil.urlEncode(channel)
             };
         } else {
             urlargs = new String[]{ getPubnubUrl(), "v2""presence""sub_key",
                     this.
             };
         }
 
         if (stateparameters.put("state""1");
         if (!uuidsparameters.put("disable_uuids""1");
 
         HttpRequest hreq = new HttpRequest(urlargsparameters,
                 new ResponseHandler() {
             public void handleResponse(HttpRequest hreqString response) {
                 invokeCallback(channelresponse"payload",cb, 1);
             }
 
             public void handleError(HttpRequest hreqPubnubError error) {
                cb.errorCallback(channelerror);
            }
        });
        _request(hreq);
    }

    
Read History for a channel.

Parameters:
channel Channel name for which history is required
start Start time
end End time
count Upper limit on number of messages to be returned
reverse True if messages need to be in reverse order
callback Callback
    public void history(final String channellong startlong end,
            int countboolean reverseCallback callback) {
        final Callback cb = getWrappedCallback(callback);
        Hashtable parameters = PubnubUtil.hashtableClone();
        if (count == -1)
            count = 100;
        parameters.put("count", String.valueOf(count));
        parameters.put("reverse", String.valueOf(reverse));
        if (start != -1)
            parameters.put("start", Long.toString(start).toLowerCase());
        if (end != -1)
            parameters.put("end", Long.toString(end).toLowerCase());
        String[] urlargs = { getPubnubUrl(), "v2""history""sub-key",
                this."channel", PubnubUtil.urlEncode(channel)
        };
        class HistoryResponseHandler extends ResponseHandler {
            public void handleResponse(HttpRequest hreqString response) {
                JSONArray respArr;
                try {
                    respArr = new JSONArray(response);
                    decryptJSONArray((JSONArray) respArr.get(0));
                    cb.successCallback(channelrespArr);
                } catch (JSONException e) {
                    cb.errorCallback(channel,
                            PubnubError.getErrorObject(., 3));
                } catch (DataLengthException e) {
                    cb.errorCallback(channel,
                            PubnubError.getErrorObject(., 6, response));
                } catch (IllegalStateException e) {
                    cb.errorCallback(channel,
                            PubnubError.getErrorObject(., 7, response));
                } catch (InvalidCipherTextException e) {
                    cb.errorCallback(channel,
                            PubnubError.getErrorObject(., 8, response));
                } catch (IOException e) {
                    cb.errorCallback(channel,
                            PubnubError.getErrorObject(., 9, response));
                } catch (Exception e) {
                    cb.errorCallback(channel,
                            PubnubError.getErrorObject(., 10, response + " : " + e.toString()));
                }
            }
            public void handleError(HttpRequest hreqPubnubError error) {
                cb.errorCallback(channelerror);
                return;
            }
        }
        
        HttpRequest hreq = new HttpRequest(urlargsparametersnew HistoryResponseHandler());
        _request(hreq);
    }

    
Read History for a channel.

Parameters:
channel Channel name for which history is required
start Start time
end End time
reverse True if messages need to be in reverse order
callback Callback
    public void history(String channellong startlong end,
            boolean reverseCallback callback) {
        history(channelstartend, -1, reversecallback);
    }

    
Read History for a channel.

Parameters:
channel Channel name for which history is required
count Maximum number of messages
callback Callback object
    public void history(String channelint countCallback callback) {
        history(channel, -1, -1, countfalsecallback);
    }


    
Read History for a channel.

Parameters:
channel Channel name for which history is required
start Start time
reverse True if messages need to be in reverse order
callback Callback
    public void history(String channellong startboolean reverse,
            Callback callback) {
        history(channelstart, -1, -1, reversecallback);
    }

    
Read History for a channel.

Parameters:
channel Channel name for which history is required
start Start time
end End time
callback Callback
    public void history(String channellong startlong end,
            Callback callback) {
        history(channelstartend, -1, falsecallback);
    }

    
Read History for a channel.

Parameters:
channel Channel name for which history is required
start Start time
end End time
count Upper limit on number of messages to be returned
callback Callback
    public void history(String channellong startlong endint count,
            Callback callback) {
        history(channelstartendcountfalsecallback);
    }

    
Read History for a channel.

Parameters:
channel Channel name for which history is required
start Start time
count Upper limit on number of messages to be returned
reverse True if messages need to be in reverse order
callback Callback
    public void history(String channellong startint count,
            boolean reverseCallback callback) {
        history(channelstart, -1, countreversecallback);
    }

    
Read History for a channel.

Parameters:
channel Channel name for which history is required
start Start time
count Upper limit on number of messages to be returned
callback Callback
    public void history(String channellong startint count,
            Callback callback) {
        history(channelstart, -1, countfalsecallback);
    }

    
Read History for a channel.

Parameters:
channel Channel name for which history is required
count Upper limit on number of messages to be returned
reverse True if messages need to be in reverse order
callback Callback
    public void history(String channelint countboolean reverse,
            Callback callback) {
        history(channel, -1, -1, countreversecallback);
    }

    
Read History for a channel.

Parameters:
channel Channel name for which history is required
reverse True if messages need to be in reverse order
callback Callback
    public void history(String channelboolean reverse,
            Callback callback) {
        history(channel, -1, -1, -1, reversecallback);
    }

    
Read current time from PubNub Cloud.

Parameters:
callback Callback object
    public void time(Callback callback) {
        final Callback cb = getWrappedCallback(callback);
        String[] url = { getPubnubUrl(), "time""0" };
        HttpRequest hreq = new HttpRequest(urlnew ResponseHandler() {
            public void handleResponse(HttpRequest hreqString response) {
                cb.successCallback(nullresponse);
            }
            public void handleError(HttpRequest hreqPubnubError error) {
                cb.errorCallback(nullerror);
            }
        });
        _request(hreq);
    }
    private boolean inputsValid(Hashtable argsthrows PubnubException {
        boolean channelMissing;
        if (((Callbackargs.get("callback")) == null) {
            throw new PubnubException("Invalid Callback");
        }
        Object _channels = args.get("channels");
        Object _channel = args.get("channel");
        channelMissing = ((_channel == null || _channel.equals("")) && (_channels == null || _channels
                .equals(""))) ? true : false;
        if (channelMissing) {
            throw new PubnubException("Channel Missing");
        }
        return true;
    }
    private void leave(final String channel) {
        String[] urlargs = { getPubnubUrl(), "v2/presence/sub_key",
                this."channel", PubnubUtil.urlEncode(channel),
                "leave"
        };
        Hashtable params = new Hashtable();
        params.put("uuid");
        HttpRequest hreq = new HttpRequest(urlargsparams,
                new ResponseHandler() {
            public void handleResponse(HttpRequest hreqString response) {
            }
            public void handleError(HttpRequest hreqPubnubError error) {
            }
        });
        _request(hreq);
    }

    
Unsubscribe from channels.

Parameters:
channels String array containing channel names
    public void unsubscribe(String[] channels) {
        for (int i = 0; i < channels.lengthi++) {
            .removeChannel(channels[i]);
            ..remove(channels[i]);
            leave(channels[i]);
        }
        resubscribe();
    }

    
Unsubscribe from all channel.
    public void unsubscribeAll() {
        String[] channels = .getChannelNames();
        for (int i = 0; i < channels.lengthi++) {
            .removeChannel(channels[i]);
            leave(channels[i]);
        }
        disconnectAndResubscribe();
    }

    
Unsubscribe from presence channel.

Parameters:
channel channel name as String.
    public void unsubscribePresence(String channel) {
        unsubscribe(new String[] { channel +  });
    }

    
Unsubscribe/Disconnect from channel.

Parameters:
channel channel name as String.
    public void unsubscribe(String channel) {
        unsubscribe(new String[] { channel });
    }

    
Unsubscribe/Disconnect from channel.

Parameters:
args Hashtable containing channel name.
    protected void unsubscribe(Hashtable args) {
        String[] channelList = (String[]) args.get("channels");
        if (channelList == null) {
            channelList = new String[] { (Stringargs.get("channel") };
        }
        unsubscribe(channelList);
    }

    
Listen for a message on a channel.

Parameters:
args Hashtable containing channel name
callback Callback
Throws:
PubnubException Throws PubnubException if Callback is null
    protected void subscribe(Hashtable argsCallback callback)
            throws PubnubException {
        args.put("callback"callback);
        subscribe(args);
    }

    
Listen for a message on a channel.

Parameters:
args Hashtable containing channel name, callback
Throws:
PubnubException Throws PubnubException if Callback is null
    protected void subscribe(Hashtable argsthrows PubnubException {
        if (!inputsValid(args)) {
            return;
        }
        _subscribe(args);
    }

    
Listen for a message on a channel.

Parameters:
channelsArr Array of channel names (string) to listen on
callback Callback
Throws:
PubnubException Throws PubnubException if Callback is null
    public void subscribe(String[] channelsArrCallback callback)
            throws PubnubException {
        subscribe(channelsArrcallback"0");
    }

    
Listen for a message on a channel.

Parameters:
channelsArr Array of channel names (string) to listen on
callback Callback
timetoken Timetoken to use for subscribing
Throws:
PubnubException Throws PubnubException if Callback is null
    public void subscribe(String[] channelsArrCallback callback,
            String timetokenthrows PubnubException {
        Hashtable args = new Hashtable();
        args.put("channels"channelsArr);
        args.put("callback"callback);
        args.put("timetoken"timetoken);
        subscribe(args);
    }

    
Listen for a message on a channel.

Parameters:
channelsArr Array of channel names (string) to listen on
callback Callback
timetoken Timetoken to use for subscribing
Throws:
PubnubException Throws PubnubException if Callback is null
    public void subscribe(String[] channelsArrCallback callback,
            long timetokenthrows PubnubException {
        Hashtable args = new Hashtable();
        args.put("channels"channelsArr);
        args.put("callback"callback);
        args.put("timetoken", String.valueOf(timetoken));
        subscribe(args);
    }

    
Listen for a message on a channel.

Parameters:
channel Name of the channel
callback Callback
Throws:
PubnubException Throws PubnubException if Callback is null
    public void subscribe(String channelCallback callback)
            throws PubnubException {
        subscribe(channelcallback"0");
    }

    
Listen for a message on a channel.

Parameters:
channel Name of the channel
callback Callback
Throws:
PubnubException Throws PubnubException if Callback is null
    public void subscribe(String channelCallback callback,
            String timetokenthrows PubnubException {
        Hashtable args = new Hashtable();
        args.put("channel"channel);
        args.put("callback"callback);
        args.put("timetoken"timetoken);
        subscribe(args);
    }

    
Listen for a message on a channel.

Parameters:
channel Name of the channel
callback Callback
timetoken Timetoken to use for subscribing
Throws:
PubnubException Throws PubnubException if Callback is null
    public void subscribe(String channelCallback callback,
            long timetokenthrows PubnubException {
        Hashtable args = new Hashtable();
        args.put("channel"channel);
        args.put("callback"callback);
        args.put("timetoken", String.valueOf(timetoken));
        subscribe(args);
    }
    private void callErrorCallbacks(String[] channelListPubnubError error) {
        for (int i = 0; i < channelList.lengthi++) {
            Callback cb = ((Channel.getChannel(channelList[i])).;
            cb.errorCallback(channelList[i], error);
        }
    }
    private void decryptJSONArray(JSONArray messagesthrows JSONException, DataLengthExceptionIllegalStateExceptionInvalidCipherTextExceptionIOException {
        if (.length() > 0) {
            for (int i = 0; i < messages.length(); i++) {
                PubnubCrypto pc = new PubnubCrypto();
                String message;
                message = pc.decrypt(messages.get(i).toString());
                messages.put(i, PubnubUtil.stringToJSON(message));
            }
        }
    }

    

Parameters:
args Hashtable
    private void _subscribe(Hashtable args) {
        String[] channelList = (String[]) args.get("channels");
        if (channelList == null) {
            channelList = new String[] { (Stringargs.get("channel") };
     &n