Back to project page RealtimeMessaging-Android.
The source code is released under:
MIT License
If you think the Android project RealtimeMessaging-Android listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
/** * @fileoverview This file contains the class to create ortc factories * @author ORTC team members (ortc@ibt.pt) *///from w w w.j a va2 s . c om package ibt.ortc.api; import ibt.ortc.extensibility.OnMessage; import ibt.ortc.extensibility.OrtcFactory; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Set; /** * Class containing the methods to create Ortc Client factories and use the Ortc * Rest services <br> * <b>How to use in android:<b> * * <pre> * try { * Ortc ortc = new Ortc(); * * OrtcFactory factory; * * factory = ortc.loadOrtcFactory("IbtRealtimeSJ"); * * client = factory.createClient(); * * HashMap<String, ChannelPermissions> permissions = new HashMap<String, ChannelPermissions>(); * permissions.put("channel1:*", ChannelPermissions.Write); * permissions.put("channel1", ChannelPermissions.Write); * * if (!Ortc.saveAuthentication( * "http://ortc-developers.realtime.co/server/2.1/", true, * "SessionId", false, "APPKEY", 1800, "PVTKEY", permissions)) { * throw new Exception("Was not possible to authenticate"); * } * * client.setClusterUrl(defaultServerUrl); * client.setConnectionMetadata("DroidApp"); * * client.OnConnected = new OnConnected() { * @Override * public void run(final OrtcClient sender) { * runOnUiThread(new Runnable() { * @Override * public void run() { * TextView t = ((TextView) findViewById(R.id.TextViewTitle)); * t.setText("Client connected to: " * + ((OrtcClient) sender).getUrl()); * } * }); * } * }; * * client.OnDisconnected = new OnDisconnected() { * @Override * public void run(OrtcClient sender) { * runOnUiThread(new Runnable() { * @Override * public void run() { * TextView t = ((TextView) findViewById(R.id.TextViewTitle)); * t.setText("Client disconnected"); * } * }); * } * }; * * client.OnSubscribed = new OnSubscribed() { * @Override * public void run(OrtcClient sender, String channel) { * final String subscribedChannel = channel; * runOnUiThread(new Runnable() { * @Override * public void run() { * TextView textViewLog = (TextView) findViewById(R.id.TextViewLog); * textViewLog.append(String.format("Channel subscribed %s\n", * subscribedChannel)); * } * }); * } * }; * * client.OnUnsubscribed = new OnUnsubscribed() { * @Override * public void run(OrtcClient sender, String channel) { * final String subscribedChannel = channel; * runOnUiThread(new Runnable() { * @Override * public void run() { * TextView textViewLog = (TextView) findViewById(R.id.TextViewLog); * textViewLog.append(String.format( * "Channel unsubscribed %s\n", subscribedChannel)); * } * }); * } * }; * * client.OnException = new OnException() { * @Override * public void run(OrtcClient send, Exception ex) { * final Exception exception = ex; * runOnUiThread(new Runnable() { * @Override * public void run() { * TextView textViewLog = (TextView) findViewById(R.id.TextViewLog); * textViewLog.append(String.format("Ortc Error: %s\n", * exception.getMessage())); * } * }); * } * }; * * client.OnReconnected = new OnReconnected() { * @Override * public void run(final OrtcClient sender) { * runOnUiThread(new Runnable() { * @Override * public void run() { * reconnectingTries = 0; * TextView textViewLog = (TextView) findViewById(R.id.TextViewTitle); * textViewLog.setText("Client reconnected to: " * + ((OrtcClient) sender).getUrl()); * } * }); * } * }; * * client.OnReconnecting = new OnReconnecting() { * @Override * public void run(OrtcClient sender) { * runOnUiThread(new Runnable() { * @Override * public void run() { * reconnectingTries++; * TextView textViewLog = (TextView) findViewById(R.id.TextViewTitle); * textViewLog.setText(String.format("Client reconnecting %s", * reconnectingTries)); * } * }); * } * }; * * client.connect(defaultApplicationKey, defaultAuthenticationToken); * * } catch (Exception e) { * System.out.println("ORTC ERROR: " + e.toString()); * } * </pre> * * <br> * <b>How to use in java:<b> * * <pre> * try { * boolean isBalancer = true; * * Ortc api = new Ortc(); * * OrtcFactory factory = api.loadOrtcFactory("IbtRealtimeSJ"); * * final OrtcClient client = factory.createClient(); * * if (isBalancer) { * client.setClusterUrl(serverUrl); * } else { * client.setUrl(serverUrl); * } * * System.out.println(String.format("Connecting to server %s", serverUrl)); * * client.OnConnected = new OnConnected() { * @Override * public void run(OrtcClient sender) { * System.out * .println(String.format("Connected to %s", client.getUrl())); * System.out.println(String.format("Session ID: %s\n", * ((OrtcClient) sender).getSessionId())); * * client.subscribe("channel1", true, new OnMessage() { * @Override * public void run(Object sender, String channel, String message) { * System.out.println(String.format( * "Message received on channel %s: '%s'", channel, * message)); * * ((OrtcClient) sender).send(channel, "Echo " + message); * } * }); * } * }; * * client.OnException = new OnException() { * @Override * public void run(OrtcClient send, Exception ex) { * System.out.println(String.format("Error: '%s'", ex.toString())); * } * }; * * client.OnDisconnected = new OnDisconnected() { * @Override * public void run(OrtcClient sender) { * System.out.println("Disconnected"); * } * }; * * client.OnReconnected = new OnReconnected() { * @Override * public void run(OrtcClient sender) { * System.out.println(String.format("Reconnected to %s", * client.getUrl())); * } * }; * * client.OnReconnecting = new OnReconnecting() { * @Override * public void run(OrtcClient sender) { * System.out.println(String.format("Reconnecting to %s", * client.getUrl())); * } * }; * * client.OnSubscribed = new OnSubscribed() { * @Override * public void run(OrtcClient sender, String channel) { * System.out.println(String.format("Subscribed to channel %s", * channel)); * } * }; * * client.OnUnsubscribed = new OnUnsubscribed() { * @Override * public void run(OrtcClient sender, String channel) { * System.out.println(String.format("Unsubscribed from channel %s", * channel)); * } * }; * * System.out.println("Connecting..."); * client.connect("APPLICATION_KEY", "AUTHENTICATION_TOKEN"); * * } catch (Exception e) { * System.out.println("ORTC ERROR: " + e.toString()); * } * </pre> * * @version 2.1.0 27 Mar 2013 * @author IBT * */ public class Ortc { private static OnMessage onPushNotification; public Ortc() { } /** * Creates an instance of a factory of the specified Ortc plugin type * * @param ortcType * The Ortc plugin type * @return Instance of Ortc factory * @throws InstantiationException * @throws IllegalAccessException * @throws ClassNotFoundException */ public OrtcFactory loadOrtcFactory(String ortcType) throws InstantiationException, IllegalAccessException, ClassNotFoundException { OrtcFactory result = null; // Gets the plugin class definition Class<?> factoryClass = this .getClass() .getClassLoader() .loadClass( String.format("ibt.ortc.plugins.%s.%sFactory", ortcType, ortcType)); if (factoryClass != null) { // Creates an instance of the plugin class result = OrtcFactory.class.cast(factoryClass.newInstance()); } return result; } /** * Saves the authentication token channels permissions in the ORTC server. * * <pre> * HashMap<String, ChannelPermissions> permissions = new HashMap<String, ChannelPermissions>(); * permissions.put("channel1:*", ChannelPermissions.Write); * permissions.put("channel1", ChannelPermissions.Write); * * if (!Ortc.saveAuthentication("http://ortc-developers.realtime.co/server/2.1/", * true, "SessionId", false, "APPKEY", 1800, "PVTKEY", permissions)) { * throw new Exception("Was not possible to authenticate"); * } * </pre> * * @param url * Ortc Server Url * @param isCluster * Indicates whether the ORTC server is in a cluster. * @param authenticationToken * Authentication Token which is generated by the application * server, for instance a unique session ID. * @param authenticationTokenIsPrivate * Indicates whether the authentication token is private (true) * or not (false) * @param applicationKey * Application Key that was provided to you together with the * ORTC service purchasing. * @param timeToLive * The authentication token time to live, in other words, the * allowed activity time (in seconds). * @param privateKey * The private key provided to you together with the ORTC service * purchasing. * @param permissions * The channels and their permissions (w: write/read or r: read * or p: presence, case sensitive). * @return True if the authentication was successful or false if it was not. * @throws ibt.ortc.api.OrtcAuthenticationNotAuthorizedException */ public static boolean saveAuthentication(String url, boolean isCluster, String authenticationToken, boolean authenticationTokenIsPrivate, String applicationKey, int timeToLive, String privateKey, Map<String, ChannelPermissions> permissions) throws IOException, InvalidBalancerServerException, OrtcAuthenticationNotAuthorizedException { String connectionUrl = url; if (isCluster) { connectionUrl = Balancer.getServerFromBalancer(url, applicationKey); } boolean isAuthenticated = false; try { URL authenticationUrl = new URL(String.format("%s/authenticate", connectionUrl)); Map<String, LinkedList<ChannelPermissions>> permissionsMap = new HashMap<String, LinkedList<ChannelPermissions>>(); Set<String> channels = permissions.keySet(); for (String channelName : channels) { LinkedList<ChannelPermissions> channelPermissionList = new LinkedList<ChannelPermissions>(); channelPermissionList.add(permissions.get(channelName)); permissionsMap.put(channelName, channelPermissionList); } isAuthenticated = Authentication.saveAuthentication( authenticationUrl, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, permissionsMap); } catch (Exception e) { throw new OrtcAuthenticationNotAuthorizedException(e.getMessage()); } return isAuthenticated; } /** * Saves the authentication token channels permissions in the ORTC server. * * <pre> * HashMap<String, LinkedList<ChannelPermissions>> permissions = new HashMap<String, LinkedList<ChannelPermissions>>(); * * LinkedList<ChannelPermissions> channelPermissions = new LinkedList<ChannelPermissions>(); * channelPermissions.add(ChannelPermissions.Write); * channelPermissions.add(ChannelPermissions.Presence); * * permissions.put("channel", channelPermissions); * * if (!Ortc.saveAuthentication("http://ortc-developers.realtime.co/server/2.1/", * true, "SessionId", false, "APPKEY", 1800, "PVTKEY", permissions)) { * throw new Exception("Was not possible to authenticate"); * } * </pre> * * @param url * Ortc Server Url * @param isCluster * Indicates whether the ORTC server is in a cluster. * @param authenticationToken * Authentication Token which is generated by the application * server, for instance a unique session ID. * @param authenticationTokenIsPrivate * Indicates whether the authentication token is private (true) * or not (false) * @param applicationKey * Application Key that was provided to you together with the * ORTC service purchasing. * @param timeToLive * The authentication token time to live, in other words, the * allowed activity time (in seconds). * @param privateKey * The private key provided to you together with the ORTC service * purchasing. * @param permissions * HashMap<String,LinkedList<String,ChannelPermissions>& * gt; permissions& The channels and their permissions (w: * write/read or r: read or p: presence, case sensitive). * @return True if the authentication was successful or false if it was not. * @throws ibt.ortc.api.OrtcAuthenticationNotAuthorizedException */ public static boolean saveAuthentication(String url, boolean isCluster, String authenticationToken, boolean authenticationTokenIsPrivate, String applicationKey, int timeToLive, String privateKey, HashMap<String, LinkedList<ChannelPermissions>> permissions) throws IOException, InvalidBalancerServerException, OrtcAuthenticationNotAuthorizedException { String connectionUrl = url; if (isCluster) { connectionUrl = Balancer.getServerFromBalancer(url, applicationKey); } boolean isAuthenticated = false; try { URL authenticationUrl = new URL(String.format("%s/authenticate", connectionUrl)); isAuthenticated = Authentication.saveAuthentication( authenticationUrl, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, permissions); } catch (Exception e) { throw new OrtcAuthenticationNotAuthorizedException(e.getMessage()); } return isAuthenticated; } /** * Asynchronously saves the authentication token channels permissions in the ORTC server. * * <pre> * HashMap<String, ChannelPermissions> permissions = new HashMap<String, ChannelPermissions>(); * permissions.put("channel1:*", ChannelPermissions.Write); * permissions.put("channel1", ChannelPermissions.Write); * * if (!Ortc.saveAuthentication("http://ortc-developers.realtime.co/server/2.1/", * true, "SessionId", false, "APPKEY", 1800, "PVTKEY", permissions)) { * throw new Exception("Was not possible to authenticate"); * } * </pre> * * @param url * Ortc Server Url * @param isCluster * Indicates whether the ORTC server is in a cluster. * @param authenticationToken * Authentication Token which is generated by the application * server, for instance a unique session ID. * @param authenticationTokenIsPrivate * Indicates whether the authentication token is private (true) * or not (false) * @param applicationKey * Application Key that was provided to you together with the * ORTC service purchasing. * @param timeToLive * The authentication token time to live, in other words, the * allowed activity time (in seconds). * @param privateKey * The private key provided to you together with the ORTC service * purchasing. * @param permissions * The channels and their permissions (w: write/read or r: read * or p: presence, case sensitive). * @param onCompleted * The callback that is executed after the save authentication is completed * @throws ibt.ortc.api.OrtcAuthenticationNotAuthorizedException */ public static void saveAuthentication(String url, boolean isCluster, final String authenticationToken, final boolean authenticationTokenIsPrivate, final String applicationKey, final int timeToLive, final String privateKey, final Map<String, ChannelPermissions> permissions, final OnRestWebserviceResponse onCompleted) throws IOException, InvalidBalancerServerException, OrtcAuthenticationNotAuthorizedException { HashMap<String, LinkedList<ChannelPermissions>> permissionsMap = new HashMap<String, LinkedList<ChannelPermissions>>(); Set<String> channels = permissions.keySet(); for (String channelName : channels) { LinkedList<ChannelPermissions> channelPermissionList = new LinkedList<ChannelPermissions>(); channelPermissionList.add(permissions.get(channelName)); permissionsMap.put(channelName, channelPermissionList); } saveAuthentication(url, isCluster, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, permissionsMap, onCompleted); } /** * Saves the authentication token channels permissions in the ORTC server. * * <pre> * HashMap<String, LinkedList<ChannelPermissions>> permissions = new HashMap<String, LinkedList<ChannelPermissions>>(); * * LinkedList<ChannelPermissions> channelPermissions = new LinkedList<ChannelPermissions>(); * channelPermissions.add(ChannelPermissions.Write); * channelPermissions.add(ChannelPermissions.Presence); * * permissions.put("channel", channelPermissions); * * if (!Ortc.saveAuthentication("http://ortc-developers.realtime.co/server/2.1/", * true, "SessionId", false, "APPKEY", 1800, "PVTKEY", permissions)) { * throw new Exception("Was not possible to authenticate"); * } * </pre> * * @param url * Ortc Server Url * @param isCluster * Indicates whether the ORTC server is in a cluster. * @param authenticationToken * Authentication Token which is generated by the application * server, for instance a unique session ID. * @param authenticationTokenIsPrivate * Indicates whether the authentication token is private (true) * or not (false) * @param applicationKey * Application Key that was provided to you together with the * ORTC service purchasing. * @param timeToLive * The authentication token time to live, in other words, the * allowed activity time (in seconds). * @param privateKey * The private key provided to you together with the ORTC service * purchasing. * @param permissions * HashMap<String,LinkedList<String,ChannelPermissions>& * gt; permissions& The channels and their permissions (w: * write/read or r: read or p: presence, case sensitive). * @param onCompleted * The callback that is executed after the save authentication is completed * @throws ibt.ortc.api.OrtcAuthenticationNotAuthorizedException */ public static void saveAuthentication(String url, boolean isCluster, final String authenticationToken, final boolean authenticationTokenIsPrivate, final String applicationKey, final int timeToLive, final String privateKey, final HashMap<String, LinkedList<ChannelPermissions>> permissions, final OnRestWebserviceResponse onCompleted) throws IOException, InvalidBalancerServerException, OrtcAuthenticationNotAuthorizedException { String connectionUrl = url; if (isCluster) { Balancer.getServerFromBalancerAsync(url, applicationKey, new OnRestWebserviceResponse() { @Override public void run(Exception error, String response) { if(error != null){ onCompleted.run(error, null); }else{ saveAuthenticationAsync(response, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, permissions, onCompleted); } } }); }else{ saveAuthenticationAsync(connectionUrl, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, permissions, onCompleted); } } private static void saveAuthenticationAsync(String url, String authenticationToken, boolean authenticationTokenIsPrivate, String applicationKey, int timeToLive, String privateKey, HashMap<String, LinkedList<ChannelPermissions>> permissions, OnRestWebserviceResponse onCompleted){ try { URL authenticationUrl = new URL(String.format("%s/authenticate", url)); Authentication.saveAuthenticationAsync(authenticationUrl, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, permissions, onCompleted); } catch (Exception e) { onCompleted.run(e, null); } } /** * Gets the subscriptions in the specified channel and if active the first * 100 unique metadata. * * <pre> * Ortc.presence("http://ortc-developers.realtime.co/server/2.1/", true, * "APPLICATION_KEY", "AUTHENTICATION_TOKEN", "CHANNEL", new onPresence() { * * public void run(Exception error, Presence presence) { * if (error != null) { * System.out.println(error.getMessage()); * } else { * System.out.println("Subscriptions - " * + presence.getSubscriptions()); * * Iterator<?> metadataIterator = presence.getMetadata() * .entrySet().iterator(); * while (metadataIterator.hasNext()) { * Map.Entry<String, Long> entry = (Map.Entry<String, Long>) metadataIterator * .next(); * System.out.println(entry.getKey() + " - " * + entry.getValue()); * } * } * } * }); * </pre> * * @param url * Server containing the presence service. * @param isCluster * Specifies if url is cluster. * @param applicationKey * Application key with access to presence service. * @param authenticationToken * Authentication token with access to presence service. * @param channel * Channel with presence data active. * @param callback * Callback with error and result. */ public static void presence(String url, Boolean isCluster, String applicationKey, String authenticationToken, String channel, OnPresence callback) { Presence.getPresence(url, isCluster, applicationKey, authenticationToken, channel, callback); } /** * Enables presence for the specified channel with first 100 unique metadata * if metadata is set to true. * * <pre> * Ortc.enablePresence("http://ortc-developers.realtime.co/server/2.1/", true, * "APPLICATION_KEY", "PRIVATE_KEY", "CHANNEL", true, * new onEnablePresence() { * * public void run(Exception error, String result) { * if (error != null) { * System.out.println(error.getMessage()); * } else { * System.out.println(result); * * } * } * }); * </pre> * * @param url * Server containing the presence service. * @param isCluster * Specifies if url is cluster. * @param applicationKey * Application key with access to presence service. * @param privateKey * The private key provided when the ORTC service is purchased. * @param channel * Channel with presence data active. * @param metadata * Defines if to collect first 100 unique metadata. * @param callback * Callback with error and result. */ public static void enablePresence(String url, Boolean isCluster, String applicationKey, String privateKey, String channel, Boolean metadata, OnEnablePresence callback) { Presence.enablePresence(url, isCluster, applicationKey, privateKey, channel, metadata, callback); } /** * Disables presence for the specified channel. * * <pre> * Ortc.disablePresence("http://ortc-developers.realtime.co/server/2.1/", true, * "APPLICATION_KEY", "PRIVATE_KEY", "CHANNEL", new onDisablePresence() { * * public void run(Exception error, String result) { * if (error != null) { * System.out.println(error.getMessage()); * } else { * System.out.println(result); * * } * } * }); * </pre> * * @param url * Server containing the presence service. * @param isCluster * Specifies if url is cluster. * @param applicationKey * Application key with access to presence service. * @param privateKey * The private key provided when the ORTC service is purchased. * @param channel * Channel to disable presence * @param callback * Callback with error and result. */ public static void disablePresence(String url, Boolean isCluster, String applicationKey, String privateKey, String channel, OnDisablePresence callback) { Presence.disablePresence(url, isCluster, applicationKey, privateKey, channel, callback); } /** * Returns the on message event to be executed when a push notification is received and there is a Realtime Client that is not connected * @return onPushNotification */ public static OnMessage getOnPushNotification() { return onPushNotification; } /** * Sets the on message event to be executed when a push notification is received and there is a Realtime Client that is not connected * @param onPushNotification * Executed when a notification is received and there is a Realtime Client that is not connected */ public static void setOnPushNotification(OnMessage onPushNotification) { Ortc.onPushNotification = onPushNotification; } }