diff --git a/build.gradle b/build.gradle index 85c39625..fec5b5d8 100755 --- a/build.gradle +++ b/build.gradle @@ -7,13 +7,13 @@ buildscript { google() } dependencies { - classpath 'com.android.tools.build:gradle:3.0.0' + classpath 'com.android.tools.build:gradle:3.0.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } -ext{ +ext { compileSdkVersion = 26 buildToolsVersion = '26.0.2' supportLibVersion = '27.0.0' diff --git a/gradle.properties b/gradle.properties index 1d3591c8..7791533f 100755 --- a/gradle.properties +++ b/gradle.properties @@ -1,17 +1,13 @@ # Project-wide Gradle settings. - # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. - # For more details on how to configure your build environment visit # http://www.gradle.org/docs/current/userguide/build_environment.html - # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. # Default value: -Xmx10248m -XX:MaxPermSize=256m # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 - # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects diff --git a/org.eclipse.paho.android.sample/src/main/AndroidManifest.xml b/org.eclipse.paho.android.sample/src/main/AndroidManifest.xml index 4c1b846a..7949ba43 100644 --- a/org.eclipse.paho.android.sample/src/main/AndroidManifest.xml +++ b/org.eclipse.paho.android.sample/src/main/AndroidManifest.xml @@ -1,28 +1,28 @@ - + - - + + + android:label="@string/app_name"> - + - + diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/ActionListener.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/ActionListener.java index 2b21248e..2f1e597c 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/ActionListener.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/ActionListener.java @@ -9,10 +9,9 @@ import org.eclipse.paho.android.sample.R; import org.eclipse.paho.android.sample.internal.Connections; import org.eclipse.paho.android.sample.model.Subscription; +import org.eclipse.paho.android.service.MqttAndroidClient; import org.eclipse.paho.client.mqttv3.IMqttActionListener; import org.eclipse.paho.client.mqttv3.IMqttToken; -import org.eclipse.paho.client.mqttv3.MqttException; -import org.eclipse.paho.android.service.MqttAndroidClient; import java.util.ArrayList; @@ -25,30 +24,6 @@ public class ActionListener implements IMqttActionListener { private static final String TAG = "ActionListener"; private static final String activityClass = "org.eclipse.paho.android.sample.activity.MainActivity"; - - /** - * Actions that can be performed Asynchronously and associated with a - * {@link ActionListener} object - */ - enum Action { - /** - * Connect Action - **/ - CONNECT, - /** - * Disconnect Action - **/ - DISCONNECT, - /** - * Subscribe Action - **/ - SUBSCRIBE, - /** - * Publish Action - **/ - PUBLISH - } - /** * The {@link Action} that is associated with this instance of * ActionListener @@ -58,7 +33,6 @@ enum Action { * The arguments passed to be used for formatting strings **/ private final String[] additionalArgs; - private final Connection connection; /** * Handle of the {@link Connection} this action was being executed on @@ -77,8 +51,7 @@ enum Action { * @param connection The connection * @param additionalArgs Used for as arguments for string formating */ - public ActionListener(Context context, Action action, - Connection connection, String... additionalArgs) { + public ActionListener(Context context, Action action, Connection connection, String... additionalArgs) { this.context = context; this.action = action; this.connection = connection; @@ -107,7 +80,6 @@ public void onSuccess(IMqttToken asyncActionToken) { publish(); break; } - } /** @@ -116,14 +88,12 @@ public void onSuccess(IMqttToken asyncActionToken) { * user of success */ private void publish() { - - Connection c = Connections.getInstance(context).getConnection(clientHandle); + Connection connection = Connections.getInstance(context).getConnection(clientHandle); @SuppressLint("StringFormatMatches") String actionTaken = context.getString(R.string.toast_pub_success, - (Object[]) additionalArgs); - c.addAction(actionTaken); + (Object[]) additionalArgs); + connection.addAction(actionTaken); Notify.toast(context, actionTaken, Toast.LENGTH_SHORT); System.out.print("Published"); - } /** @@ -132,13 +102,12 @@ private void publish() { * the user of success */ private void subscribe() { - Connection c = Connections.getInstance(context).getConnection(clientHandle); + Connection connection = Connections.getInstance(context).getConnection(clientHandle); String actionTaken = context.getString(R.string.toast_sub_success, (Object[]) additionalArgs); - c.addAction(actionTaken); + connection.addAction(actionTaken); Notify.toast(context, actionTaken, Toast.LENGTH_SHORT); System.out.print(actionTaken); - } /** @@ -147,16 +116,15 @@ private void subscribe() { * then notify the user of success. */ private void disconnect() { - Connection c = Connections.getInstance(context).getConnection(clientHandle); - c.changeConnectionStatus(Connection.ConnectionStatus.DISCONNECTED); + Connection connection = Connections.getInstance(context).getConnection(clientHandle); + connection.changeConnectionStatus(Connection.ConnectionStatus.DISCONNECTED); String actionTaken = context.getString(R.string.toast_disconnected); - c.addAction(actionTaken); - Log.i(TAG, c.handle() + " disconnected."); + connection.addAction(actionTaken); + Log.i(TAG, connection.handle() + " disconnected."); //build intent Intent intent = new Intent(); intent.setClassName(context, activityClass); intent.putExtra("handle", clientHandle); - } /** @@ -165,16 +133,15 @@ private void disconnect() { * then notify the user of success. */ private void connect() { + Connection connection = Connections.getInstance(context).getConnection(clientHandle); + connection.changeConnectionStatus(Connection.ConnectionStatus.CONNECTED); + connection.addAction("Client Connected"); + Log.i(TAG, connection.handle() + " connected."); - Connection c = Connections.getInstance(context).getConnection(clientHandle); - c.changeConnectionStatus(Connection.ConnectionStatus.CONNECTED); - c.addAction("Client Connected"); - Log.i(TAG, c.handle() + " connected."); - - ArrayList subscriptions = connection.getSubscriptions(); + ArrayList subscriptions = this.connection.getSubscriptions(); for (Subscription sub : subscriptions) { Log.i(TAG, "Auto-subscribing to: " + sub.getTopic() + "@ QoS: " + sub.getQos()); - connection.getClient().subscribe(sub.getTopic(), sub.getQos()); + this.connection.getClient().subscribe(sub.getTopic(), sub.getQos()); } } @@ -200,7 +167,6 @@ public void onFailure(IMqttToken token, Throwable exception) { publish(exception); break; } - } /** @@ -209,13 +175,13 @@ public void onFailure(IMqttToken token, Throwable exception) { * @param exception This argument is not used */ private void publish(Throwable exception) { - Connection c = Connections.getInstance(context).getConnection(clientHandle); - @SuppressLint("StringFormatMatches") String action = context.getString(R.string.toast_pub_failed, + Connection connection = Connections.getInstance(context).getConnection(clientHandle); + @SuppressLint("StringFormatMatches") + String action = context.getString(R.string.toast_pub_failed, (Object[]) additionalArgs); - c.addAction(action); + connection.addAction(action); Notify.toast(context, action, Toast.LENGTH_SHORT); System.out.print("Publish failed"); - } /** @@ -224,13 +190,12 @@ private void publish(Throwable exception) { * @param exception This argument is not used */ private void subscribe(Throwable exception) { - Connection c = Connections.getInstance(context).getConnection(clientHandle); + Connection connection = Connections.getInstance(context).getConnection(clientHandle); String action = context.getString(R.string.toast_sub_failed, (Object[]) additionalArgs); - c.addAction(action); + connection.addAction(action); Notify.toast(context, action, Toast.LENGTH_SHORT); System.out.print(action); - } /** @@ -239,10 +204,9 @@ private void subscribe(Throwable exception) { * @param exception This argument is not used */ private void disconnect(Throwable exception) { - Connection c = Connections.getInstance(context).getConnection(clientHandle); - c.changeConnectionStatus(Connection.ConnectionStatus.DISCONNECTED); - c.addAction("Disconnect Failed - an error occured"); - + Connection connection = Connections.getInstance(context).getConnection(clientHandle); + connection.changeConnectionStatus(Connection.ConnectionStatus.DISCONNECTED); + connection.addAction("Disconnect Failed - an error occured"); } /** @@ -251,11 +215,33 @@ private void disconnect(Throwable exception) { * @param exception This argument is not used */ private void connect(Throwable exception) { - Connection c = Connections.getInstance(context).getConnection(clientHandle); - c.changeConnectionStatus(Connection.ConnectionStatus.ERROR); - c.addAction("Client failed to connect"); + Connection connection = Connections.getInstance(context).getConnection(clientHandle); + connection.changeConnectionStatus(Connection.ConnectionStatus.ERROR); + connection.addAction("Client failed to connect"); System.out.println("Client failed to connect"); + } + /** + * Actions that can be performed Asynchronously and associated with a + * {@link ActionListener} object + */ + enum Action { + /** + * Connect Action + **/ + CONNECT, + /** + * Disconnect Action + **/ + DISCONNECT, + /** + * Subscribe Action + **/ + SUBSCRIBE, + /** + * Publish Action + **/ + PUBLISH } } \ No newline at end of file diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/ActivityConstants.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/ActivityConstants.java index 808696f9..3f7f35f5 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/ActivityConstants.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/ActivityConstants.java @@ -2,23 +2,27 @@ class ActivityConstants { - /** Bundle key for passing a connection around by it's name **/ + /** + * Bundle key for passing a connection around by it's name + **/ public static final String CONNECTION_KEY = "CONNECTION_KEY"; - public static final String AUTO_CONNECT = "AUTO_CONNECT"; public static final String CONNECTED = "CONNECTEd"; - public static final String LOGGING_KEY = "LOGGING_ENABLED"; - - /** Property name for the history field in {@link Connection} object for use with {@link java.beans.PropertyChangeEvent} **/ + /** + * Property name for the history field in {@link Connection} object for use with {@link java.beans.PropertyChangeEvent} + **/ public static final String historyProperty = "history"; - /** Property name for the connection status field in {@link Connection} object for use with {@link java.beans.PropertyChangeEvent} **/ + /** + * Property name for the connection status field in {@link Connection} object for use with {@link java.beans.PropertyChangeEvent} + **/ public static final String ConnectionStatusProperty = "connectionStatus"; - - /** Empty String for comparisons **/ + /** + * Empty String for comparisons + **/ static final String empty = ""; } diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/Connection.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/Connection.java index 0526cd99..ed7b7b47 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/Connection.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/Connection.java @@ -3,8 +3,6 @@ import android.content.Context; import android.content.Intent; -import android.text.Html; -import android.text.Spanned; import org.eclipse.paho.android.sample.R; import org.eclipse.paho.android.sample.internal.IReceivedMessageListener; @@ -27,9 +25,7 @@ import java.util.Map; /** - * * Represents a {@link MqttAndroidClient} and the actions it has performed - * */ public class Connection { /** @@ -37,85 +33,104 @@ public class Connection { */ private static final String activityClass = "org.eclipse.paho.android.sample.activity.MainActivity"; - - /** ClientHandle for this Connection object **/ + /** + * Collection of {@link java.beans.PropertyChangeListener} + **/ + private final ArrayList listeners = new ArrayList(); + /** + * The list of this connection's subscriptions + **/ + private final Map subscriptions = new HashMap(); + private final ArrayList messageHistory = new ArrayList(); + private final ArrayList receivedMessageListeners = new ArrayList(); + /** + * ClientHandle for this Connection object + **/ private String clientHandle = null; - - /** The clientId of the client associated with this Connection object **/ + /** + * The clientId of the client associated with this Connection object + **/ private String clientId = null; - - /** The host that the {@link MqttAndroidClient} represented by this Connection is represented by **/ + /** + * The host that the {@link MqttAndroidClient} represented by this Connection is represented by + **/ private String host = null; - - /** The port on the server that this client is connecting to **/ + /** + * The port on the server that this client is connecting to + **/ private int port = 0; - - /** {@link ConnectionStatus } of the {@link MqttAndroidClient} represented by this Connection object. Default value is {@link ConnectionStatus#NONE} **/ + /** + * {@link ConnectionStatus } of the {@link MqttAndroidClient} represented by this Connection object. Default value is + * {@link ConnectionStatus#NONE} + **/ private ConnectionStatus status = ConnectionStatus.NONE; - - /** Te history of the {@link MqttAndroidClient} represented by this Connection object **/ + /** + * Te history of the {@link MqttAndroidClient} represented by this Connection object + **/ private ArrayList history = null; - - /** The {@link MqttAndroidClient} instance this class represents **/ + /** + * The {@link MqttAndroidClient} instance this class represents + **/ private MqttAndroidClient client = null; - - /** Collection of {@link java.beans.PropertyChangeListener} **/ - private final ArrayList listeners = new ArrayList(); - - /** The {@link Context} of the application this object is part of**/ + /** + * The {@link Context} of the application this object is part of + **/ private Context context = null; - - /** The {@link MqttConnectOptions} that were used to connect this client **/ + /** + * The {@link MqttConnectOptions} that were used to connect this client + **/ private MqttConnectOptions mqttConnectOptions; - - /** True if this connection is secured using TLS **/ + /** + * True if this connection is secured using TLS + **/ private boolean tlsConnection = true; - - /** Persistence id, used by {@link Persistence} **/ + /** + * Persistence id, used by {@link Persistence} + **/ private long persistenceId = -1; - - /** The list of this connection's subscriptions **/ - private final Map subscriptions = new HashMap(); - - private final ArrayList messageHistory = new ArrayList(); - - private final ArrayList receivedMessageListeners = new ArrayList(); - /** - * Connections status for a connection + * Creates a connection object with the server information and the client + * hand which is the reference used to pass the client around activities + * + * @param clientHandle The handle to this Connection object + * @param clientId The Id of the client + * @param host The server which the client is connecting to + * @param port The port on the server which the client will attempt to connect to + * @param context The application context + * @param client The MqttAndroidClient which communicates with the service for this connection + * @param tlsConnection true if the connection is secured by SSL */ - public enum ConnectionStatus { - - /** Client is Connecting **/ - CONNECTING, - /** Client is Connected **/ - CONNECTED, - /** Client is Disconnecting **/ - DISCONNECTING, - /** Client is Disconnected **/ - DISCONNECTED, - /** Client has encountered an Error **/ - ERROR, - /** Status is unknown **/ - NONE + private Connection(String clientHandle, String clientId, String host, + int port, Context context, MqttAndroidClient client, boolean tlsConnection) { + //generate the client handle from its hash code + this.clientHandle = clientHandle; + this.clientId = clientId; + this.host = host; + this.port = port; + this.context = context; + this.client = client; + this.tlsConnection = tlsConnection; + history = new ArrayList<>(); + String sb = "Client: " + clientId + " created"; + addAction(sb); } - /** * Creates a connection from persisted information in the database store, attempting * to create a {@link MqttAndroidClient} and the client handle. - * @param clientId The id of the client - * @param host the server which the client is connecting to - * @param port the port on the server which the client will attempt to connect to - * @param context the application context + * + * @param clientId The id of the client + * @param host the server which the client is connecting to + * @param port the port on the server which the client will attempt to connect to + * @param context the application context * @param tlsConnection true if the connection is secured by SSL * @return a new instance of Connection */ - public static Connection createConnection(String clientHandle, String clientId, String host, int port, Context context, boolean tlsConnection){ + public static Connection createConnection(String clientHandle, String clientId, String host, int port, Context context, boolean tlsConnection) { String uri; - if(tlsConnection) { + if (tlsConnection) { uri = "ssl://" + host + ":" + port; } else { uri = "tcp://" + host + ":" + port; @@ -125,9 +140,9 @@ public static Connection createConnection(String clientHandle, String clientId, return new Connection(clientHandle, clientId, host, port, context, client, tlsConnection); } - public void updateConnection(String clientId, String host, int port, boolean tlsConnection){ + public void updateConnection(String clientId, String host, int port, boolean tlsConnection) { String uri; - if(tlsConnection) { + if (tlsConnection) { uri = "ssl://" + host + ":" + port; } else { uri = "tcp://" + host + ":" + port; @@ -138,40 +153,11 @@ public void updateConnection(String clientId, String host, int port, boolean tls this.port = port; this.tlsConnection = tlsConnection; this.client = new MqttAndroidClient(context, uri, clientId); - - } - - - /** - * Creates a connection object with the server information and the client - * hand which is the reference used to pass the client around activities - * @param clientHandle The handle to this Connection object - * @param clientId The Id of the client - * @param host The server which the client is connecting to - * @param port The port on the server which the client will attempt to connect to - * @param context The application context - * @param client The MqttAndroidClient which communicates with the service for this connection - * @param tlsConnection true if the connection is secured by SSL - */ - private Connection(String clientHandle, String clientId, String host, - int port, Context context, MqttAndroidClient client, boolean tlsConnection) { - //generate the client handle from its hash code - this.clientHandle = clientHandle; - this.clientId = clientId; - this.host = host; - this.port = port; - this.context = context; - this.client = client; - this.tlsConnection = tlsConnection; - history = new ArrayList(); - String sb = "Client: " + - clientId + - " created"; - addAction(sb); } /** * Add an action to the history of the client + * * @param action the history item to add */ public void addAction(String action) { @@ -188,6 +174,7 @@ public void addAction(String action) { /** * Gets the client handle for this connection + * * @return client Handle for this connection */ public String handle() { @@ -196,6 +183,7 @@ public String handle() { /** * Determines if the client is connected + * * @return is the client connected */ public boolean isConnected() { @@ -204,6 +192,7 @@ public boolean isConnected() { /** * Changes the connection status of the client + * * @param connectionStatus The connection status of this connection */ public void changeConnectionStatus(ConnectionStatus connectionStatus) { @@ -215,7 +204,6 @@ public void changeConnectionStatus(ConnectionStatus connectionStatus) { * A string representing the state of the client this connection * object represents * - * * @return A string representing the state of the client */ @Override @@ -225,23 +213,22 @@ public String toString() { sb.append("\n "); switch (status) { - - case CONNECTED : + case CONNECTED: sb.append(context.getString(R.string.connection_connected_to)); break; - case DISCONNECTED : + case DISCONNECTED: sb.append(context.getString(R.string.connection_disconnected_from)); break; - case NONE : + case NONE: sb.append(context.getString(R.string.connection_unknown_status)); break; - case CONNECTING : + case CONNECTING: sb.append(context.getString(R.string.connection_connecting_to)); break; - case DISCONNECTING : + case DISCONNECTING: sb.append(context.getString(R.string.connection_disconnecting_from)); break; - case ERROR : + case ERROR: sb.append(context.getString(R.string.connection_error_connecting_to)); } sb.append(" "); @@ -253,6 +240,7 @@ public String toString() { /** * Compares two connection objects for equality * this only takes account of the client handle + * * @param o The object to compare to * @return true if the client handles match */ @@ -262,14 +250,15 @@ public boolean equals(Object o) { return false; } - Connection c = (Connection) o; + Connection connection = (Connection) o; - return clientHandle.equals(c.clientHandle); + return clientHandle.equals(connection.clientHandle); } /** * Get the client Id for the client this object represents + * * @return the client id for the client this object represents */ public String getId() { @@ -278,15 +267,16 @@ public String getId() { /** * Get the host name of the server that this connection object is associated with + * * @return the host name of the server this connection object is associated with */ public String getHostName() { - return host; } /** * Gets the client which communicates with the org.eclipse.paho.android.service service. + * * @return the client which communicates with the org.eclipse.paho.android.service service */ public MqttAndroidClient getClient() { @@ -295,45 +285,45 @@ public MqttAndroidClient getClient() { /** * Add the connectOptions used to connect the client to the server + * * @param connectOptions the connectOptions used to connect to the server */ public void addConnectionOptions(MqttConnectOptions connectOptions) { mqttConnectOptions = connectOptions; - } /** * Get the connectOptions used to connect this client to the server + * * @return The connectOptions used to connect the client to the server */ - public MqttConnectOptions getConnectionOptions() - { + public MqttConnectOptions getConnectionOptions() { return mqttConnectOptions; } /** * Register a {@link PropertyChangeListener} to this object + * * @param listener the listener to register */ - public void registerChangeListener(PropertyChangeListener listener) - { + public void registerChangeListener(PropertyChangeListener listener) { listeners.add(listener); } /** * Notify {@link PropertyChangeListener} objects that the object has been updated + * * @param propertyChangeEvent - The property Change event */ - private void notifyListeners(PropertyChangeEvent propertyChangeEvent) - { - for (PropertyChangeListener listener : listeners) - { + private void notifyListeners(PropertyChangeEvent propertyChangeEvent) { + for (PropertyChangeListener listener : listeners) { listener.propertyChange(propertyChangeEvent); } } /** * Gets the port that this connection connects to. + * * @return port that this connection connects to */ public int getPort() { @@ -342,6 +332,7 @@ public int getPort() { /** * Determines if the connection is secured using SSL, returning a C style integer value + * * @return 1 if SSL secured 0 if plain text */ public int isSSL() { @@ -350,6 +341,7 @@ public int isSSL() { /** * Assign a persistence ID to this object + * * @param id the persistence id to assign */ public void assignPersistenceId(long id) { @@ -358,67 +350,63 @@ public void assignPersistenceId(long id) { /** * Returns the persistence ID assigned to this object + * * @return the persistence ID assigned to this object */ public long persistenceId() { return persistenceId; } - - public void addNewSubscription(Subscription subscription) throws MqttException { - if(!subscriptions.containsKey(subscription.getTopic())){ - try{ + if (!subscriptions.containsKey(subscription.getTopic())) { + try { String[] actionArgs = new String[1]; actionArgs[0] = subscription.getTopic(); - final ActionListener callback = new ActionListener(this.context, - ActionListener.Action.SUBSCRIBE, this, actionArgs); + final ActionListener callback = new ActionListener(this.context, ActionListener.Action.SUBSCRIBE, this, actionArgs); this.getClient().subscribe(subscription.getTopic(), subscription.getQos(), null, callback); Persistence persistence = new Persistence(context); long rowId = persistence.persistSubscription(subscription); subscription.setPersistenceId(rowId); subscriptions.put(subscription.getTopic(), subscription); - } catch (PersistenceException pe){ + } catch (PersistenceException pe) { throw new MqttException(pe); } } } - - public void unsubscribe (Subscription subscription) throws MqttException { - if(subscriptions.containsKey(subscription.getTopic())){ + public void unsubscribe(Subscription subscription) throws MqttException { + if (subscriptions.containsKey(subscription.getTopic())) { this.getClient().unsubscribe(subscription.getTopic()); subscriptions.remove(subscription.getTopic()); Persistence persistence = new Persistence(context); persistence.deleteSubscription(subscription); } - - } - - public void setSubscriptions(ArrayList newSubs){ - for(Subscription sub : newSubs){ - subscriptions.put(sub.getTopic(), sub); - } } - public ArrayList getSubscriptions(){ + public ArrayList getSubscriptions() { ArrayList subs = new ArrayList(); subs.addAll(subscriptions.values()); return subs; } - public void addReceivedMessageListner(IReceivedMessageListener listener){ + public void setSubscriptions(ArrayList newSubs) { + for (Subscription sub : newSubs) { + subscriptions.put(sub.getTopic(), sub); + } + } + + public void addReceivedMessageListner(IReceivedMessageListener listener) { receivedMessageListeners.add(listener); } - public void messageArrived(String topic, MqttMessage message){ + public void messageArrived(String topic, MqttMessage message) { ReceivedMessage msg = new ReceivedMessage(topic, message); messageHistory.add(0, msg); - if(subscriptions.containsKey(topic)){ + if (subscriptions.containsKey(topic)) { subscriptions.get(topic).setLastMessage(new String(message.getPayload())); - if(subscriptions.get(topic).isEnableNotifications()){ + if (subscriptions.get(topic).isEnableNotifications()) { //create intent to start activity Intent intent = new Intent(); intent.setClassName(context, activityClass); @@ -432,21 +420,48 @@ public void messageArrived(String topic, MqttMessage message){ //notify the user Notify.notifcation(context, context.getString(R.string.notification, notifyArgs), intent, R.string.notifyTitle); - } } - for(IReceivedMessageListener listener : receivedMessageListeners){ + for (IReceivedMessageListener listener : receivedMessageListeners) { listener.onMessageReceived(msg); } - } - public ArrayList getMessages(){ + public ArrayList getMessages() { return messageHistory; } + /** + * Connections status for a connection + */ + public enum ConnectionStatus { + /** + * Client is Connecting + **/ + CONNECTING, + /** + * Client is Connected + **/ + CONNECTED, + /** + * Client is Disconnecting + **/ + DISCONNECTING, + /** + * Client is Disconnected + **/ + DISCONNECTED, + /** + * Client has encountered an Error + **/ + ERROR, + /** + * Status is unknown + **/ + NONE + } } diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/ConnectionFragment.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/ConnectionFragment.java index 8b5b43b3..ad3c1bb4 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/ConnectionFragment.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/ConnectionFragment.java @@ -10,8 +10,10 @@ import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.Switch; + import org.eclipse.paho.android.sample.R; import org.eclipse.paho.android.sample.internal.Connections; + import java.util.Map; @@ -27,8 +29,7 @@ public ConnectionFragment() { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - Map connections = Connections.getInstance(this.getActivity()) - .getConnections(); + Map connections = Connections.getInstance(this.getActivity()).getConnections(); connection = connections.get(this.getArguments().getString(ActivityConstants.CONNECTION_KEY)); boolean connected = this.getArguments().getBoolean(ActivityConstants.CONNECTED, false); @@ -36,14 +37,10 @@ public void onCreate(Bundle savedInstanceState) { } @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_connection, container, false); - - - Bundle bundle = new Bundle(); bundle.putString(ActivityConstants.CONNECTION_KEY, connection.handle()); @@ -55,21 +52,19 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, mTabHost.addTab(mTabHost.newTabSpec("Publish").setIndicator("Publish"), PublishFragment.class, bundle); mTabHost.addTab(mTabHost.newTabSpec("Subscribe").setIndicator("Subscribe"), SubscriptionFragment.class, bundle); return rootView; - } - private void changeConnectedState(boolean state){ + private void changeConnectedState(boolean state) { mTabHost.getTabWidget().getChildTabViewAt(1).setEnabled(state); mTabHost.getTabWidget().getChildTabViewAt(2).setEnabled(state); connectSwitch.setChecked(state); } @Override - public void onCreateOptionsMenu(final Menu menu, MenuInflater inflater){ + public void onCreateOptionsMenu(final Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_connection, menu); - - connectSwitch = (Switch) menu.findItem(R.id.connect_switch).getActionView().findViewById(R.id.switchForActionBar); + connectSwitch = (Switch) menu.findItem(R.id.connect_switch).getActionView().findViewById(R.id.switchForActionBar); connectSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/EditConnectionFragment.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/EditConnectionFragment.java index 89aaf90c..3cd70ec2 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/EditConnectionFragment.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/EditConnectionFragment.java @@ -17,6 +17,7 @@ import android.widget.EditText; import android.widget.Spinner; import android.widget.Switch; + import org.eclipse.paho.android.sample.R; import org.eclipse.paho.android.sample.internal.Connections; import org.eclipse.paho.android.sample.model.ConnectionModel; @@ -27,6 +28,9 @@ public class EditConnectionFragment extends Fragment { + private static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + private static final Random random = new Random(); + private static final int length = 8; private EditText clientId; private EditText serverHostname; private EditText serverPort; @@ -41,14 +45,9 @@ public class EditConnectionFragment extends Fragment { private EditText lwtMessage; private Spinner lwtQos; private Switch lwtRetain; - private ConnectionModel formModel; private boolean newConnection = true; - private static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - private static final Random random = new Random(); - private static final int length = 8; - public EditConnectionFragment() { // Required empty public constructor } @@ -56,12 +55,11 @@ public EditConnectionFragment() { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setHasOptionsMenu(true); + setHasOptionsMenu(true); } @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_edit_connection, container, false); clientId = (EditText) rootView.findViewById(R.id.client_id); serverHostname = (EditText) rootView.findViewById(R.id.hostname); @@ -80,21 +78,16 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, lwtRetain = (Switch) rootView.findViewById(R.id.retain_switch); - - ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.qos_options, android.R.layout.simple_spinner_item); + ArrayAdapter adapter = ArrayAdapter + .createFromResource(getActivity(), R.array.qos_options, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); lwtQos.setAdapter(adapter); - - - - - if(this.getArguments() != null && this.getArguments().getString(ActivityConstants.CONNECTION_KEY) != null){ + if (this.getArguments() != null && this.getArguments().getString(ActivityConstants.CONNECTION_KEY) != null) { /** This Form is referencing an existing connection. **/ //this.getArguments().getString(ActivityConstants.CONNECTION_KEY) - Map connections = Connections.getInstance(this.getActivity()) - .getConnections(); + Map connections = Connections.getInstance(this.getActivity()).getConnections(); String connectionKey = this.getArguments().getString(ActivityConstants.CONNECTION_KEY); Connection connection = connections.get(connectionKey); System.out.println("Editing an existing connection: " + connection.handle()); @@ -104,22 +97,19 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, formModel.setClientHandle(connection.handle()); populateFromConnectionModel(formModel); - } else { formModel = new ConnectionModel(); populateFromConnectionModel(formModel); - } setFormItemListeners(); - // Inflate the layout for this fragment return rootView; } - private void setFormItemListeners(){ - clientId.addTextChangedListener(new TextWatcher() { + private void setFormItemListeners() { + clientId.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { @@ -302,7 +292,7 @@ public void onTextChanged(CharSequence s, int start, int before, int count) { @Override public void afterTextChanged(Editable s) { - formModel.setLwtTopic(s.toString()); + formModel.setLwtTopic(s.toString()); } }); lwtMessage.addTextChangedListener(new TextWatcher() { @@ -346,7 +336,7 @@ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { private void populateFromConnectionModel(ConnectionModel connectionModel) { clientId.setText(connectionModel.getClientId()); serverHostname.setText(connectionModel.getServerHostName()); - serverPort.setText(Integer.toString(connectionModel.getServerPort())); + serverPort.setText(Integer.toString(connectionModel.getServerPort())); cleanSession.setChecked(connectionModel.isCleanSession()); username.setText(connectionModel.getUsername()); password.setText(connectionModel.getPassword()); @@ -360,13 +350,13 @@ private void populateFromConnectionModel(ConnectionModel connectionModel) { lwtRetain.setChecked(connectionModel.isLwtRetain()); } - private void saveConnection(){ + private void saveConnection() { System.out.println("SAVING CONNECTION"); System.out.println(formModel.toString()); - if(newConnection){ + if (newConnection) { // Generate a new Client Handle StringBuilder sb = new StringBuilder(length); - for (int i = 0; i < length; i++){ + for (int i = 0; i < length; i++) { sb.append(AB.charAt(random.nextInt(AB.length()))); } String clientHandle = sb.toString() + '-' + formModel.getServerHostName() + '-' + formModel.getClientId(); @@ -379,7 +369,6 @@ private void saveConnection(){ ((MainActivity) getActivity()).updateAndConnect(formModel); } - } @Override diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/FragmentDrawer.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/FragmentDrawer.java index 2386de2f..c86eff90 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/FragmentDrawer.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/FragmentDrawer.java @@ -25,12 +25,12 @@ public class FragmentDrawer extends Fragment { + private final List data = new ArrayList(); private ActionBarDrawerToggle mDrawerToggle; private DrawerLayout mDrawerLayout; private NavigationDrawerAdapter adapter; private View containerView; private FragmentDrawerListener drawerListener; - private final List data = new ArrayList(); public FragmentDrawer() { @@ -40,19 +40,18 @@ public void setDrawerListener(FragmentDrawerListener listener) { this.drawerListener = listener; } - public void addConnection(Connection connection){ + public void addConnection(Connection connection) { System.out.println("Adding new Connection: " + connection.getId()); NavDrawerItem navItem = new NavDrawerItem(connection); data.add(navItem); adapter.notifyDataSetChanged(); - } public void updateConnection(Connection connection) { System.out.println("Updating Connection: " + connection.getId()); Iterator iterator = data.iterator(); int index = 0; - while(iterator.hasNext()) { + while (iterator.hasNext()) { NavDrawerItem item = iterator.next(); if (item.getHandle().equals(connection.handle())) { item = new NavDrawerItem(connection); @@ -64,11 +63,11 @@ public void updateConnection(Connection connection) { adapter.notifyDataSetChanged(); } - public void removeConnection(Connection connection){ + public void removeConnection(Connection connection) { System.out.println("Removing connection from drawer: " + connection.getId()); Iterator iterator = data.iterator(); - while(iterator.hasNext()) { + while (iterator.hasNext()) { NavDrawerItem item = iterator.next(); if (item.getHandle().equals(connection.handle())) { iterator.remove(); @@ -77,26 +76,22 @@ public void removeConnection(Connection connection){ adapter.notifyDataSetChanged(); } - public void clearConnections(){ + public void clearConnections() { data.clear(); adapter.notifyDataSetChanged(); } - public void notifyDataSetChanged(){ + public void notifyDataSetChanged() { adapter.notifyDataSetChanged(); } private List getData() { - - - - return data; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + Bundle savedInstanceState) { // Inflating view layout View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false); RecyclerView recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList); @@ -111,7 +106,6 @@ public void onClick(View v) { } }); - TextView helpTextView = (TextView) layout.findViewById(R.id.action_help); helpTextView.setOnClickListener(new View.OnClickListener() { @@ -122,7 +116,6 @@ public void onClick(View v) { } }); - adapter = new NavigationDrawerAdapter(getActivity(), getData()); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); @@ -175,7 +168,6 @@ public void run() { mDrawerToggle.syncState(); } }); - } public interface ClickListener { @@ -184,6 +176,16 @@ public interface ClickListener { void onLongClick(int position); } + public interface FragmentDrawerListener { + void onDrawerItemSelected(int position); + + void onDrawerItemLongSelected(int position); + + void onAddConnectionSelected(); + + void onHelpSelected(); + } + static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener { private final GestureDetector gestureDetector; @@ -202,7 +204,6 @@ public void onLongPress(MotionEvent e) { View child = recyclerView.findChildViewUnder(e.getX(), e.getY()); if (child != null && clickListener != null) { clickListener.onLongClick(recyclerView.getChildPosition(child)); - } } }); @@ -227,13 +228,5 @@ public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { } - - } - - public interface FragmentDrawerListener { - void onDrawerItemSelected(int position); - void onDrawerItemLongSelected(int position); - void onAddConnectionSelected(); - void onHelpSelected(); } } \ No newline at end of file diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/HelpFragment.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/HelpFragment.java index 70cc5a33..6c6c27cd 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/HelpFragment.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/HelpFragment.java @@ -37,21 +37,15 @@ public class HelpFragment extends Fragment { private static final String PAHO_WEBSITE = "http://www.eclipse.org/paho/"; - public HelpFragment() { // Required empty public constructor } @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View rootView = inflater.inflate(R.layout.fragment_help, container, false); - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(rootView.getContext()); - - Button websiteButton = (Button) rootView.findViewById(R.id.websiteButton); websiteButton.setOnClickListener(new View.OnClickListener() { @Override @@ -79,11 +73,11 @@ public void onClick(View v) { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Map connections = Connections.getInstance(rootView.getContext()) .getConnections(); - if(!connections.isEmpty()){ + if (!connections.isEmpty()) { Map.Entry entry = connections.entrySet().iterator().next(); Connection connection = entry.getValue(); connection.getClient().setTraceEnabled(isChecked); - if(isChecked){ + if (isChecked) { connection.getClient().setTraceCallback(new MqttTraceCallback()); } Log.i(TAG, "Trace was set to: " + isChecked); @@ -93,28 +87,24 @@ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { } }); - - // Inflate the layout for this fragment return rootView; } - private String getDebugInfoForEmail(){ + private String getDebugInfoForEmail() { StringBuilder sb = new StringBuilder(); try { PackageInfo pInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0); sb.append(FEEDBACK_VERSION + pInfo.versionName + FEEDBACK_NEW_LINE); - } catch(PackageManager.NameNotFoundException ex){ + } catch (PackageManager.NameNotFoundException ex) { sb.append(FEEDBACK_VERSION + FEEDBACK_UNKNOWN + FEEDBACK_NEW_LINE); } - sb.append(FEEDBACK_PHONE_MODEL + Build.MANUFACTURER + " " +Build.MODEL + FEEDBACK_NEW_LINE); + sb.append(FEEDBACK_PHONE_MODEL + Build.MANUFACTURER + " " + Build.MODEL + FEEDBACK_NEW_LINE); sb.append(FEEDBACK_ANDROID_VERSION + Build.VERSION.SDK_INT); - - return sb.toString(); } } \ No newline at end of file diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/HistoryFragment.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/HistoryFragment.java index dd701698..31387713 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/HistoryFragment.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/HistoryFragment.java @@ -22,19 +22,16 @@ public class HistoryFragment extends Fragment { private MessageListItemAdapter messageListAdapter; - private ArrayList messages; - public HistoryFragment() { + public HistoryFragment() { setHasOptionsMenu(true); - } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - Map connections = Connections.getInstance(this.getActivity()) - .getConnections(); + Map connections = Connections.getInstance(this.getActivity()).getConnections(); Connection connection = connections.get(this.getArguments().getString(ActivityConstants.CONNECTION_KEY)); System.out.println("History Fragment: " + connection.getId()); setHasOptionsMenu(true); @@ -49,15 +46,10 @@ public void onMessageReceived(ReceivedMessage message) { }); - - - } @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_connection_history, container, false); @@ -76,12 +68,7 @@ public void onClick(View v) { // Inflate the layout for this fragment return rootView; - - - - } - } diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/HomeFragment.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/HomeFragment.java index 7e79306e..d5d425b9 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/HomeFragment.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/HomeFragment.java @@ -16,9 +16,7 @@ public HomeFragment() { } @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_home, container, false); diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/MainActivity.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/MainActivity.java index c8cad822..e2adbacc 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/MainActivity.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/MainActivity.java @@ -1,23 +1,20 @@ package org.eclipse.paho.android.sample.activity; - -import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.DrawerLayout; -import android.util.Log; -import android.view.Menu; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; +import android.util.Log; +import android.view.Menu; import org.eclipse.paho.android.sample.R; import org.eclipse.paho.android.sample.internal.Connections; import org.eclipse.paho.android.sample.model.ConnectionModel; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; -import org.eclipse.paho.client.mqttv3.MqttException; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; @@ -26,16 +23,12 @@ import java.util.Map; -public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener{ - - private FragmentDrawer drawerFragment; +public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener { private static final String TAG = "MainActivity"; - private final ChangeListener changeListener = new ChangeListener(); - private final MainActivity mainActivity = this; - + private FragmentDrawer drawerFragment; private ArrayList connectionMap; @Override @@ -55,13 +48,13 @@ protected void onCreate(Bundle savedInstanceState) { populateConnectionList(); } - public void removeConnectionRow(Connection connection){ + public void removeConnectionRow(Connection connection) { drawerFragment.removeConnection(connection); populateConnectionList(); } - private void populateConnectionList(){ + private void populateConnectionList() { // Clear drawerFragment drawerFragment.clearConnections(); @@ -72,14 +65,14 @@ private void populateConnectionList(){ connectionMap = new ArrayList(); Iterator connectionIterator = connections.entrySet().iterator(); - while (connectionIterator.hasNext()){ + while (connectionIterator.hasNext()) { Map.Entry pair = (Map.Entry) connectionIterator.next(); drawerFragment.addConnection((Connection) pair.getValue()); connectionMap.add((String) pair.getKey()); ++connectionIndex; } - if(connectionMap.size() == 0){ + if (connectionMap.size() == 0) { displayView(-1); } else { displayView(0); @@ -94,20 +87,19 @@ public boolean onCreateOptionsMenu(Menu menu) { } - @Override - public void onDrawerItemSelected(int position){ + public void onDrawerItemSelected(int position) { displayView(position); } @Override - public void onDrawerItemLongSelected(int position){ + public void onDrawerItemLongSelected(int position) { displayDeleteView(position); } @Override public void onAddConnectionSelected() { - Fragment editConnectionFragment = new EditConnectionFragment(); + Fragment editConnectionFragment = new EditConnectionFragment(); String title = "Edit Connection"; displayFragment(editConnectionFragment, title); } @@ -116,14 +108,13 @@ public void onAddConnectionSelected() { public void onHelpSelected() { Fragment helpFragment = new HelpFragment(); displayFragment(helpFragment, getString(R.string.help_and_feedback)); - } - private void displayDeleteView(int position){ - if(position == -1){ + private void displayDeleteView(int position) { + if (position == -1) { displayFragment(new HomeFragment(), "Home"); } else { - Fragment fragment = new ManageConnectionFragment(); + Fragment fragment = new ManageConnectionFragment(); Bundle bundle = new Bundle(); bundle.putString(ActivityConstants.CONNECTION_KEY, connectionMap.get(position)); fragment.setArguments(bundle); @@ -134,11 +125,11 @@ private void displayDeleteView(int position){ } } - private void displayView(int position){ - if(position == -1){ + private void displayView(int position) { + if (position == -1) { displayFragment(new HomeFragment(), "Home"); } else { - Fragment fragment = new ConnectionFragment(); + Fragment fragment = new ConnectionFragment(); Bundle bundle = new Bundle(); bundle.putString(ActivityConstants.CONNECTION_KEY, connectionMap.get(position)); fragment.setArguments(bundle); @@ -150,8 +141,8 @@ private void displayView(int position){ } } - private void displayFragment(Fragment fragment, String title){ - if (fragment != null){ + private void displayFragment(Fragment fragment, String title) { + if (fragment != null) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.container_body, fragment); @@ -164,7 +155,7 @@ private void displayFragment(Fragment fragment, String title){ } } - public void updateAndConnect(ConnectionModel model){ + public void updateAndConnect(ConnectionModel model) { Map connections = Connections.getInstance(this) .getConnections(); @@ -172,7 +163,7 @@ public void updateAndConnect(ConnectionModel model){ Connection connection = connections.get(model.getClientHandle()); // First disconnect the current instance of this connection - if(connection.isConnected()){ + if (connection.isConnected()) { connection.changeConnectionStatus(Connection.ConnectionStatus.DISCONNECTING); connection.getClient().disconnect(); } @@ -193,7 +184,7 @@ public void updateAndConnect(ConnectionModel model){ drawerFragment.updateConnection(connection); connection.getClient().connect(connOpts, null, callback); - Fragment fragment = new ConnectionFragment(); + Fragment fragment = new ConnectionFragment(); Bundle bundle = new Bundle(); bundle.putString(ActivityConstants.CONNECTION_KEY, connection.handle()); fragment.setArguments(bundle); @@ -201,15 +192,17 @@ public void updateAndConnect(ConnectionModel model){ displayFragment(fragment, title); } - /** * Takes a {@link ConnectionModel} and uses it to connect * and then persist. + * * @param model - The connection Model */ - public void persistAndConnect(ConnectionModel model){ + public void persistAndConnect(ConnectionModel model) { Log.i(TAG, "Persisting new connection:" + model.getClientHandle()); - Connection connection = Connection.createConnection(model.getClientHandle(),model.getClientId(),model.getServerHostName(),model.getServerPort(),this,model.isTlsConnection()); + Connection connection = Connection + .createConnection(model.getClientHandle(), model.getClientId(), model.getServerHostName(), model.getServerPort(), this, model + .isTlsConnection()); connection.registerChangeListener(changeListener); connection.changeConnectionStatus(Connection.ConnectionStatus.CONNECTING); @@ -221,7 +214,6 @@ public void persistAndConnect(ConnectionModel model){ connection.getClient().setCallback(new MqttCallbackHandler(this, model.getClientHandle())); - connection.getClient().setTraceCallback(new MqttTraceCallback()); MqttConnectOptions connOpts = optionsFromModel(model); @@ -232,7 +224,7 @@ public void persistAndConnect(ConnectionModel model){ drawerFragment.addConnection(connection); connection.getClient().connect(connOpts, null, callback); - Fragment fragment = new ConnectionFragment(); + Fragment fragment = new ConnectionFragment(); Bundle bundle = new Bundle(); bundle.putString(ActivityConstants.CONNECTION_KEY, connection.handle()); bundle.putBoolean(ActivityConstants.CONNECTED, true); @@ -242,23 +234,20 @@ public void persistAndConnect(ConnectionModel model){ } - - - - private MqttConnectOptions optionsFromModel(ConnectionModel model){ + private MqttConnectOptions optionsFromModel(ConnectionModel model) { MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setCleanSession(model.isCleanSession()); connOpts.setConnectionTimeout(model.getTimeout()); connOpts.setKeepAliveInterval(model.getKeepAlive()); - if(!model.getUsername().equals(ActivityConstants.empty)){ + if (!model.getUsername().equals(ActivityConstants.empty)) { connOpts.setUserName(model.getUsername()); } - if(!model.getPassword().equals(ActivityConstants.empty)){ + if (!model.getPassword().equals(ActivityConstants.empty)) { connOpts.setPassword(model.getPassword().toCharArray()); } - if(!model.getLwtTopic().equals(ActivityConstants.empty) && !model.getLwtMessage().equals(ActivityConstants.empty)){ + if (!model.getLwtTopic().equals(ActivityConstants.empty) && !model.getLwtMessage().equals(ActivityConstants.empty)) { connOpts.setWill(model.getLwtTopic(), model.getLwtMessage().getBytes(), model.getLwtQos(), model.isLwtRetain()); } // if(tlsConnection){ @@ -269,8 +258,6 @@ private MqttConnectOptions optionsFromModel(ConnectionModel model){ } - - public void connect(Connection connection) { String[] actionArgs = new String[1]; actionArgs[0] = connection.getId(); @@ -280,23 +267,20 @@ public void connect(Connection connection) { connection.getClient().connect(connection.getConnectionOptions(), null, callback); } - public void disconnect(Connection connection){ + public void disconnect(Connection connection) { connection.getClient().disconnect(); } - public void publish(Connection connection, String topic, String message, int qos, boolean retain){ + public void publish(Connection connection, String topic, String message, int qos, boolean retain) { String[] actionArgs = new String[2]; actionArgs[0] = message; actionArgs[1] = topic; - final ActionListener callback = new ActionListener(this, - ActionListener.Action.PUBLISH, connection, actionArgs); + final ActionListener callback = new ActionListener(this, ActionListener.Action.PUBLISH, connection, actionArgs); connection.getClient().publish(topic, message.getBytes(), qos, retain, null, callback); } /** * This class ensures that the user interface is updated as the Connection objects change their states - * - * */ private class ChangeListener implements PropertyChangeListener { diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/ManageConnectionFragment.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/ManageConnectionFragment.java index ae3b4e48..cb9294d4 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/ManageConnectionFragment.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/ManageConnectionFragment.java @@ -44,17 +44,15 @@ public ManageConnectionFragment() { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - connections = Connections.getInstance(this.getActivity()) + connections = Connections.getInstance(this.getActivity()) .getConnections(); connectionKey = this.getArguments().getString(ActivityConstants.CONNECTION_KEY); connection = connections.get(connectionKey); setHasOptionsMenu(false); - } @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_manage, container, false); final String name = connection.getId() + "@" + connection.getHostName() + ":" + connection.getPort(); TextView label = (TextView) rootView.findViewById(R.id.connection_id_text); @@ -64,7 +62,7 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, deleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - System.out.println("Deleting Connection: " + name + "."); + System.out.println("Deleting Connection: " + name + "."); connections.remove(connectionKey); Connections.getInstance(getActivity()).removeConnection(connection); FragmentManager fragmentManager = getFragmentManager(); @@ -91,7 +89,6 @@ public void onClick(View v) { } }); - // Inflate the layout for this fragment return rootView; } diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/MessagesFragment.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/MessagesFragment.java index 4155517f..8e881b86 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/MessagesFragment.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/MessagesFragment.java @@ -16,9 +16,7 @@ public MessagesFragment() { } @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_publish, container, false); diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/MqttCallbackHandler.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/MqttCallbackHandler.java index 93d1f230..fb2d0f71 100755 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/MqttCallbackHandler.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/MqttCallbackHandler.java @@ -25,77 +25,80 @@ /** * Handles call backs from the MQTT Client - * */ class MqttCallbackHandler implements MqttCallback { - /** {@link Context} for the application used to format and import external strings**/ - private final Context context; - /** Client handle to reference the connection that this handler is attached to**/ - private final String clientHandle; - - private static final String TAG = "MqttCallbackHandler"; + private static final String TAG = "MqttCallbackHandler"; private static final String activityClass = "org.eclipse.paho.android.sample.activity.MainActivity"; - - /** - * Creates an MqttCallbackHandler object - * @param context The application's context - * @param clientHandle The handle to a {@link Connection} object - */ - public MqttCallbackHandler(Context context, String clientHandle) - { - this.context = context; - this.clientHandle = clientHandle; - } - - /** - * @see org.eclipse.paho.client.mqttv3.MqttCallback#connectionLost(java.lang.Throwable) - */ - @Override - public void connectionLost(Throwable cause) { - if (cause != null) { - Log.d(TAG, "Connection Lost: " + cause.getMessage()); - Connection c = Connections.getInstance(context).getConnection(clientHandle); - c.addAction("Connection Lost"); - c.changeConnectionStatus(Connection.ConnectionStatus.DISCONNECTED); - - String message = context.getString(R.string.connection_lost, c.getId(), c.getHostName()); - - //build intent - Intent intent = new Intent(); - intent.setClassName(context, activityClass); - intent.putExtra("handle", clientHandle); - - //notify the user - Notify.notifcation(context, message, intent, R.string.notifyTitle_connectionLost); + /** + * {@link Context} for the application used to format and import external strings + **/ + private final Context context; + /** + * Client handle to reference the connection that this handler is attached to + **/ + private final String clientHandle; + + /** + * Creates an MqttCallbackHandler object + * + * @param context The application's context + * @param clientHandle The handle to a {@link Connection} object + */ + public MqttCallbackHandler(Context context, String clientHandle) { + this.context = context; + this.clientHandle = clientHandle; } - } - /** - * @see org.eclipse.paho.client.mqttv3.MqttCallback#messageArrived(java.lang.String, org.eclipse.paho.client.mqttv3.MqttMessage) - */ - @Override - public void messageArrived(String topic, MqttMessage message) throws Exception { + /** + * @see org.eclipse.paho.client.mqttv3.MqttCallback#connectionLost(java.lang.Throwable) + */ + @Override + public void connectionLost(Throwable cause) { + if (cause != null) { + Log.d(TAG, "Connection Lost: " + cause.getMessage()); + Connection c = Connections.getInstance(context).getConnection(clientHandle); + c.addAction("Connection Lost"); + c.changeConnectionStatus(Connection.ConnectionStatus.DISCONNECTED); + + String message = context.getString(R.string.connection_lost, c.getId(), c.getHostName()); + + //build intent + Intent intent = new Intent(); + intent.setClassName(context, activityClass); + intent.putExtra("handle", clientHandle); + + //notify the user + Notify.notifcation(context, message, intent, R.string.notifyTitle_connectionLost); + } + } - //Get connection object associated with this object - Connection c = Connections.getInstance(context).getConnection(clientHandle); - c.messageArrived(topic, message); - //get the string from strings.xml and format - String messageString = context.getString(R.string.messageRecieved, new String(message.getPayload()), topic+";qos:"+message.getQos()+";retained:"+message.isRetained()); + /** + * @see org.eclipse.paho.client.mqttv3.MqttCallback#messageArrived(java.lang.String, org.eclipse.paho.client.mqttv3.MqttMessage) + */ + @Override + public void messageArrived(String topic, MqttMessage message) throws Exception { - Log.i(TAG, messageString); + //Get connection object associated with this object + Connection connection = Connections.getInstance(context).getConnection(clientHandle); + connection.messageArrived(topic, message); + //get the string from strings.xml and format + String messageString = context + .getString(R.string.messageRecieved, new String(message.getPayload()), topic + ";qos:" + message.getQos() + ";retained:" + message + .isRetained()); - //update client history - c.addAction(messageString); + Log.i(TAG, messageString); - } + //update client history + connection.addAction(messageString); + } - /** - * @see org.eclipse.paho.client.mqttv3.MqttCallback#deliveryComplete(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken) - */ - @Override - public void deliveryComplete(IMqttDeliveryToken token) { - // Do nothing - } + /** + * @see org.eclipse.paho.client.mqttv3.MqttCallback#deliveryComplete(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken) + */ + @Override + public void deliveryComplete(IMqttDeliveryToken token) { + // Do nothing + } } diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/Notify.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/Notify.java index 35337280..3c18ed38 100755 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/Notify.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/Notify.java @@ -24,64 +24,66 @@ /** * Provides static methods for creating and showing notifications to the user. - * */ class Notify { - /** Message ID Counter **/ - private static int MessageID = 0; - - /** - * Displays a notification in the notification area of the UI - * @param context Context from which to create the notification - * @param messageString The string to display to the user as a message - * @param intent The intent which will start the activity when the user clicks the notification - * @param notificationTitle The resource reference to the notification title - */ - static void notifcation(Context context, String messageString, Intent intent, int notificationTitle) { + /** + * Message ID Counter + **/ + private static int MessageID = 0; - //Get the notification manage which we will use to display the notification - String ns = Context.NOTIFICATION_SERVICE; - NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns); + /** + * Displays a notification in the notification area of the UI + * + * @param context Context from which to create the notification + * @param messageString The string to display to the user as a message + * @param intent The intent which will start the activity when the user clicks the notification + * @param notificationTitle The resource reference to the notification title + */ + static void notifcation(Context context, String messageString, Intent intent, int notificationTitle) { - long when = System.currentTimeMillis(); + //Get the notification manage which we will use to display the notification + String ns = Context.NOTIFICATION_SERVICE; + NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns); - //get the notification title from the application's strings.xml file - CharSequence contentTitle = context.getString(notificationTitle); + long when = System.currentTimeMillis(); - //the message that will be displayed as the ticker - String ticker = contentTitle + " " + messageString; + //get the notification title from the application's strings.xml file + CharSequence contentTitle = context.getString(notificationTitle); - //build the pending intent that will start the appropriate activity - PendingIntent pendingIntent = PendingIntent.getActivity(context, - 0, intent, 0); + //the message that will be displayed as the ticker + String ticker = contentTitle + " " + messageString; - //build the notification - Builder notificationCompat = new Builder(context); - notificationCompat.setAutoCancel(true) - .setContentTitle(contentTitle) - .setContentIntent(pendingIntent) - .setContentText(messageString) - .setTicker(ticker) - .setWhen(when) - .setSmallIcon(R.mipmap.ic_launcher); + //build the pending intent that will start the appropriate activity + PendingIntent pendingIntent = PendingIntent.getActivity(context, + 0, intent, 0); - Notification notification = notificationCompat.build(); - //display the notification - mNotificationManager.notify(MessageID, notification); - MessageID++; + //build the notification + Builder notificationCompat = new Builder(context); + notificationCompat.setAutoCancel(true) + .setContentTitle(contentTitle) + .setContentIntent(pendingIntent) + .setContentText(messageString) + .setTicker(ticker) + .setWhen(when) + .setSmallIcon(R.mipmap.ic_launcher); - } + Notification notification = notificationCompat.build(); + //display the notification + mNotificationManager.notify(MessageID, notification); + MessageID++; + } - /** - * Display a toast notification to the user - * @param context Context from which to create a notification - * @param text The text the toast should display - * @param duration The amount of time for the toast to appear to the user - */ - static void toast(Context context, CharSequence text, @SuppressWarnings("SameParameterValue") int duration) { - Toast toast = Toast.makeText(context, text, duration); - toast.show(); - } + /** + * Display a toast notification to the user + * + * @param context Context from which to create a notification + * @param text The text the toast should display + * @param duration The amount of time for the toast to appear to the user + */ + static void toast(Context context, CharSequence text, @SuppressWarnings("SameParameterValue") int duration) { + Toast toast = Toast.makeText(context, text, duration); + toast.show(); + } } diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/PublishFragment.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/PublishFragment.java index 086f17aa..99452417 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/PublishFragment.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/PublishFragment.java @@ -37,18 +37,15 @@ public PublishFragment() { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - Map connections = Connections.getInstance(this.getActivity()) - .getConnections(); + Map connections = Connections.getInstance(this.getActivity()).getConnections(); connection = connections.get(this.getArguments().getString(ActivityConstants.CONNECTION_KEY)); System.out.println("FRAGMENT CONNECTION: " + this.getArguments().getString(ActivityConstants.CONNECTION_KEY)); System.out.println("NAME:" + connection.getId()); - } @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View rootView = inflater.inflate(R.layout.fragment_publish, container, false); EditText topicText = (EditText) rootView.findViewById(R.id.topic); EditText messageText = (EditText) rootView.findViewById(R.id.message); @@ -109,7 +106,8 @@ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { } }); - ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.qos_options, android.R.layout.simple_spinner_item); + ArrayAdapter adapter = ArrayAdapter + .createFromResource(getActivity(), R.array.qos_options, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); qos.setAdapter(adapter); @@ -117,17 +115,14 @@ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { publishButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - System.out.println("Publising: [topic: " + topic + ", message: " + message + ", QoS: " + selectedQos + ", Retain: " + retainValue + "]"); + System.out.println("Publising: [topic: " + topic + ", message: " + message + ", QoS: " + selectedQos + ", Retain: " + retainValue + + "]"); ((MainActivity) getActivity()).publish(connection, topic, message, selectedQos, retainValue); - - } }); - // Inflate the layout for this fragment return rootView; } - } \ No newline at end of file diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/SubscriptionFragment.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/SubscriptionFragment.java index 46f5f8e8..afd5ddc2 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/SubscriptionFragment.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/activity/SubscriptionFragment.java @@ -6,7 +6,6 @@ import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; -import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -20,9 +19,9 @@ import android.widget.Switch; import org.eclipse.paho.android.sample.R; -import org.eclipse.paho.android.sample.model.Subscription; import org.eclipse.paho.android.sample.components.SubscriptionListItemAdapter; import org.eclipse.paho.android.sample.internal.Connections; +import org.eclipse.paho.android.sample.model.Subscription; import org.eclipse.paho.client.mqttv3.MqttException; import java.util.ArrayList; @@ -45,18 +44,15 @@ public SubscriptionFragment() { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - Bundle bundle = this.getArguments(); + Bundle bundle = this.getArguments(); String connectionHandle = bundle.getString(ActivityConstants.CONNECTION_KEY); - Map connections = Connections.getInstance(this.getActivity()) - .getConnections(); + Map connections = Connections.getInstance(this.getActivity()).getConnections(); connection = connections.get(connectionHandle); subscriptions = connection.getSubscriptions(); - } @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_subscriptions, container, false); Button subscribeButton = (Button) rootView.findViewById(R.id.subscribe_button); @@ -83,18 +79,18 @@ public void onUnsubscribe(Subscription subscription) { }); subscriptionListView.setAdapter(adapter); - // Inflate the layout for this fragment return rootView; } - private void showInputDialog(){ - LayoutInflater layoutInflater = (LayoutInflater) this.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); + private void showInputDialog() { + LayoutInflater layoutInflater = (LayoutInflater) this.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); @SuppressLint("InflateParams") View promptView = layoutInflater.inflate(R.layout.subscription_dialog, null); final EditText topicText = (EditText) promptView.findViewById(R.id.subscription_topic_edit_text); final Spinner qos = (Spinner) promptView.findViewById(R.id.subscription_qos_spinner); - final ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.qos_options, android.R.layout.simple_spinner_item); + final ArrayAdapter adapter = ArrayAdapter + .createFromResource(getActivity(), R.array.qos_options, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); qos.setAdapter(adapter); qos.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @@ -111,9 +107,6 @@ public void onNothingSelected(AdapterView parent) { final Switch notifySwitch = (Switch) promptView.findViewById(R.id.show_notifications_switch); - - - AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity()); alertDialogBuilder.setView(promptView); alertDialogBuilder.setCancelable(true).setPositiveButton(R.string.subscribe_ok, new DialogInterface.OnClickListener() { @@ -124,7 +117,6 @@ public void onClick(DialogInterface dialog, int id) { subscriptions.add(subscription); try { connection.addNewSubscription(subscription); - } catch (MqttException ex) { System.out.println("MqttException whilst subscribing: " + ex.getMessage()); } @@ -137,7 +129,7 @@ public void onClick(DialogInterface dialog, int id) { } }); - AlertDialog alert = alertDialogBuilder.create(); + AlertDialog alert = alertDialogBuilder.create(); alert.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); alert.show(); } diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/adapter/NavigationDrawerAdapter.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/adapter/NavigationDrawerAdapter.java index aa7e4985..36271ee9 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/adapter/NavigationDrawerAdapter.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/adapter/NavigationDrawerAdapter.java @@ -13,13 +13,14 @@ import java.util.Collections; import java.util.List; + import org.eclipse.paho.android.sample.R; import org.eclipse.paho.android.sample.model.NavDrawerItem; public class NavigationDrawerAdapter extends RecyclerView.Adapter { - private List data = Collections.emptyList(); private final LayoutInflater inflater; private final Context context; + private List data = Collections.emptyList(); public NavigationDrawerAdapter(Context context, List data) { this.context = context; diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/components/MessageListItemAdapter.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/components/MessageListItemAdapter.java index b4080bac..850dc9c1 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/components/MessageListItemAdapter.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/components/MessageListItemAdapter.java @@ -16,21 +16,20 @@ import java.util.ArrayList; -public class MessageListItemAdapter extends ArrayAdapter{ +public class MessageListItemAdapter extends ArrayAdapter { private final Context context; private final ArrayList messages; - public MessageListItemAdapter(Context context, ArrayList messages){ + public MessageListItemAdapter(Context context, ArrayList messages) { super(context, R.layout.message_list_item, messages); this.context = context; this.messages = messages; - } @NonNull @Override - public View getView(final int position, View convertView, @NonNull ViewGroup parent){ + public View getView(final int position, View convertView, @NonNull ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = inflater.inflate(R.layout.message_list_item, parent, false); TextView topicTextView = (TextView) rowView.findViewById(R.id.message_topic_text); diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/components/SubscriptionListItemAdapter.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/components/SubscriptionListItemAdapter.java index c5506088..a1d3499f 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/components/SubscriptionListItemAdapter.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/components/SubscriptionListItemAdapter.java @@ -14,33 +14,33 @@ import java.util.ArrayList; -public class SubscriptionListItemAdapter extends ArrayAdapter{ +public class SubscriptionListItemAdapter extends ArrayAdapter { private final Context context; private final ArrayList topics; private final ArrayList unsubscribeListners = new ArrayList(); - //private final Map topics; - public SubscriptionListItemAdapter(Context context, ArrayList topics){ + public SubscriptionListItemAdapter(Context context, ArrayList topics) { super(context, R.layout.subscription_list_item, topics); this.context = context; this.topics = topics; - } @NonNull @Override - public View getView(final int position, View convertView, @NonNull ViewGroup parent){ + public View getView(final int position, View convertView, @NonNull ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = inflater.inflate(R.layout.subscription_list_item, parent, false); TextView topicTextView = (TextView) rowView.findViewById(R.id.message_text); ImageView topicDeleteButton = (ImageView) rowView.findViewById(R.id.topic_delete_image); - TextView qosTextView = (TextView) rowView.findViewById(R.id.qos_label); + TextView qosTextView = (TextView) rowView.findViewById(R.id.qos_label); topicTextView.setText(topics.get(position).getTopic()); String qosString = context.getString(R.string.qos_text, topics.get(position).getQos()); qosTextView.setText(qosString); TextView notifyTextView = (TextView) rowView.findViewById(R.id.show_notifications_label); - String notifyString = context.getString(R.string.notify_text, (topics.get(position).isEnableNotifications() ? context.getString(R.string.enabled) : context.getString(R.string.disabled))); + String notifyString = context + .getString(R.string.notify_text, (topics.get(position).isEnableNotifications() ? context.getString(R.string.enabled) : context + .getString(R.string.disabled))); notifyTextView.setText(notifyString); topicDeleteButton.setOnClickListener(new View.OnClickListener() { @@ -58,14 +58,12 @@ public void onClick(View v) { return rowView; } - public void addOnUnsubscribeListner(OnUnsubscribeListner listner){ + public void addOnUnsubscribeListner(OnUnsubscribeListner listner) { unsubscribeListners.add(listner); } - public interface OnUnsubscribeListner{ + public interface OnUnsubscribeListner { void onUnsubscribe(Subscription subscription); } - - } diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/components/TextSelectComponent.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/components/TextSelectComponent.java index fcd36bbf..558b12a4 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/components/TextSelectComponent.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/components/TextSelectComponent.java @@ -30,14 +30,10 @@ public class TextSelectComponent extends RelativeLayout { private final TextView subLabel; private final String inputTitle; - - - private String setText; private final boolean numberInput; - private final ArrayList registeredCallbacks = new ArrayList(); - private final Context context; + private String setText; public TextSelectComponent(Context context, AttributeSet attr) { super(context, attr); @@ -62,15 +58,14 @@ public void onClick(View v) { attributeArray.recycle(); } - - - private void showInputDialog(){ + private void showInputDialog() { LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - @SuppressLint("InflateParams") View promptView = layoutInflater.inflate(R.layout.text_input_dialog, null); + @SuppressLint("InflateParams") + View promptView = layoutInflater.inflate(R.layout.text_input_dialog, null); TextView promptText = (TextView) promptView.findViewById(R.id.textView); promptText.setText(inputTitle); final EditText promptEditText = (EditText) promptView.findViewById(R.id.edittext); - if(this.numberInput){ + if (this.numberInput) { Log.i(TAG, "NUMBER INPUT"); promptEditText.setInputType(InputType.TYPE_CLASS_NUMBER); } else { @@ -81,7 +76,6 @@ private void showInputDialog(){ Log.i(TAG, "input Type: " + promptEditText.getInputType()); promptEditText.setText(setText); - AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setView(promptView); @@ -102,10 +96,10 @@ public void onClick(DialogInterface dialog, int id) { } }); - alertDialogBuilder.setOnKeyListener(new Dialog.OnKeyListener(){ + alertDialogBuilder.setOnKeyListener(new Dialog.OnKeyListener() { @Override - public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event){ - if(keyCode == KeyEvent.KEYCODE_BACK){ + public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { dialog.cancel(); } return true; @@ -117,11 +111,10 @@ public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event){ alert.show(); } - public void register(ITextSelectCallback callback){ + public void register(ITextSelectCallback callback) { registeredCallbacks.add(callback); } - public String getSetText() { return setText; } @@ -132,17 +125,12 @@ public void setSetText(String setText) { this.subLabel.setText(setText); } - public int getSetInt(){ + public int getSetInt() { return Integer.parseInt(setText); } - public void setSetInt(int value){ + public void setSetInt(int value) { this.setText = String.valueOf(value); } - - - - - } diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/internal/Connections.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/internal/Connections.java index cb6917e4..84598876 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/internal/Connections.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/internal/Connections.java @@ -31,31 +31,38 @@ */ public class Connections { - /** Singleton instance of Connections**/ + /** + * Singleton instance of Connections + **/ private static Connections instance = null; - /** List of {@link Connection} object **/ + /** + * List of {@link Connection} object + **/ private HashMap connections = null; - /** {@link Persistence} object used to save, delete and restore connections**/ + /** + * {@link Persistence} object used to save, delete and restore connections + **/ private Persistence persistence = null; /** * Create a Connections object + * * @param context Applications context */ - private Connections(Context context){ + private Connections(Context context) { connections = new HashMap(); // If there is state, attempt to restore it persistence = new Persistence(context); try { List connectionList = persistence.restoreConnections(context); - for(Connection connection : connectionList) { + for (Connection connection : connectionList) { System.out.println("Connection was persisted.." + connection.handle()); connections.put(connection.handle(), connection); } - } catch (PersistenceException e){ + } catch (PersistenceException e) { e.printStackTrace(); } } @@ -63,11 +70,12 @@ private Connections(Context context){ /** * Returns an already initialised instance of Connections, if Connections has yet to be created, it will * create and return that instance. + * * @param context The applications context used to create the Connections object if it is not already initialised * @return Connections instance */ - public synchronized static Connections getInstance(Context context){ - if(instance == null){ + public synchronized static Connections getInstance(Context context) { + if (instance == null) { instance = new Connections(context); } return instance; @@ -75,22 +83,24 @@ public synchronized static Connections getInstance(Context context){ /** * Finds and returns a {@link Connection} object that the given client handle points to + * * @param handle The handle to the {@link Connection} to return * @return a connection associated with the client handle, null if one is not found */ - public Connection getConnection(String handle){ + public Connection getConnection(String handle) { return connections.get(handle); } /** * Adds a {@link Connection} object to the collection of connections associated with this object + * * @param connection {@link Connection} to add */ - public void addConnection(Connection connection){ + public void addConnection(Connection connection) { connections.put(connection.handle(), connection); - try{ + try { persistence.persistConnection(connection); - } catch (PersistenceException e){ + } catch (PersistenceException e) { // @todo Handle this error more appropriately //error persisting well lets just swallow this e.printStackTrace(); @@ -98,32 +108,34 @@ public void addConnection(Connection connection){ } -// --Commented out by Inspection START (12/10/2016, 10:21): -// /** -// * Create a fully initialised MqttAndroidClient for the parameters given -// * @param context The Applications context -// * @param serverURI The ServerURI to connect to -// * @param clientId The clientId for this client -// * @return new instance of MqttAndroidClient -// */ -// public MqttAndroidClient createClient(Context context, String serverURI, String clientId){ -// return new MqttAndroidClient(context, serverURI, clientId); -// } -// --Commented out by Inspection STOP (12/10/2016, 10:21) + // --Commented out by Inspection START (12/10/2016, 10:21): + // /** + // * Create a fully initialised MqttAndroidClient for the parameters given + // * @param context The Applications context + // * @param serverURI The ServerURI to connect to + // * @param clientId The clientId for this client + // * @return new instance of MqttAndroidClient + // */ + // public MqttAndroidClient createClient(Context context, String serverURI, String clientId){ + // return new MqttAndroidClient(context, serverURI, clientId); + // } + // --Commented out by Inspection STOP (12/10/2016, 10:21) /** * Get all the connections associated with this Connections object. + * * @return Map of connections */ - public Map getConnections(){ + public Map getConnections() { return connections; } /** * Removes a connection from the map of connections + * * @param connection connection to be removed */ - public void removeConnection(Connection connection){ + public void removeConnection(Connection connection) { connections.remove(connection.handle()); persistence.deleteConnection(connection); } @@ -132,9 +144,10 @@ public void removeConnection(Connection connection){ /** * Updates an existing connection within the map of * connections as well as in the persisted model + * * @param connection connection to be updated. */ - public void updateConnection(Connection connection){ + public void updateConnection(Connection connection) { connections.put(connection.handle(), connection); persistence.updateConnection(connection); } diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/internal/Persistence.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/internal/Persistence.java index 85c760e3..8e61b145 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/internal/Persistence.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/internal/Persistence.java @@ -21,79 +21,127 @@ * Persistence deals with interacting with the database to persist * {@link Connection} objects so created clients survive, the destruction of the * singleton {@link Connections} object. - * */ public class Persistence extends SQLiteOpenHelper implements BaseColumns { private static final String TAG = "Persistence"; - /** The version of the database **/ + /** + * The version of the database + **/ private static final int DATABASE_VERSION = 1; - /** The name of the database file **/ + /** + * The name of the database file + **/ private static final String DATABASE_NAME = "connections.db"; - /** The name of the connections table **/ + /** + * The name of the connections table + **/ private static final String TABLE_CONNECTIONS = "connections"; - - /** Table column for client handle **/ + /** + * Table column for client handle + **/ private static final String COLUMN_CLIENT_HANDLE = "clientHandle"; - /** Table column for host **/ + /** + * Table column for host + **/ private static final String COLUMN_HOST = "host"; - /** Table column for client id **/ + /** + * Table column for client id + **/ private static final String COLUMN_client_ID = "clientID"; - /** Table column for port **/ + /** + * Table column for port + **/ private static final String COLUMN_port = "port"; - /** Table column for ssl enabled**/ + /** + * Table column for ssl enabled + **/ private static final String COLUMN_ssl = "ssl"; //connection options - /** Table column for client's timeout**/ + /** + * Table column for client's timeout + **/ private static final String COLUMN_TIME_OUT = "timeout"; - /** Table column for client's keepalive **/ + /** + * Table column for client's keepalive + **/ private static final String COLUMN_KEEP_ALIVE = "keepalive"; - /** Table column for the client's username**/ + /** + * Table column for the client's username + **/ private static final String COLUMN_USER_NAME = "username"; - /** Table column for the client's password**/ + /** + * Table column for the client's password + **/ private static final String COLUMN_PASSWORD = "password"; - /** Table column for clean session **/ + /** + * Table column for clean session + **/ private static final String COLUMN_CLEAN_SESSION = "cleanSession"; /** Table column for **/ //last will - /** Table column for last will topic **/ + /** + * Table column for last will topic + **/ private static final String COLUMN_TOPIC = "topic"; - /** Table column for the last will message payload **/ + /** + * Table column for the last will message payload + **/ private static final String COLUMN_MESSAGE = "message"; - /** Table column for the last will message qos **/ + /** + * Table column for the last will message qos + **/ private static final String COLUMN_QOS = "qos"; - /** Table column for the retained state of the message **/ + /** + * Table column for the retained state of the message + **/ private static final String COLUMN_RETAINED = "retained"; - /** The name of the subscriptions table **/ + /** + * The name of the subscriptions table + **/ private static final String TABLE_SUBSCRIPTIONS = "subscriptions"; - /** Table column for subscription topic **/ + /** + * Table column for subscription topic + **/ private static final String SUBSCRIPTIONS_COLUMN_TOPIC = "topic"; - /** Table column for the subscription qos **/ + /** + * Table column for the subscription qos + **/ private static final String SUBSCRIPTIONS_COLUMN_QOS = "qos"; - /** Table column for the subscription enable notification setting **/ + /** + * Table column for the subscription enable notification setting + **/ private static final String SUBSCRIPTIONS_COLUMN_NOTIFY = "notify"; //sql lite data types - /** Text type for SQLite**/ + /** + * Text type for SQLite + **/ private static final String TEXT_TYPE = " TEXT"; - /** Int type for SQLite**/ + /** + * Int type for SQLite + **/ private static final String INT_TYPE = " INTEGER"; - /**Comma separator **/ + /** + * Comma separator + **/ private static final String COMMA_SEP = ","; - /** Create tables query **/ + /** + * Create tables query + **/ private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + TABLE_CONNECTIONS + " (" + @@ -123,15 +171,16 @@ public class Persistence extends SQLiteOpenHelper implements BaseColumns { SUBSCRIPTIONS_COLUMN_NOTIFY + INT_TYPE + COMMA_SEP + SUBSCRIPTIONS_COLUMN_QOS + INT_TYPE + ");"; - /** Delete tables entry **/ - private static final String SQL_DELETE_ENTRIES = - "DROP TABLE IF EXISTS " + TABLE_CONNECTIONS; + /** + * Delete tables entry + **/ + private static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + TABLE_CONNECTIONS; - private static final String SQL_DELETE_SUBSCRIPTION_ENTRIES = - "DROP TABLE IF EXISTS " + TABLE_SUBSCRIPTIONS; + private static final String SQL_DELETE_SUBSCRIPTION_ENTRIES = "DROP TABLE IF EXISTS " + TABLE_SUBSCRIPTIONS; /** * Creates the persistence object passing it a context + * * @param context Context that the application is running in */ public Persistence(Context context) { @@ -139,17 +188,18 @@ public Persistence(Context context) { } /* (non-Javadoc) - * @see org.eclipse.paho.android.service.database.sqlite.SQLiteOpenHelper#onCreate(org.eclipse.paho.android.service.database.sqlite.SQLiteDatabase) + * @see org.eclipse.paho.android.service.database.sqlite.SQLiteOpenHelper#onCreate(org.eclipse.paho.android.service.database.sqlite + * .SQLiteDatabase) */ @Override public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_ENTRIES); db.execSQL(SQL_CREATE_SUBSCRIPTION_ENTRIES); - } /* (non-Javadoc) - * @see org.eclipse.paho.android.service.database.sqlite.SQLiteOpenHelper#onUpgrade(org.eclipse.paho.android.service.database.sqlite.SQLiteDatabase, int, int) + * @see org.eclipse.paho.android.service.database.sqlite.SQLiteOpenHelper#onUpgrade(org.eclipse.paho.android.service.database.sqlite + * .SQLiteDatabase, int, int) */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { @@ -159,7 +209,8 @@ public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { /* * (non-Javadoc) - * @see org.eclipse.paho.android.service.database.sqlite.SQLiteOpenHelper#onDowngrade(org.eclipse.paho.android.service.database.sqlite.SQLiteDatabase, int, int) + * @see org.eclipse.paho.android.service.database.sqlite.SQLiteOpenHelper#onDowngrade(org.eclipse.paho.android.service.database.sqlite + * .SQLiteDatabase, int, int) */ @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { @@ -168,6 +219,7 @@ public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { /** * Persist a Connection to the database + * * @param connection the connection to persist * @throws PersistenceException If storing the data fails */ @@ -181,14 +233,14 @@ public void persistConnection(Connection connection) throws PersistenceException if (newRowId == -1) { throw new PersistenceException("Failed to persist connection: " + connection.handle()); - } - else { //Successfully persisted assigning persistenceID + } else { //Successfully persisted assigning persistenceID connection.assignPersistenceId(newRowId); } } /** * Updates a {@link Connection} in the database + * * @param connection {@link Connection} to update */ public void updateConnection(Connection connection) { @@ -199,7 +251,7 @@ public void updateConnection(Connection connection) { db.update(TABLE_CONNECTIONS, getValues(connection), whereClause, whereArgs); } - private ContentValues getValues(Connection connection){ + private ContentValues getValues(Connection connection) { MqttConnectOptions conOpts = connection.getConnectionOptions(); MqttMessage lastWill = conOpts.getWillMessage(); ContentValues values = new ContentValues(); @@ -225,8 +277,7 @@ private ContentValues getValues(Connection connection){ if (lastWill == null) { values.put(COLUMN_RETAINED, 0); - } - else { + } else { values.put(COLUMN_RETAINED, lastWill.isRetained() ? 1 : 0); //convert from boolean to int } return values; @@ -234,6 +285,7 @@ private ContentValues getValues(Connection connection){ /** * Persist a Subscription to the database + * * @param subscription the subscription to persist * @throws PersistenceException If storing the data fails */ @@ -247,7 +299,7 @@ public long persistSubscription(Subscription subscription) throws PersistenceExc long newRowId = db.insert(TABLE_SUBSCRIPTIONS, null, values); db.close(); - if(newRowId == -1){ + if (newRowId == -1) { throw new PersistenceException("Failed to persist subscription: " + subscription.toString()); } else { subscription.setPersistenceId(newRowId); @@ -258,6 +310,7 @@ public long persistSubscription(Subscription subscription) throws PersistenceExc /** * Deletes a subscription from the database + * * @param subscription The subscription to delete from the database */ public void deleteSubscription(Subscription subscription) { @@ -266,19 +319,16 @@ public void deleteSubscription(Subscription subscription) { db.delete(TABLE_SUBSCRIPTIONS, _ID + "=?", new String[]{String.valueOf(subscription.getPersistenceId())}); db.close(); //don't care if it failed, means it's not in the db therefore no need to delete - } - /** * Recreates connection objects based upon information stored in the database + * * @param context Context for creating {@link Connection} objects * @return list of connections that have been restored * @throws PersistenceException if restoring connections fails, this is thrown */ - public List restoreConnections(Context context) throws PersistenceException - { - + public List restoreConnections(Context context) throws PersistenceException { //columns to return String[] connectionColumns = { @@ -297,8 +347,7 @@ public List restoreConnections(Context context) throws PersistenceEx COLUMN_RETAINED, COLUMN_QOS, _ID - - }; + }; // Columns to return for subscription String[] subscriptionColumns = { @@ -316,36 +365,36 @@ public List restoreConnections(Context context) throws PersistenceEx SQLiteDatabase db = getReadableDatabase(); - Cursor c = db.query(TABLE_CONNECTIONS, connectionColumns, null, null, null, null, sort); - ArrayList list = new ArrayList(c.getCount()); + Cursor cursor = db.query(TABLE_CONNECTIONS, connectionColumns, null, null, null, null, sort); + ArrayList list = new ArrayList(cursor.getCount()); Connection connection; - for (int i = 0; i < c.getCount(); i++) { - if (!c.moveToNext()) { //move to the next item throw persistence exception, if it fails - throw new PersistenceException("Failed restoring connection - count: " + c.getCount() + "loop iteration: " + i); + for (int i = 0; i < cursor.getCount(); i++) { + if (!cursor.moveToNext()) { //move to the next item throw persistence exception, if it fails + throw new PersistenceException("Failed restoring connection - count: " + cursor.getCount() + "loop iteration: " + i); } //get data from cursor - Long id = c.getLong(c.getColumnIndexOrThrow(_ID)); + Long id = cursor.getLong(cursor.getColumnIndexOrThrow(_ID)); //basic client information - String clientHandle = c.getString(c.getColumnIndexOrThrow(COLUMN_CLIENT_HANDLE)); - String host = c.getString(c.getColumnIndexOrThrow(COLUMN_HOST)); - String clientID = c.getString(c.getColumnIndexOrThrow(COLUMN_client_ID)); - int port = c.getInt(c.getColumnIndexOrThrow(COLUMN_port)); + String clientHandle = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_CLIENT_HANDLE)); + String host = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_HOST)); + String clientID = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_client_ID)); + int port = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_port)); //connect options strings - String username = c.getString(c.getColumnIndexOrThrow(COLUMN_USER_NAME)); - String password = c.getString(c.getColumnIndexOrThrow(COLUMN_PASSWORD)); - String topic = c.getString(c.getColumnIndexOrThrow(COLUMN_TOPIC)); - String message = c.getString(c.getColumnIndexOrThrow(COLUMN_MESSAGE)); + String username = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_USER_NAME)); + String password = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_PASSWORD)); + String topic = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_TOPIC)); + String message = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_MESSAGE)); //connect options integers - int qos = c.getInt(c.getColumnIndexOrThrow(COLUMN_QOS)); - int keepAlive = c.getInt(c.getColumnIndexOrThrow(COLUMN_KEEP_ALIVE)); - int timeout = c.getInt(c.getColumnIndexOrThrow(COLUMN_TIME_OUT)); + int qos = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_QOS)); + int keepAlive = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_KEEP_ALIVE)); + int timeout = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_TIME_OUT)); //get all values that need converting and convert integers to booleans in line using "condition ? trueValue : falseValue" - boolean cleanSession = c.getInt(c.getColumnIndexOrThrow(COLUMN_CLEAN_SESSION)) == 1 ; - boolean retained = c.getInt(c.getColumnIndexOrThrow(COLUMN_RETAINED)) == 1; - boolean ssl = c.getInt(c.getColumnIndexOrThrow(COLUMN_ssl)) == 1; + boolean cleanSession = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_CLEAN_SESSION)) == 1; + boolean retained = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_RETAINED)) == 1; + boolean ssl = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_ssl)) == 1; //rebuild objects starting with the connect options MqttConnectOptions opts = new MqttConnectOptions(); @@ -375,7 +424,7 @@ public List restoreConnections(Context context) throws PersistenceEx if (!sub_c.moveToNext()) { //move to the next item throw persistence exception, if it fails throw new PersistenceException("Failed restoring subscription - count: " + sub_c.getCount() + "loop iteration: " + x); } - Long sub_id = sub_c.getLong(sub_c.getColumnIndexOrThrow(_ID)); + Long sub_id = sub_c.getLong(sub_c.getColumnIndexOrThrow(_ID)); String sub_clientHandle = sub_c.getString(sub_c.getColumnIndexOrThrow(COLUMN_CLIENT_HANDLE)); String sub_topic = sub_c.getString(sub_c.getColumnIndexOrThrow(SUBSCRIPTIONS_COLUMN_TOPIC)); boolean sub_notify = sub_c.getInt(sub_c.getColumnIndexOrThrow(SUBSCRIPTIONS_COLUMN_NOTIFY)) == 1; @@ -394,16 +443,16 @@ public List restoreConnections(Context context) throws PersistenceEx } //close the cursor now we are finished with it - c.close(); + cursor.close(); - db.close(); + db.close(); return list; - } /** * Deletes a connection from the database + * * @param connection The connection to delete from the database */ public void deleteConnection(Connection connection) { @@ -412,12 +461,6 @@ public void deleteConnection(Connection connection) { db.delete(TABLE_CONNECTIONS, _ID + "=?", new String[]{String.valueOf(connection.persistenceId())}); db.close(); //don't care if it failed, means it's not in the db therefore no need to delete - } - - - - - } \ No newline at end of file diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/internal/PersistenceException.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/internal/PersistenceException.java index 1c248808..d0e45e6c 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/internal/PersistenceException.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/internal/PersistenceException.java @@ -4,21 +4,24 @@ /** * Persistence Exception, defines an error with persisting a {@link Connection} - * fails. Example operations are {@link Persistence#persistConnection(Connection)} and {@link Persistence#restoreConnections(android.content.Context)}; + * fails. Example operations are {@link Persistence#persistConnection(Connection)} and + * {@link Persistence#restoreConnections(android.content.Context)}; * these operations throw this exception to indicate unexpected results occurred when performing actions on the database. - * */ public class PersistenceException extends Exception { + /** + * Serialisation ID + **/ + private static final long serialVersionUID = 5326458803268855071L; + /** * Creates a persistence exception with the given error message + * * @param message The error message to display */ public PersistenceException(String message) { super(message); } - /** Serialisation ID**/ - private static final long serialVersionUID = 5326458803268855071L; - } diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/model/ConnectionModel.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/model/ConnectionModel.java index 22446869..1317ed49 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/model/ConnectionModel.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/model/ConnectionModel.java @@ -5,23 +5,6 @@ public class ConnectionModel { - private static final String CLIENT_HANDLE = "CLIENT_HANDLE"; - private static final String CLIENT_ID = "CLIENT_ID"; - private static final String HOST_NAME = "HOST_NAME"; - private static final String PORT = "PORT"; - private static final String CLEAN_SESSION = "CLEAN_SESSION"; - private static final String USERNAME = "USERNAME"; - private static final String PASSWORD = "PASSWORD"; - private static final String TLS_SERVER_KEY = "TLS_SERVER_KEY"; - private static final String TLS_CLIENT_KEY = "TLS_CLIENT_KEY"; - private static final String TIMEOUT = "TIMEOUT"; - private static final String KEEP_ALIVE = "KEEP_ALIVE"; - private static final String LWT_TOPIC = "LWT_TOPIC"; - private static final String LWT_MESSAGE = "LWT_MESSAGE"; - private static final String LWT_QOS = "LWT_QOS"; - private static final String LWT_RETAIN = "LWT_RETAIN"; - - private String clientHandle = ""; private String clientId = "AndroidExampleClient"; private String serverHostName = "iot.eclipse.org"; @@ -30,7 +13,6 @@ public class ConnectionModel { private String username = ""; private String password = ""; - private boolean tlsConnection = false; private String tlsServerKey = ""; private String tlsClientKey = ""; @@ -39,28 +21,28 @@ public class ConnectionModel { private String lwtTopic = ""; private String lwtMessage = ""; private int lwtQos = 0; - private boolean lwtRetain = false; + private boolean lwtRetain = false; - public ConnectionModel(){ + public ConnectionModel() { } - - - /** Initialise the ConnectionModel with an existing connection **/ - public ConnectionModel(Connection connection){ + /** + * Initialise the ConnectionModel with an existing connection + **/ + public ConnectionModel(Connection connection) { clientHandle = connection.handle(); clientId = connection.getId(); serverHostName = connection.getHostName(); serverPort = connection.getPort(); cleanSession = connection.getConnectionOptions().isCleanSession(); - if(connection.getConnectionOptions().getUserName() == null){ + if (connection.getConnectionOptions().getUserName() == null) { username = ""; - }else { + } else { username = connection.getConnectionOptions().getUserName(); } - if(connection.getConnectionOptions().getPassword() != null) { + if (connection.getConnectionOptions().getPassword() != null) { password = new String(connection.getConnectionOptions().getPassword()); } else { password = ""; @@ -70,12 +52,12 @@ public ConnectionModel(Connection connection){ timeout = connection.getConnectionOptions().getConnectionTimeout(); keepAlive = connection.getConnectionOptions().getKeepAliveInterval(); - if(connection.getConnectionOptions().getWillDestination() == null){ + if (connection.getConnectionOptions().getWillDestination() == null) { lwtTopic = ""; } else { lwtTopic = connection.getConnectionOptions().getWillDestination(); } - if(connection.getConnectionOptions().getWillMessage() != null) { + if (connection.getConnectionOptions().getWillMessage() != null) { lwtMessage = new String(connection.getConnectionOptions().getWillMessage().getPayload()); lwtQos = connection.getConnectionOptions().getWillMessage().getQos(); lwtRetain = connection.getConnectionOptions().getWillMessage().isRetained(); @@ -84,7 +66,6 @@ public ConnectionModel(Connection connection){ lwtQos = 0; lwtRetain = false; } - } public String getClientHandle() { @@ -239,34 +220,60 @@ public String toString() { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } ConnectionModel that = (ConnectionModel) o; - if (serverPort != that.serverPort) return false; - if (cleanSession != that.cleanSession) return false; - if (tlsConnection != that.tlsConnection) return false; - if (timeout != that.timeout) return false; - if (keepAlive != that.keepAlive) return false; - if (lwtQos != that.lwtQos) return false; - if (lwtRetain != that.lwtRetain) return false; - if (clientHandle != null ? !clientHandle.equals(that.clientHandle) : that.clientHandle != null) + if (serverPort != that.serverPort) { + return false; + } + if (cleanSession != that.cleanSession) { + return false; + } + if (tlsConnection != that.tlsConnection) { + return false; + } + if (timeout != that.timeout) { return false; - if (clientId != null ? !clientId.equals(that.clientId) : that.clientId != null) + } + if (keepAlive != that.keepAlive) { + return false; + } + if (lwtQos != that.lwtQos) { + return false; + } + if (lwtRetain != that.lwtRetain) { + return false; + } + if (clientHandle != null ? !clientHandle.equals(that.clientHandle) : that.clientHandle != null) { + return false; + } + if (clientId != null ? !clientId.equals(that.clientId) : that.clientId != null) { return false; - if (serverHostName != null ? !serverHostName.equals(that.serverHostName) : that.serverHostName != null) + } + if (serverHostName != null ? !serverHostName.equals(that.serverHostName) : that.serverHostName != null) { return false; - if (username != null ? !username.equals(that.username) : that.username != null) + } + if (username != null ? !username.equals(that.username) : that.username != null) { return false; - if (password != null ? !password.equals(that.password) : that.password != null) + } + if (password != null ? !password.equals(that.password) : that.password != null) { return false; - if (tlsServerKey != null ? !tlsServerKey.equals(that.tlsServerKey) : that.tlsServerKey != null) + } + if (tlsServerKey != null ? !tlsServerKey.equals(that.tlsServerKey) : that.tlsServerKey != null) { return false; - if (tlsClientKey != null ? !tlsClientKey.equals(that.tlsClientKey) : that.tlsClientKey != null) + } + if (tlsClientKey != null ? !tlsClientKey.equals(that.tlsClientKey) : that.tlsClientKey != null) { return false; - if (lwtTopic != null ? !lwtTopic.equals(that.lwtTopic) : that.lwtTopic != null) + } + if (lwtTopic != null ? !lwtTopic.equals(that.lwtTopic) : that.lwtTopic != null) { return false; + } return !(lwtMessage != null ? !lwtMessage.equals(that.lwtMessage) : that.lwtMessage != null); } diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/model/NavDrawerItem.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/model/NavDrawerItem.java index bd280fd3..347a9c71 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/model/NavDrawerItem.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/model/NavDrawerItem.java @@ -4,16 +4,15 @@ import org.eclipse.paho.android.sample.activity.Connection; public class NavDrawerItem { - private boolean showNotify; private String title; private String handle; - public NavDrawerItem(Connection connection){ + public NavDrawerItem(Connection connection) { this.title = connection.getId(); this.handle = connection.handle(); } - public String getTitle(){ + public String getTitle() { return title; } diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/model/ReceivedMessage.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/model/ReceivedMessage.java index d3503d7d..bbc30eee 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/model/ReceivedMessage.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/model/ReceivedMessage.java @@ -6,16 +6,15 @@ public class ReceivedMessage { + private final String topic; + private final MqttMessage message; + private final Date timestamp; public ReceivedMessage(String topic, MqttMessage message) { this.topic = topic; this.message = message; this.timestamp = new Date(); } - private final String topic; - private final MqttMessage message; - private final Date timestamp; - public String getTopic() { return topic; } diff --git a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/model/Subscription.java b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/model/Subscription.java index a80f51df..195d07e8 100644 --- a/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/model/Subscription.java +++ b/org.eclipse.paho.android.sample/src/main/java/org/eclipse/paho/android/sample/model/Subscription.java @@ -3,8 +3,6 @@ public class Subscription { - - private String topic; private int qos; private String lastMessage; @@ -12,7 +10,7 @@ public class Subscription { private long persistenceId; private boolean enableNotifications; - public Subscription(String topic, int qos, String clientHandle, boolean enableNotifications){ + public Subscription(String topic, int qos, String clientHandle, boolean enableNotifications) { this.topic = topic; this.qos = qos; this.clientHandle = clientHandle; @@ -74,7 +72,7 @@ public String toString() { ", qos=" + qos + ", clientHandle='" + clientHandle + '\'' + ", persistenceId='" + persistenceId + '\'' + - ", enableNotifications='" + enableNotifications + '\''+ + ", enableNotifications='" + enableNotifications + '\'' + '}'; } } diff --git a/org.eclipse.paho.android.sample/src/main/res/layout/activity_main.xml b/org.eclipse.paho.android.sample/src/main/res/layout/activity_main.xml index 9c573f6a..4e69fc44 100644 --- a/org.eclipse.paho.android.sample/src/main/res/layout/activity_main.xml +++ b/org.eclipse.paho.android.sample/src/main/res/layout/activity_main.xml @@ -1,9 +1,9 @@ - + + layout="@layout/toolbar"/> + android:layout_weight="1"/> @@ -39,6 +39,6 @@ android:layout_height="match_parent" android:layout_gravity="start" app:layout="@layout/fragment_navigation_drawer" - tools:layout="@layout/fragment_navigation_drawer" /> + tools:layout="@layout/fragment_navigation_drawer"/> \ No newline at end of file diff --git a/org.eclipse.paho.android.sample/src/main/res/layout/fragment_connection.xml b/org.eclipse.paho.android.sample/src/main/res/layout/fragment_connection.xml index dec7ca8e..7e5f2f34 100644 --- a/org.eclipse.paho.android.sample/src/main/res/layout/fragment_connection.xml +++ b/org.eclipse.paho.android.sample/src/main/res/layout/fragment_connection.xml @@ -1,8 +1,8 @@ + android:layout_width="match_parent" + android:layout_height="match_parent" + android:orientation="vertical"> + - - diff --git a/org.eclipse.paho.android.sample/src/main/res/layout/fragment_connection_history.xml b/org.eclipse.paho.android.sample/src/main/res/layout/fragment_connection_history.xml index 3b299900..d82101c0 100644 --- a/org.eclipse.paho.android.sample/src/main/res/layout/fragment_connection_history.xml +++ b/org.eclipse.paho.android.sample/src/main/res/layout/fragment_connection_history.xml @@ -1,29 +1,28 @@ + xmlns:tools="http://schemas.android.com/tools" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:layout_marginTop="56dp" + android:orientation="vertical" + tools:context="org.eclipse.paho.android.sample.activity.MessagesFragment">