diff --git a/.gitignore b/.gitignore
index d3f5d3e..710103f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -14,3 +14,6 @@ gen/
# Local configuration file (sdk path, etc)
local.properties
+
+# osX folder files
+.DS_Store
diff --git a/demo/AndroidManifest.xml b/demo/AndroidManifest.xml
index a8021f4..1ab8710 100644
--- a/demo/AndroidManifest.xml
+++ b/demo/AndroidManifest.xml
@@ -7,6 +7,8 @@
android:minSdkVersion="8"
android:targetSdkVersion="15" />
+
+
+
+
\ No newline at end of file
diff --git a/demo/res/layout/fayedemo_activity_demo.xml b/demo/res/layout/fayedemo_activity_demo.xml
index a8034a8..df2410a 100644
--- a/demo/res/layout/fayedemo_activity_demo.xml
+++ b/demo/res/layout/fayedemo_activity_demo.xml
@@ -1,58 +1,78 @@
-
+ android:orientation="vertical"
+ android:padding="10dp" >
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
\ No newline at end of file
+ android:layout_gravity="center_vertical"
+ android:layout_marginTop="10dp"
+ android:onClick="onToggleButtonClick"
+ android:text="Connected"
+ android:textOff="Connect to faye"
+ android:textOn="Connected" />
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/demo/res/menu/fayedemo_activity_demo.xml b/demo/res/menu/fayedemo_activity_demo.xml
deleted file mode 100644
index cfc10fd..0000000
--- a/demo/res/menu/fayedemo_activity_demo.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
diff --git a/demo/res/values/strings.xml b/demo/res/values/strings.xml
index 76267e8..ba0da06 100644
--- a/demo/res/values/strings.xml
+++ b/demo/res/values/strings.xml
@@ -1,8 +1,6 @@
Faye Client Demo
- Hello world!
- Settings
- DemoActivity
+ Faye Client Demo
\ No newline at end of file
diff --git a/demo/src/com/b3rwynmobile/fayeclient/demo/DemoActivity.java b/demo/src/com/b3rwynmobile/fayeclient/demo/DemoActivity.java
index 83d7ee7..a163c12 100644
--- a/demo/src/com/b3rwynmobile/fayeclient/demo/DemoActivity.java
+++ b/demo/src/com/b3rwynmobile/fayeclient/demo/DemoActivity.java
@@ -7,145 +7,202 @@
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
-import android.view.Menu;
import android.view.View;
-import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
-import android.widget.Toast;
+import android.widget.ProgressBar;
+import android.widget.TextView;
import android.widget.ToggleButton;
+
import com.b3rwynmobile.fayeclient.FayeBinder;
import com.b3rwynmobile.fayeclient.FayeClient;
import com.b3rwynmobile.fayeclient.FayeListener;
import com.b3rwynmobile.fayeclient.FayeService;
+import com.b3rwynmobile.fayeclient.config.FayeConfigurations;
import com.b3rwynmobile.fayeclient.models.FayeMessage;
public class DemoActivity extends Activity implements FayeListener,
- ServiceConnection {
-
- private boolean mFayeConnected;
- private FayeBinder mBinder;
- private EditText mTextBox;
- private ToggleButton mConnectToggle;
- private Button mSendTextButton;
- private Button mSendRawButton;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.fayedemo_activity_demo);
-
- mTextBox = (EditText) findViewById(R.id.message_box);
- mConnectToggle = (ToggleButton) findViewById(R.id.connect_toggle_button);
- mSendTextButton = (Button) findViewById(R.id.send_text_button);
- mSendRawButton = (Button) findViewById(R.id.send_raw_button);
-
- mConnectToggle.setOnClickListener(new OnClickListener() {
-
- public void onClick(View v) {
- if (!mFayeConnected) {
- connect();
- } else {
- disconnect();
- }
- }
- });
-
- mSendTextButton.setOnClickListener(new OnClickListener() {
-
- public void onClick(View v) {
- sendMessage(mTextBox.getText().toString());
- }
- });
-
- mSendRawButton.setOnClickListener(new OnClickListener() {
-
- public void onClick(View v) {
- sendRawMessage(mTextBox.getText().toString());
- }
- });
- }
-
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- getMenuInflater().inflate(R.menu.fayedemo_activity_demo, menu);
- return true;
+ ServiceConnection {
+
+ /**
+ * a easy form to controller the connection status
+ */
+ private enum FayeConnectionStatus {
+ FAYE_CS_CONNECTED, FAYE_CS_DESCONNECTED, FAYE_CS_CONNECTING, FAYE_CS_DESCONNECTING;
+ }
+
+ /*
+ * Instance variables
+ */
+
+ private FayeConnectionStatus mFayeConnected = FayeConnectionStatus.FAYE_CS_DESCONNECTED;
+ private FayeBinder mBinder;
+ private EditText mTextBox;
+ private ToggleButton mConnectToggle;
+ private Button mSendTextButton;
+ private Button mSendRawButton;
+ private ProgressBar mProgressBar;
+ private TextView mDataReceivedTextView;
+
+ /*
+ * life cycle
+ */
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.fayedemo_activity_demo);
+
+ // You need set the configurations before use the faye client
+ FayeConfigurations.shared = new MyFayeConfigurations();
+
+ mTextBox = (EditText) findViewById(R.id.message_box);
+ mConnectToggle = (ToggleButton) findViewById(R.id.connect_toggle_button);
+ mSendTextButton = (Button) findViewById(R.id.send_text_button);
+ mSendRawButton = (Button) findViewById(R.id.send_raw_button);
+ mProgressBar = (ProgressBar) findViewById(R.id.progress_bar_wait_connection);
+ mDataReceivedTextView = (TextView) findViewById(R.id.txt_messages_receiveds);
+ }
+
+ /*
+ * onClicks handlers
+ */
+
+ public void onToggleButtonClick(View v) {
+ switch (mFayeConnected) {
+ case FAYE_CS_DESCONNECTED:
+ connect();
+ break;
+ case FAYE_CS_CONNECTED:
+ disconnect();
+ break;
+ default:
+ MyFayeConfigurations.log("wait faye connection proccess");
}
-
- public void connectedToServer(FayeClient faye) {
- mFayeConnected = true;
- mConnectToggle.setChecked(mFayeConnected);
+ }
+
+ public void onTextButtonClick(View v) {
+ if (mFayeConnected == FayeConnectionStatus.FAYE_CS_CONNECTED)
+ mBinder.getFayeClient().sendTextMessage(
+ mTextBox.getText().toString());
+ else
+ MyFayeConfigurations.log("Connect Faye before to send a message");
+ }
+
+ public void onRawButtonClick(View v) {
+ if (mFayeConnected == FayeConnectionStatus.FAYE_CS_CONNECTED)
+ mBinder.getFayeClient().sendRawTextMessage(
+ mTextBox.getText().toString());
+ else
+ MyFayeConfigurations.log("Connect Faye before to send a message");
+ }
+
+ public void onClearButtonClick(View v) {
+ mDataReceivedTextView.setText("");
+ }
+
+ /*
+ * layout behavior methods
+ */
+
+ public void setmFayeConnected(FayeConnectionStatus mFayeConnected) {
+ switch (mFayeConnected) {
+ case FAYE_CS_DESCONNECTED:
+ case FAYE_CS_CONNECTED:
+ mConnectToggle.setVisibility(View.VISIBLE);
+ mProgressBar.setVisibility(View.INVISIBLE);
+ mSendRawButton.setEnabled(true);
+ mSendTextButton.setEnabled(true);
+ mConnectToggle
+ .setChecked(mFayeConnected == FayeConnectionStatus.FAYE_CS_CONNECTED);
+ break;
+ default:
+ mConnectToggle.setVisibility(View.INVISIBLE);
+ mProgressBar.setVisibility(View.VISIBLE);
+ mSendRawButton.setEnabled(false);
+ mSendTextButton.setEnabled(false);
}
-
- public void disconnectedFromServer(FayeClient faye) {
- mFayeConnected = false;
- mConnectToggle.setChecked(mFayeConnected);
+ this.mFayeConnected = mFayeConnected;
+ }
+
+ /*
+ * custom methods
+ */
+
+ public void connect() {
+ if (mBinder == null) {
+ bindFayeService();
+ } else if (mFayeConnected == FayeConnectionStatus.FAYE_CS_DESCONNECTED) {
+ setmFayeConnected(FayeConnectionStatus.FAYE_CS_CONNECTING);
+ mBinder.getFayeService().startFaye();
}
-
- public void messageReceived(FayeClient faye, FayeMessage message) {
- Toast.makeText(this, "Faye received message: "
- + message.getData().toString(), Toast.LENGTH_LONG).show();
+ }
+
+ public void disconnect() {
+ if (mBinder == null) {
+ bindFayeService();
+ } else if (mFayeConnected == FayeConnectionStatus.FAYE_CS_CONNECTED) {
+ setmFayeConnected(FayeConnectionStatus.FAYE_CS_DESCONNECTING);
+ mBinder.getFayeService().stopFaye();
}
+ }
+
+ private void bindFayeService() {
+ Intent intent = new Intent();
+ intent.setClass(this, FayeService.class);
+ bindService(intent, this, Context.BIND_AUTO_CREATE);
+ }
+
+ /**
+ * example to subscribe a channel
+ *
+ * @param channel
+ * example: /channel_to_connect
+ */
+ public void subscribe(String channel) {
+ if (mBinder != null)
+ mBinder.getFayeClient().subscribe(channel);
+ else
+ MyFayeConfigurations.log("Connect Faye before subscribe a channel");
+ }
+
+ /*
+ * Faye Listener
+ */
+
+ public void connectedToServer(FayeClient faye) {
+ setmFayeConnected(FayeConnectionStatus.FAYE_CS_CONNECTED);
+ }
+
+ public void disconnectedFromServer(FayeClient faye) {
+ setmFayeConnected(FayeConnectionStatus.FAYE_CS_DESCONNECTED);
+ }
+
+ public void messageReceived(FayeClient faye, FayeMessage message) {
+ MyFayeConfigurations.log("Faye received message", message);
+
+ // Example of get message
+ if (message != null && message.getData() != null)
+ mDataReceivedTextView.setText(mDataReceivedTextView.getText()
+ + "\n" + message.getData().toString());
+ }
+
+ /*
+ * Service Connection Listener
+ */
+
+ public void onServiceConnected(ComponentName name, IBinder service) {
+ mBinder = (FayeBinder) service;
+ mBinder.getFayeClient().setFayeListener(this);
+ if (mBinder.getFayeClient().isFayeConnected())
+ setmFayeConnected(FayeConnectionStatus.FAYE_CS_CONNECTED);
+ else
+ connect();
+ }
+
+ public void onServiceDisconnected(ComponentName name) {
+ mBinder = null;
+ setmFayeConnected(FayeConnectionStatus.FAYE_CS_DESCONNECTED);
+ }
- public void onServiceConnected(ComponentName name, IBinder service) {
- mBinder = (FayeBinder) service;
- mBinder.getFayeClient().setFayeListener(this);
- mFayeConnected = mBinder.getFayeClient().isFayeConnected();
- if (!mFayeConnected) connect();
- }
-
- public void onServiceDisconnected(ComponentName name) {
- mBinder = null;
- mFayeConnected = false;
- }
-
- public void subscribe(String channel) {
- if (mBinder != null) {
- mBinder.getFayeClient().subscribe(channel);
- } else {
- Toast.makeText(this, "Please connect Faye first", Toast.LENGTH_LONG).show();
- }
- }
-
- public void sendMessage(String message) {
- if (mFayeConnected) {
- mBinder.getFayeClient().sendTextMessage(message);
- } else {
- Toast.makeText(this,
- "Please connect Faye before trying to send a message",
- Toast.LENGTH_LONG).show();
- }
- }
-
- public void sendRawMessage(String message) {
- if (mFayeConnected) {
- mBinder.getFayeClient().sendRawTextMessage(message);
- } else {
- Toast.makeText(this,
- "Please connect Faye before attempting to send a message",
- Toast.LENGTH_LONG).show();
- }
- }
-
- private void bindFayeService() {
- Intent intent = new Intent();
- intent.setClass(this, FayeService.class);
- bindService(intent, this, Context.BIND_AUTO_CREATE);
- }
-
- public void connect() {
- if (mBinder == null) {
- bindFayeService();
- } else {
- if (!mFayeConnected) mBinder.getFayeService().startFaye();
- }
- }
-
- public void disconnect() {
- if (mBinder == null) {
- bindFayeService();
- } else {
- if (mFayeConnected) mBinder.getFayeService().stopFaye();
- }
- }
}
diff --git a/demo/src/com/b3rwynmobile/fayeclient/demo/MyFayeConfigurations.java b/demo/src/com/b3rwynmobile/fayeclient/demo/MyFayeConfigurations.java
new file mode 100644
index 0000000..8ca2c60
--- /dev/null
+++ b/demo/src/com/b3rwynmobile/fayeclient/demo/MyFayeConfigurations.java
@@ -0,0 +1,36 @@
+package com.b3rwynmobile.fayeclient.demo;
+
+import com.b3rwynmobile.fayeclient.config.FayeConfigurations;
+
+public class MyFayeConfigurations extends FayeConfigurations {
+
+ public MyFayeConfigurations() {
+
+ /*
+ * Need override to work, here you put your url initial channel and if
+ * need the auth token
+ */
+ FAYE_URL = "ws://example.com:00/mount";
+ FAYE_INITIAL_CHANNEL = "/some_channel";
+ FAYE_AUTH_TOKEN = "";
+
+ /*
+ * Override to debug, it will show faye logs with logcat tag
+ * "FayeAndroid" default is false
+ */
+ logEnabled = true;
+
+ /*
+ * Override to see faye method called with logcat tag
+ * "FayeAndroidMethodTracer" default is false
+ */
+ logMethodTrackerEnabled = true;
+
+ /*
+ * Override to see faye exceptions use the logcat tag
+ * "FayeAndroidException" default is false
+ */
+ logExceptionsEnabled = true;
+ }
+
+}
diff --git a/src/com/b3rwynmobile/fayeclient/FayeAdvice.java b/src/com/b3rwynmobile/fayeclient/FayeAdvice.java
deleted file mode 100644
index c6b1b59..0000000
--- a/src/com/b3rwynmobile/fayeclient/FayeAdvice.java
+++ /dev/null
@@ -1,53 +0,0 @@
-// @formatter:off
-/******************************************************************************
- *
- * Copyright 2011-2012 b3rwyn Mobile Solutions
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************************/
-// @formatter:on
-
-package com.b3rwynmobile.fayeclient;
-
-public class FayeAdvice {
-
- private String reconnect;
- private int interval;
- private long timeout;
-
- public String getReconnect() {
- return reconnect;
- }
-
- public void setReconnect(String reconnect) {
- this.reconnect = reconnect;
- }
-
- public int getInterval() {
- return interval;
- }
-
- public void setInterval(int interval) {
- this.interval = interval;
- }
-
- public long getTimeout() {
- return timeout;
- }
-
- public void setTimeout(long timeout) {
- this.timeout = timeout;
- }
-
-}
diff --git a/src/com/b3rwynmobile/fayeclient/FayeClient.java b/src/com/b3rwynmobile/fayeclient/FayeClient.java
index 17f6e60..6e8f9eb 100644
--- a/src/com/b3rwynmobile/fayeclient/FayeClient.java
+++ b/src/com/b3rwynmobile/fayeclient/FayeClient.java
@@ -20,22 +20,25 @@
package com.b3rwynmobile.fayeclient;
-import android.util.Log;
+import java.io.UnsupportedEncodingException;
+import java.lang.Thread.State;
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Random;
+import com.b3rwynmobile.fayeclient.config.FayeConfigurations;
import com.b3rwynmobile.fayeclient.models.FayeMessage;
import com.google.gson.Gson;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonPrimitive;
import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketException;
import de.tavendo.autobahn.WebSocketHandler;
import de.tavendo.autobahn.WebSocketOptions;
-import java.io.UnsupportedEncodingException;
-import java.lang.Thread.State;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.List;
-
/**
* This class handles interactions with the Faye server, such as connecting,
* (un-)subscribing to channels and receiving push messages
@@ -44,33 +47,27 @@
*/
public class FayeClient {
- // Debug tag
- protected static final String TAG = "Faye Client";
-
// Channel constants
protected static final String HANDSHAKE_CHANNEL = "/meta/handshake";
- protected static final String CONNECT_CHANNEL = "/meta/connect";
+ protected static final String CONNECT_CHANNEL = "/meta/connect";
protected static final String DISCONNECT_CHANNEL = "/meta/disconnect";
protected static final String SUBSCRIBE_CHANNEL = "/meta/subscribe";
protected static final String UNSUBSCRIBE_CHANNEL = "/meta/unsubscribe";
- // Debug flag
- protected static final boolean DEBUG = true;
-
// Data objects
protected WebSocketConnection mWebSocket;
- protected FayeListener mFayeListener;
+ protected FayeListener mFayeListener;
protected FayeHeartbeatThread mHeartbeatThread;
// Connection fields
- protected String mFayeUrl;
- protected String mAuthToken;
- protected List mActiveSubchannels;
- protected String mClientId;
+ protected String mFayeUrl;
+ protected String mAuthToken;
+ protected List mActiveSubchannels;
+ protected String mClientId;
// Status fields
- protected boolean mFayeConnected;
- protected boolean mDisconnectExpected;
+ protected boolean mFayeConnected;
+ protected boolean mDisconnectExpected;
/**
* Simplified constructor
@@ -111,6 +108,8 @@ public FayeClient(String fayeUrl, String channel) {
* Auth token for authenticated Faye hosts
*/
public FayeClient(String fayeUrl, String channel, String authToken) {
+ FayeConfigurations.tracker(this, fayeUrl, channel, authToken);
+
this.mFayeUrl = fayeUrl;
this.mActiveSubchannels = new ArrayList();
this.mFayeConnected = false;
@@ -124,20 +123,23 @@ public FayeClient(String fayeUrl, String channel, String authToken) {
}
protected void closeFayeConnection() {
- if (this.mClientId == null) { return; }
+ FayeConfigurations.tracker(this, this.mClientId);
+ if (this.mClientId == null) return;
- String disconnectString = "{\"channel\":\""
- + FayeClient.DISCONNECT_CHANNEL + "\",\"clientID\":\""
- + this.mClientId + "\"}";
- if (DEBUG) {
- Log.d(FayeClient.TAG, "Disconnect: " + disconnectString);
- }
- this.mWebSocket.sendTextMessage(disconnectString);
+ // Object to send
+ JsonObject disconnectJson = new JsonObject();
+ disconnectJson.addProperty("channel", FayeClient.DISCONNECT_CHANNEL);
+ disconnectJson.addProperty("clientId", this.mClientId);
+
+ this.mWebSocket.sendTextMessage(disconnectJson.toString());
this.mClientId = null;
}
protected void closeSocketConnection() {
+ FayeConfigurations.tracker(this, this.mWebSocket);
if (this.mWebSocket != null) {
+ FayeConfigurations.log("mWebSocket isConnected",
+ this.mWebSocket.isConnected());
if (this.mWebSocket.isConnected()) {
this.mWebSocket.disconnect();
}
@@ -150,6 +152,7 @@ protected void closeSocketConnection() {
* handshake
*/
public void connect() {
+ FayeConfigurations.tracker(this);
this.mDisconnectExpected = false;
openSocketConnection();
}
@@ -158,6 +161,7 @@ public void connect() {
* Disconnects Faye and the socket gracefully
*/
public void disconnect() {
+ FayeConfigurations.tracker(this);
this.mDisconnectExpected = true;
closeFayeConnection();
closeSocketConnection();
@@ -209,17 +213,23 @@ public boolean isSocketConnected() {
}
protected void openFayeConnection() {
- String connectString = "{\"channel\":\"" + FayeClient.CONNECT_CHANNEL
- + "\",\"clientId\":\"" + this.mClientId
- + "\",\"connectionType\":\"websocket\"}";
+ FayeConfigurations.tracker(this);
+
+ JsonObject connectJson = new JsonObject();
+ connectJson.addProperty("channel", FayeClient.CONNECT_CHANNEL);
+ connectJson.addProperty("clientId", this.mClientId);
+ connectJson.addProperty("connectionType", "websocket");
+
try {
- mWebSocket.sendBinaryMessage(connectString.getBytes("UTF-8"));
+ mWebSocket.sendBinaryMessage(connectJson.toString().getBytes(
+ "UTF-8"));
} catch (UnsupportedEncodingException e) {
- e.printStackTrace();
+ FayeConfigurations.logException(e);
}
}
private void openSocketConnection() {
+ FayeConfigurations.tracker(this);
WebSocketOptions options = new WebSocketOptions();
options.setReceiveTextMessagesRaw(true);
this.mWebSocket = new WebSocketConnection();
@@ -227,74 +237,80 @@ private void openSocketConnection() {
this.mWebSocket.connect(this.mFayeUrl, new WebSocketHandler() {
public void onBinaryMessage(byte[] payload) {
+ FayeConfigurations.tracker(this, payload);
onTextMessage(new String(payload));
}
public void onClose(int code, String reason) {
+ FayeConfigurations.tracker(this, code, reason);
processClose(code);
}
public void onOpen() {
- String handshakeString = "{\"supportedConnectionTypes\":[\"websocket\"],\"minimumVersion\":\"1.0beta\",\"version\":\"1.0\",\"channel\":\""
- + FayeClient.HANDSHAKE_CHANNEL + "\"}";
+ FayeConfigurations.tracker(this);
+
+ JsonArray supportedConnectionTypes = new JsonArray();
+ supportedConnectionTypes
+ .add(new JsonPrimitive("websocket"));
+
+ JsonObject handshakeJson = new JsonObject();
+ handshakeJson.add("supportedConnectionTypes",
+ supportedConnectionTypes);
+ handshakeJson.addProperty("minimumVersion", "1.0beta");
+ handshakeJson.addProperty("version", "1.0");
+ handshakeJson.addProperty("channel",
+ FayeClient.HANDSHAKE_CHANNEL);
+
try {
- mWebSocket.sendBinaryMessage(handshakeString
- .getBytes("UTF-8"));
+ mWebSocket.sendBinaryMessage(handshakeJson.toString()
+ .getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
- e.printStackTrace();
+ FayeConfigurations.logException(e);
}
}
public void onRawTextMessage(byte[] payload) {
+ FayeConfigurations.tracker(this, payload);
onTextMessage(new String(payload));
}
public void onTextMessage(String payload) {
- if (DEBUG) {
- Log.d(FayeClient.TAG, "Text message payload: "
- + payload);
- }
+ FayeConfigurations.tracker(this, payload);
+ FayeConfigurations.log("Text message payload", payload);
Gson gson = new Gson();
FayeMessage[] messages = gson.fromJson(payload,
- FayeMessage[].class);
+ FayeMessage[].class);
for (FayeMessage message : messages) {
String channel = message.getChannel();
processTextMessage(message, channel);
}
}
}, options);
- if (DEBUG) {
- Log.d(FayeClient.TAG, "Service is opening the web socket");
- }
- Log.d(FayeClient.TAG, "Service is opening the web socket");
+ FayeConfigurations.log("Service is opening the web socket");
} catch (WebSocketException e) {
- e.printStackTrace();
+ FayeConfigurations.logException(e);
}
}
protected void processTextMessage(FayeMessage message, String channel) {
+ FayeConfigurations.tracker(this, message, channel);
if (channel.equals(FayeClient.HANDSHAKE_CHANNEL)) {
if (message.isSuccessful()) {
mClientId = message.getClientId();
openFayeConnection();
} else {
- if (DEBUG) {
- Log.e(FayeClient.TAG, "Faye failed to handshake");
- }
+ FayeConfigurations.log("Faye failed to handshake");
}
} else if (channel.equals(FayeClient.CONNECT_CHANNEL)) {
if (message.isSuccessful()) {
mFayeConnected = true;
- mFayeListener.connectedToServer(this);
+ // auto-subscribe channel to get messages
+ subscribe(FayeConfigurations.shared.FAYE_INITIAL_CHANNEL);
scheduleHeartbeat(message.getAdvice().getInterval());
- if (DEBUG) {
- Log.d(TAG, "Faye connected");
- }
+ FayeConfigurations.log("Faye connected");
} else {
mFayeConnected = false;
- if (DEBUG) {
- Log.e(FayeClient.TAG, "Faye failed to connect");
- }
+ FayeConfigurations.log("Faye failed to connect");
}
} else if (channel.equals(FayeClient.DISCONNECT_CHANNEL)) {
if (message.isSuccessful()) {
@@ -303,23 +319,19 @@ protected void processTextMessage(FayeMessage message, String channel) {
closeSocketConnection();
} else {
mFayeConnected = true;
- if (DEBUG) {
- Log.e(FayeClient.TAG, "Faye failed to disconnect");
- }
+ FayeConfigurations.log("Faye failed to disconnect");
}
} else if (channel.equals(FayeClient.SUBSCRIBE_CHANNEL)) {
if (message.isSuccessful()) {
- if (DEBUG) {
- Log.i(FayeClient.TAG, "Faye subscribed to channel"
- + message.getSubscription());
- }
+ FayeConfigurations.log("Faye subscribed to channel",
+ message.getSubscription());
mActiveSubchannels.add(message.getSubscription());
mFayeConnected = true;
mFayeListener.connectedToServer(this);
- Log.d(TAG, "Faye connected");
+ FayeConfigurations.log("Faye connected");
} else {
mFayeConnected = false;
- Log.e(FayeClient.TAG, "Faye failed to connect");
+ FayeConfigurations.log("Faye failed to connect");
}
} else if (channel.equals(FayeClient.DISCONNECT_CHANNEL)) {
if (message.isSuccessful()) {
@@ -328,51 +340,40 @@ protected void processTextMessage(FayeMessage message, String channel) {
closeSocketConnection();
} else {
mFayeConnected = true;
- Log.e(FayeClient.TAG, "Faye failed to disconnect");
+ FayeConfigurations.log("Faye failed to disconnect");
}
} else if (channel.equals(FayeClient.SUBSCRIBE_CHANNEL)) {
if (message.isSuccessful()) {
- Log.i(FayeClient.TAG,
- "Faye subscribed to channel"
- + message.getSubscription());
+ FayeConfigurations.log("Faye subscribed to channel",
+ message.getSubscription());
mActiveSubchannels.add(message.getSubscription());
} else {
- if (DEBUG) {
- Log.e(FayeClient.TAG,
- MessageFormat
- .format("Faye failed to connect to channel {0} with error {1}",
- message.getSubscription(),
- message.getError()));
- }
+ FayeConfigurations.log(MessageFormat.format(
+ "Faye failed to connect to channel {0} with error {1}",
+ message.getSubscription(), message.getError()));
// TODO Handle failed subscribe
}
} else if (channel.equals(FayeClient.UNSUBSCRIBE_CHANNEL)) {
- if (DEBUG) {
- Log.i(FayeClient.TAG, "Faye unsubscribed from channel "
- + message.getSubscription());
- }
- } else if (this.mActiveSubchannels.contains(channel)) {
- mFayeListener.messageReceived(this, message);
- Log.i(FayeClient.TAG,
- "Faye unsubscribed from channel "
- + message.getSubscription());
+ FayeConfigurations.log("Faye unsubscribed from channel ",
+ message.getSubscription());
} else if (this.mActiveSubchannels.contains(channel)) {
mFayeListener.messageReceived(this, message);
+ FayeConfigurations.log("Faye unsubscribed from channel",
+ message.getSubscription());
} else {
- if (DEBUG) {
- Log.e(FayeClient.TAG,
- "Faye recieved a message with no subscription for channel "
- + message.getSubscription());
- }
+ FayeConfigurations
+ .log("Faye recieved a message with no subscription for channel ",
+ message.getSubscription());
}
}
protected void scheduleHeartbeat(int interval) {
+ FayeConfigurations.tracker(this, interval);
if (interval == 0) {
openFayeConnection();
} else {
if (mHeartbeatThread == null
- || mHeartbeatThread.getState() != State.RUNNABLE) {
+ || mHeartbeatThread.getState() != State.RUNNABLE) {
mHeartbeatThread = new FayeHeartbeatThread(this);
}
mHeartbeatThread.setDelay(interval);
@@ -381,22 +382,14 @@ protected void scheduleHeartbeat(int interval) {
}
protected void processClose(int code) {
+ FayeConfigurations.tracker(this, code);
switch (code) {
- case WebSocketHandler.CLOSE_INTERNAL_ERROR:
- FayeClient.this.mWebSocket = new WebSocketConnection();
- connect();
- break;
case WebSocketHandler.CLOSE_PROTOCOL_ERROR:
case WebSocketHandler.CLOSE_CANNOT_CONNECT:
case WebSocketHandler.CLOSE_CONNECTION_LOST:
- while (!FayeClient.this.mWebSocket.isConnected()) {
- try {
- connect();
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
+ case WebSocketHandler.CLOSE_INTERNAL_ERROR:
+ mFayeListener.disconnectedFromServer(this);
+ break;
case WebSocketHandler.CLOSE_NORMAL:
break;
}
@@ -407,6 +400,7 @@ protected void processClose(int code) {
* explicity called.
*/
public void heartbeat() {
+ FayeConfigurations.tracker(this);
openFayeConnection();
}
@@ -417,6 +411,7 @@ public void heartbeat() {
* The FayeListener to attach to the client
*/
public void setFayeListener(FayeListener fayeListener) {
+ FayeConfigurations.tracker(this, fayeListener);
this.mFayeListener = fayeListener;
}
@@ -427,21 +422,24 @@ public void setFayeListener(FayeListener fayeListener) {
* The channel to subscribe to
*/
public void subscribe(String channel) {
- String subscribe = "{\"clientId\":\""
- + this.mClientId
- + "\",\"subscription\":\""
- + channel
- + "\",\"channel\":\"/meta/subscribe\",\"ext\":{\"authToken\":\""
- + this.mAuthToken + "\"}}";
- if (DEBUG) {
- Log.d(FayeClient.TAG,
- "Faye is attempting to subscribe to channel \"" + channel
- + "\"");
- }
+ if (this.mWebSocket == null) return;
+
+ FayeConfigurations.tracker(this, channel);
+
+ JsonObject ext = new JsonObject();
+ ext.addProperty("authToken", this.mAuthToken);
+
+ JsonObject subscribeJson = new JsonObject();
+ subscribeJson.addProperty("clientId", this.mClientId);
+ subscribeJson.addProperty("subscription", channel);
+ subscribeJson.addProperty("channel", FayeClient.SUBSCRIBE_CHANNEL);
+ subscribeJson.add("ext", ext);
+
try {
- this.mWebSocket.sendBinaryMessage(subscribe.getBytes("UTF-8"));
+ this.mWebSocket.sendBinaryMessage(subscribeJson.toString()
+ .getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
- e.printStackTrace();
+ FayeConfigurations.logException(e);
}
}
@@ -452,18 +450,18 @@ public void subscribe(String channel) {
* The channel to unsubscribe to
*/
public void unsubscribe(String channel) {
- String unsubscribe = "{\"clientId\":\"" + this.mClientId
- + "\",\"subscription\":\"" + channel
- + "\",\"channel\":\"/meta/unsubscribe\"}";
- if (DEBUG) {
- Log.d(FayeClient.TAG,
- "Faye is attempting to unsubscribe from channel \""
- + channel + "\"");
- }
+ FayeConfigurations.tracker(this, channel);
+
+ JsonObject unsubscribeJson = new JsonObject();
+ unsubscribeJson.addProperty("clientId", this.mClientId);
+ unsubscribeJson.addProperty("subscription", channel);
+ unsubscribeJson.addProperty("channel", FayeClient.UNSUBSCRIBE_CHANNEL);
+
try {
- this.mWebSocket.sendBinaryMessage(unsubscribe.getBytes("UTF-8"));
+ this.mWebSocket.sendBinaryMessage(unsubscribeJson.toString()
+ .getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
- e.printStackTrace();
+ FayeConfigurations.logException(e);
}
}
@@ -474,8 +472,18 @@ public void unsubscribe(String channel) {
* The string message to send to the server
*/
public void sendTextMessage(String message) {
+ FayeConfigurations.tracker(this, message);
+
+ // TODO a easy method to send a mutiples channels
+ JsonObject messageJson = new JsonObject();
+ messageJson.addProperty("channel",
+ FayeConfigurations.shared.FAYE_INITIAL_CHANNEL);
+ messageJson.addProperty("clientId", getClientId());
+ messageJson.addProperty("data", message);
+ messageJson.addProperty("id", new Random().nextInt());
+
if (isFayeConnected()) {
- mWebSocket.sendTextMessage(message);
+ mWebSocket.sendTextMessage(messageJson.toString());
}
}
@@ -486,12 +494,12 @@ public void sendTextMessage(String message) {
* The string message to send to the server
*/
public void sendRawTextMessage(String message) {
+ FayeConfigurations.tracker(this, message);
if (isFayeConnected()) {
try {
mWebSocket.sendRawTextMessage(message.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
+ FayeConfigurations.logException(e);
}
}
}
@@ -503,6 +511,7 @@ public void sendRawTextMessage(String message) {
* The binary byte[] payload to send to the server
*/
public void sendBinaryMessage(byte[] payload) {
+ FayeConfigurations.tracker(this, payload);
if (isFayeConnected()) {
mWebSocket.sendBinaryMessage(payload);
}
diff --git a/src/com/b3rwynmobile/fayeclient/FayeHeartbeatThread.java b/src/com/b3rwynmobile/fayeclient/FayeHeartbeatThread.java
index 4db3edf..f6418e0 100644
--- a/src/com/b3rwynmobile/fayeclient/FayeHeartbeatThread.java
+++ b/src/com/b3rwynmobile/fayeclient/FayeHeartbeatThread.java
@@ -20,9 +20,11 @@
package com.b3rwynmobile.fayeclient;
+import com.b3rwynmobile.fayeclient.config.FayeConfigurations;
+
public class FayeHeartbeatThread extends Thread {
- private int delay;
+ private int delay;
private FayeClient client;
public FayeHeartbeatThread(FayeClient client) {
@@ -38,7 +40,7 @@ public void run() {
Thread.sleep(1000);
sleepCount++;
} catch (InterruptedException e) {
- // Do nothing, server will send a timeout
+ FayeConfigurations.logException(e);
}
}
client.heartbeat();
diff --git a/src/com/b3rwynmobile/fayeclient/FayeMessage.java b/src/com/b3rwynmobile/fayeclient/FayeMessage.java
deleted file mode 100644
index 3131e87..0000000
--- a/src/com/b3rwynmobile/fayeclient/FayeMessage.java
+++ /dev/null
@@ -1,115 +0,0 @@
-// @formatter:off
-/******************************************************************************
- *
- * Copyright 2011-2012 b3rwyn Mobile Solutions
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************************/
-// @formatter:on
-
-package com.b3rwynmobile.fayeclient;
-
-public class FayeMessage {
-
- // General
- private String channel;
-
- // Handshake
- private String version;
- private String[] supportedConnectionTypes;
- private FayeAdvice advice;
-
- // Event
- private String data;
-
- // (Un-)Subscribe
- private String subscription;
- private String error;
-
- // Handshake + Subscribe
- private boolean successful;
- private String clientId;
-
- public String getChannel() {
- return channel;
- }
-
- public void setChannel(String channel) {
- this.channel = channel;
- }
-
- public String getVersion() {
- return version;
- }
-
- public void setVersion(String version) {
- this.version = version;
- }
-
- public String[] getSupportedConnectionTypes() {
- return supportedConnectionTypes;
- }
-
- public void setSupportedConnectionTypes(String[] supportedConnectionTypes) {
- this.supportedConnectionTypes = supportedConnectionTypes;
- }
-
- public FayeAdvice getAdvice() {
- return advice;
- }
-
- public void setAdvice(FayeAdvice advice) {
- this.advice = advice;
- }
-
- public String getData() {
- return data;
- }
-
- public void setData(String data) {
- this.data = data;
- }
-
- public String getSubscription() {
- return subscription;
- }
-
- public void setSubscription(String subscription) {
- this.subscription = subscription;
- }
-
- public String getError() {
- return error;
- }
-
- public void setError(String error) {
- this.error = error;
- }
-
- public boolean isSuccessful() {
- return successful;
- }
-
- public void setSuccessful(boolean successful) {
- this.successful = successful;
- }
-
- public String getClientId() {
- return clientId;
- }
-
- public void setClientId(String clientId) {
- this.clientId = clientId;
- }
-}
diff --git a/src/com/b3rwynmobile/fayeclient/FayeService.java b/src/com/b3rwynmobile/fayeclient/FayeService.java
index a8ff73b..359894d 100644
--- a/src/com/b3rwynmobile/fayeclient/FayeService.java
+++ b/src/com/b3rwynmobile/fayeclient/FayeService.java
@@ -23,7 +23,8 @@
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
-import android.widget.Toast;
+
+import com.b3rwynmobile.fayeclient.config.FayeConfigurations;
/**
* Service class to run Faye. Provides a singleton method to get the running
@@ -33,24 +34,16 @@
*/
public class FayeService extends Service {
- // Debug tag
- protected final String TAG = "Faye Service";
-
- // String constants
- final protected static String FAYE_HOST = "YOUR_ADDRESS"; // ws://someurl.com
- final protected static String FAYE_PORT = "YOUR_PORT";// 80
- final protected static String INITIAL_CHANNEL = "YOUR_INITIAL_CHANNEL";// /push
- final protected static String AUTH_TOKEN = "SUPER SECRET TOKEN";
-
// Data objects
- protected FayeClient mFaye;
- protected FayeBinder mFayeBinder;
+ protected FayeClient mFaye;
+ protected FayeBinder mFayeBinder;
/**
* Default constructor
*/
public FayeService() {
super();
+ FayeConfigurations.tracker(this);
}
/**
@@ -59,6 +52,7 @@ public FayeService() {
*/
@Override
public IBinder onBind(Intent intent) {
+ FayeConfigurations.tracker(this, intent);
setup();
return this.mFayeBinder;
}
@@ -66,6 +60,7 @@ public IBinder onBind(Intent intent) {
@Override
public void onCreate() {
super.onCreate();
+ FayeConfigurations.tracker(this);
setup();
}
@@ -74,21 +69,18 @@ public void onCreate() {
*/
@Override
public void onDestroy() {
+ FayeConfigurations.tracker(this);
stopFaye();
super.onDestroy();
}
protected void setup() {
- // Debug toast
- if (FayeClient.DEBUG) {
- Toast.makeText(getApplicationContext(), "Faye Service created",
- Toast.LENGTH_SHORT).show();
- }
- String fayeUrl = FayeService.FAYE_HOST + ":" + FayeService.FAYE_PORT
- + FayeService.INITIAL_CHANNEL;
+ FayeConfigurations.tracker(this);
// Create the client
- this.mFaye = new FayeClient(fayeUrl);
+ this.mFaye = new FayeClient(FayeConfigurations.shared.FAYE_URL,
+ FayeConfigurations.shared.FAYE_INITIAL_CHANNEL,
+ FayeConfigurations.shared.FAYE_AUTH_TOKEN);
// Create the binder
this.mFayeBinder = new FayeBinder(this, this.mFaye);
@@ -98,10 +90,7 @@ protected void setup() {
* Starts the Faye client
*/
public void startFaye() {
- if (FayeClient.DEBUG) {
- Toast.makeText(getApplicationContext(), "Faye Started",
- Toast.LENGTH_SHORT).show();
- }
+ FayeConfigurations.tracker(this);
this.mFaye.connect();
}
@@ -109,6 +98,7 @@ public void startFaye() {
* Stops the Faye client
*/
public void stopFaye() {
+ FayeConfigurations.tracker(this);
this.mFaye.disconnect();
}
diff --git a/src/com/b3rwynmobile/fayeclient/autobahn/WampConnection.java b/src/com/b3rwynmobile/fayeclient/autobahn/WampConnection.java
index 3d1d65b..412d4a2 100644
--- a/src/com/b3rwynmobile/fayeclient/autobahn/WampConnection.java
+++ b/src/com/b3rwynmobile/fayeclient/autobahn/WampConnection.java
@@ -23,15 +23,12 @@
import org.codehaus.jackson.type.TypeReference;
+import com.b3rwynmobile.fayeclient.config.FayeConfigurations;
+
import android.os.HandlerThread;
-import android.util.Log;
public class WampConnection extends WebSocketConnection implements Wamp {
- private static final boolean DEBUG = true;
- private static final String TAG = WampConnection.class.getName();
-
-
/// The message handler of the background writer.
protected WampWriter mWriterHandler;
@@ -118,7 +115,7 @@ protected void createWriter() {
mWriterThread.start();
mWriter = new WampWriter(mWriterThread.getLooper(), mMasterHandler, mTransportChannel, mOptions);
- if (DEBUG) Log.d(TAG, "writer created and started");
+ FayeConfigurations.tracker(this, "writer created and started");
}
@@ -129,7 +126,7 @@ protected void createReader() {
mReader = new WampReader(mCalls, mSubs, mMasterHandler, mTransportChannel, mOptions, "AutobahnReader");
mReader.start();
- if (DEBUG) Log.d(TAG, "reader created and started");
+ FayeConfigurations.tracker(this, "reader created and started");
}
@@ -193,7 +190,7 @@ public void onOpen() {
if (mSessionHandler != null) {
mSessionHandler.onOpen();
} else {
- if (DEBUG) Log.d(TAG, "could not call onOpen() .. handler already NULL");
+ FayeConfigurations.tracker(this, "could not call onOpen() .. handler already NULL");
}
}
@@ -202,7 +199,7 @@ public void onClose(int code, String reason) {
if (mSessionHandler != null) {
mSessionHandler.onClose(code, reason);
} else {
- if (DEBUG) Log.d(TAG, "could not call onClose() .. handler already NULL");
+ FayeConfigurations.tracker(this, "could not call onClose() .. handler already NULL");
}
}
@@ -213,7 +210,7 @@ public void onClose(int code, String reason) {
if (mSessionHandler != null) {
mSessionHandler.onClose(WebSocketConnectionHandler.CLOSE_CANNOT_CONNECT, "cannot connect (" + e.toString() + ")");
} else {
- if (DEBUG) Log.d(TAG, "could not call onClose() .. handler already NULL");
+ FayeConfigurations.tracker(this, "could not call onClose() .. handler already NULL");
}
}
@@ -263,11 +260,11 @@ protected void processAppMessage(Object message) {
WampMessage.Welcome welcome = (WampMessage.Welcome) message;
// FIXME: safe session ID / fire session opened hook
- if (DEBUG) Log.d(TAG, "WAMP session " + welcome.mSessionId + " established (protocol version " + welcome.mProtocolVersion + ", server " + welcome.mServerIdent + ")");
+ FayeConfigurations.tracker(this, "WAMP session " + welcome.mSessionId + " established (protocol version " + welcome.mProtocolVersion + ", server " + welcome.mServerIdent + ")");
} else {
- if (DEBUG) Log.d(TAG, "unknown WAMP message in AutobahnConnection.processAppMessage");
+ FayeConfigurations.tracker(this, "unknown WAMP message in AutobahnConnection.processAppMessage");
}
}
diff --git a/src/com/b3rwynmobile/fayeclient/autobahn/WampReader.java b/src/com/b3rwynmobile/fayeclient/autobahn/WampReader.java
index f363a55..c125b9b 100644
--- a/src/com/b3rwynmobile/fayeclient/autobahn/WampReader.java
+++ b/src/com/b3rwynmobile/fayeclient/autobahn/WampReader.java
@@ -29,20 +29,17 @@
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
+import android.os.Handler;
+
import com.b3rwynmobile.fayeclient.autobahn.WampConnection.CallMeta;
import com.b3rwynmobile.fayeclient.autobahn.WampConnection.SubMeta;
-
-import android.os.Handler;
-import android.util.Log;
+import com.b3rwynmobile.fayeclient.config.FayeConfigurations;
/**
* Autobahn WAMP reader, the receiving leg of a WAMP connection.
*/
public class WampReader extends WebSocketReader {
- private static final boolean DEBUG = true;
- private static final String TAG = WampReader.class.getName();
-
/// Jackson JSON-to-object mapper.
private final ObjectMapper mJsonMapper;
@@ -81,7 +78,7 @@ public WampReader(ConcurrentHashMap calls,
mJsonMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mJsonFactory = mJsonMapper.getJsonFactory();
- if (DEBUG) Log.d(TAG, "created");
+ FayeConfigurations.tracker(this, "created");
}
protected void onTextMessage(String payload) {
@@ -138,7 +135,7 @@ protected void onRawTextMessage(byte[] payload) {
} else {
- if (DEBUG) Log.d(TAG, "WAMP RPC success return for unknown call ID received");
+ FayeConfigurations.tracker(this, "WAMP RPC success return for unknown call ID received");
}
} else if (msgType == WampMessage.MESSAGE_TYPE_CALL_ERROR) {
@@ -161,7 +158,7 @@ protected void onRawTextMessage(byte[] payload) {
} else {
- if (DEBUG) Log.d(TAG, "WAMP RPC error return for unknown call ID received");
+ FayeConfigurations.tracker(this, "WAMP RPC error return for unknown call ID received");
}
} else if (msgType == WampMessage.MESSAGE_TYPE_EVENT) {
@@ -187,7 +184,7 @@ protected void onRawTextMessage(byte[] payload) {
} else {
- if (DEBUG) Log.d(TAG, "WAMP event for not-subscribed topic received");
+ FayeConfigurations.tracker(this, "WAMP event for not-subscribed topic received");
}
} else if (msgType == WampMessage.MESSAGE_TYPE_PREFIX) {
@@ -221,12 +218,12 @@ protected void onRawTextMessage(byte[] payload) {
} else {
// FIXME: invalid WAMP message
- if (DEBUG) Log.d(TAG, "invalid WAMP message: unrecognized message type");
+ FayeConfigurations.tracker(this, "invalid WAMP message: unrecognized message type");
}
} else {
- if (DEBUG) Log.d(TAG, "invalid WAMP message: missing message type or message type not an integer");
+ FayeConfigurations.tracker(this, "invalid WAMP message: missing message type or message type not an integer");
}
if (parser.nextToken() == JsonToken.END_ARRAY) {
@@ -235,23 +232,23 @@ protected void onRawTextMessage(byte[] payload) {
} else {
- if (DEBUG) Log.d(TAG, "invalid WAMP message: missing array close or invalid additional args");
+ FayeConfigurations.tracker(this, "invalid WAMP message: missing array close or invalid additional args");
}
} else {
- if (DEBUG) Log.d(TAG, "invalid WAMP message: not an array");
+ FayeConfigurations.tracker(this, "invalid WAMP message: not an array");
}
parser.close();
} catch (JsonParseException e) {
- if (DEBUG) e.printStackTrace();
+ FayeConfigurations.logException(e);
} catch (IOException e) {
- if (DEBUG) e.printStackTrace();
+ FayeConfigurations.logException(e);
}
}
diff --git a/src/com/b3rwynmobile/fayeclient/autobahn/WampWriter.java b/src/com/b3rwynmobile/fayeclient/autobahn/WampWriter.java
index d7e60c0..a0a3bd0 100644
--- a/src/com/b3rwynmobile/fayeclient/autobahn/WampWriter.java
+++ b/src/com/b3rwynmobile/fayeclient/autobahn/WampWriter.java
@@ -27,9 +27,10 @@
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.MappingJsonFactory;
+import com.b3rwynmobile.fayeclient.config.FayeConfigurations;
+
import android.os.Handler;
import android.os.Looper;
-import android.util.Log;
/**
* Autobahn WAMP writer, the transmitting leg of a WAMP connection.
@@ -39,9 +40,6 @@
*/
public class WampWriter extends WebSocketWriter {
- private static final boolean DEBUG = true;
- private static final String TAG = WampWriter.class.getName();
-
/**
* This is the Jackson JSON factory we use to create JSON generators.
*/
@@ -68,7 +66,7 @@ public WampWriter(Looper looper, Handler master, SocketChannel socket,
mJsonFactory = new MappingJsonFactory();
mPayload = new NoCopyByteArrayOutputStream();
- if (DEBUG) Log.d(TAG, "created");
+ FayeConfigurations.tracker(this, "created");
}
/**
diff --git a/src/com/b3rwynmobile/fayeclient/autobahn/WebSocketConnection.java b/src/com/b3rwynmobile/fayeclient/autobahn/WebSocketConnection.java
index 99d4d4a..7565f26 100644
--- a/src/com/b3rwynmobile/fayeclient/autobahn/WebSocketConnection.java
+++ b/src/com/b3rwynmobile/fayeclient/autobahn/WebSocketConnection.java
@@ -24,17 +24,16 @@
import java.net.URISyntaxException;
import java.nio.channels.SocketChannel;
+import com.b3rwynmobile.fayeclient.config.FayeConfigurations;
+
+import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
-import android.util.Log;
public class WebSocketConnection implements WebSocket {
-
- private static final boolean DEBUG = true;
- private static final String TAG = WebSocketConnection.class.getName();
-
+
protected Handler mMasterHandler;
protected WebSocketReader mReader;
@@ -130,7 +129,7 @@ protected void onPostExecute(String reason) {
public WebSocketConnection() {
- if (DEBUG) Log.d(TAG, "created");
+ FayeConfigurations.tracker(this, "created");
}
@@ -156,18 +155,18 @@ public boolean isConnected() {
private void failConnection(int code, String reason) {
- if (DEBUG) Log.d(TAG, "fail connection [code = " + code + ", reason = " + reason);
+ FayeConfigurations.tracker(this, "fail connection [code = " + code + ", reason = " + reason);
if (mReader != null) {
mReader.quit();
try {
mReader.join();
} catch (InterruptedException e) {
- if (DEBUG) e.printStackTrace();
+ FayeConfigurations.logException(e);
}
//mReader = null;
} else {
- if (DEBUG) Log.d(TAG, "mReader already NULL");
+ FayeConfigurations.tracker(this, "mReader already NULL");
}
if (mWriter != null) {
@@ -176,36 +175,36 @@ private void failConnection(int code, String reason) {
try {
mWriterThread.join();
} catch (InterruptedException e) {
- if (DEBUG) e.printStackTrace();
+ FayeConfigurations.logException(e);
}
//mWriterThread = null;
} else {
- if (DEBUG) Log.d(TAG, "mWriter already NULL");
+ FayeConfigurations.tracker(this, "mWriter already NULL");
}
if (mTransportChannel != null) {
try {
mTransportChannel.close();
} catch (IOException e) {
- if (DEBUG) e.printStackTrace();
+ FayeConfigurations.logException(e);
}
//mTransportChannel = null;
} else {
- if (DEBUG) Log.d(TAG, "mTransportChannel already NULL");
+ FayeConfigurations.tracker(this, "mTransportChannel already NULL");
}
if (mWsHandler != null) {
try {
mWsHandler.onClose(code, reason);
} catch (Exception e) {
- if (DEBUG) e.printStackTrace();
+ FayeConfigurations.logException(e);
}
//mWsHandler = null;
} else {
- if (DEBUG) Log.d(TAG, "mWsHandler already NULL");
+ FayeConfigurations.tracker(this, "mWsHandler already NULL");
}
- if (DEBUG) Log.d(TAG, "worker threads stopped");
+ FayeConfigurations.tracker(this, "worker threads stopped");
}
@@ -291,14 +290,15 @@ public void disconnect() {
if (mWriter != null) {
mWriter.forward(new WebSocketMessage.Close(1000));
} else {
- if (DEBUG) Log.d(TAG, "could not send Close .. writer already NULL");
+ FayeConfigurations.tracker(this, "could not send Close .. writer already NULL");
}
}
-
+ //this method causes a {@link HandlerLeak} FIXME
/**
- * Create master message handler.
+ * Create master message handler.
*/
+ @SuppressLint("HandlerLeak")
protected void createHandler() {
mMasterHandler = new Handler() {
@@ -312,7 +312,7 @@ public void handleMessage(Message msg) {
if (mWsHandler != null) {
mWsHandler.onTextMessage(textMessage.mPayload);
} else {
- if (DEBUG) Log.d(TAG, "could not call onTextMessage() .. handler already NULL");
+ FayeConfigurations.tracker(this, "could not call onTextMessage() .. handler already NULL");
}
} else if (msg.obj instanceof WebSocketMessage.RawTextMessage) {
@@ -322,7 +322,7 @@ public void handleMessage(Message msg) {
if (mWsHandler != null) {
mWsHandler.onRawTextMessage(rawTextMessage.mPayload);
} else {
- if (DEBUG) Log.d(TAG, "could not call onRawTextMessage() .. handler already NULL");
+ FayeConfigurations.tracker(this, "could not call onRawTextMessage() .. handler already NULL");
}
} else if (msg.obj instanceof WebSocketMessage.BinaryMessage) {
@@ -332,13 +332,13 @@ public void handleMessage(Message msg) {
if (mWsHandler != null) {
mWsHandler.onBinaryMessage(binaryMessage.mPayload);
} else {
- if (DEBUG) Log.d(TAG, "could not call onBinaryMessage() .. handler already NULL");
+ FayeConfigurations.tracker(this, "could not call onBinaryMessage() .. handler already NULL");
}
} else if (msg.obj instanceof WebSocketMessage.Ping) {
WebSocketMessage.Ping ping = (WebSocketMessage.Ping) msg.obj;
- if (DEBUG) Log.d(TAG, "WebSockets Ping received");
+ FayeConfigurations.tracker(this, "WebSockets Ping received");
// reply with Pong
WebSocketMessage.Pong pong = new WebSocketMessage.Pong();
@@ -350,13 +350,13 @@ public void handleMessage(Message msg) {
@SuppressWarnings("unused")
WebSocketMessage.Pong pong = (WebSocketMessage.Pong) msg.obj;
- if (DEBUG) Log.d(TAG, "WebSockets Pong received");
+ FayeConfigurations.tracker(this, "WebSockets Pong received");
} else if (msg.obj instanceof WebSocketMessage.Close) {
WebSocketMessage.Close close = (WebSocketMessage.Close) msg.obj;
- if (DEBUG) Log.d(TAG, "WebSockets Close received (" + close.mCode + " - " + close.mReason + ")");
+ FayeConfigurations.tracker(this, "WebSockets Close received (" + close.mCode + " - " + close.mReason + ")");
mWriter.forward(new WebSocketMessage.Close(1000));
@@ -365,12 +365,12 @@ public void handleMessage(Message msg) {
@SuppressWarnings("unused")
WebSocketMessage.ServerHandshake serverHandshake = (WebSocketMessage.ServerHandshake) msg.obj;
- if (DEBUG) Log.d(TAG, "opening handshake received");
+ FayeConfigurations.tracker(this, "opening handshake received");
if (mWsHandler != null) {
mWsHandler.onOpen();
} else {
- if (DEBUG) Log.d(TAG, "could not call onOpen() .. handler already NULL");
+ FayeConfigurations.tracker(this, "could not call onOpen() .. handler already NULL");
}
} else if (msg.obj instanceof WebSocketMessage.ConnectionLost) {
@@ -413,7 +413,7 @@ protected void createWriter() {
mWriterThread.start();
mWriter = new WebSocketWriter(mWriterThread.getLooper(), mMasterHandler, mTransportChannel, mOptions);
- if (DEBUG) Log.d(TAG, "WS writer created and started");
+ FayeConfigurations.tracker(this, "WS writer created and started");
}
@@ -425,6 +425,6 @@ protected void createReader() {
mReader = new WebSocketReader(mMasterHandler, mTransportChannel, mOptions, "WebSocketReader");
mReader.start();
- if (DEBUG) Log.d(TAG, "WS reader created and started");
+ FayeConfigurations.tracker(this, "WS reader created and started");
}
}
diff --git a/src/com/b3rwynmobile/fayeclient/autobahn/WebSocketReader.java b/src/com/b3rwynmobile/fayeclient/autobahn/WebSocketReader.java
index baf7a3d..620d94a 100644
--- a/src/com/b3rwynmobile/fayeclient/autobahn/WebSocketReader.java
+++ b/src/com/b3rwynmobile/fayeclient/autobahn/WebSocketReader.java
@@ -22,9 +22,10 @@
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
+import com.b3rwynmobile.fayeclient.config.FayeConfigurations;
+
import android.os.Handler;
import android.os.Message;
-import android.util.Log;
/**
* WebSocket reader, the receiving leg of a WebSockets connection.
@@ -35,9 +36,6 @@
*/
public class WebSocketReader extends Thread {
- private static final boolean DEBUG = true;
- private static final String TAG = WebSocketReader.class.getName();
-
private final Handler mMaster;
private final SocketChannel mSocket;
private final WebSocketOptions mOptions;
@@ -97,7 +95,7 @@ public WebSocketReader(Handler master, SocketChannel socket, WebSocketOptions op
mFrameHeader = null;
mState = STATE_CONNECTING;
- if (DEBUG) Log.d(TAG, "created");
+ FayeConfigurations.tracker(this, "created");
}
@@ -108,7 +106,7 @@ public void quit() {
mStopped = true;
- if (DEBUG) Log.d(TAG, "quit");
+ FayeConfigurations.tracker(this, "quit");
}
@@ -564,7 +562,7 @@ private boolean consumeData() throws Exception {
@Override
public void run() {
- if (DEBUG) Log.d(TAG, "running");
+ FayeConfigurations.tracker(this, "running");
try {
@@ -578,7 +576,7 @@ public void run() {
}
} else if (len < 0) {
- if (DEBUG) Log.d(TAG, "run() : ConnectionLost");
+ FayeConfigurations.tracker(this, "run() : ConnectionLost");
notify(new WebSocketMessage.ConnectionLost());
mStopped = true;
@@ -587,14 +585,14 @@ public void run() {
} catch (WebSocketException e) {
- if (DEBUG) Log.d(TAG, "run() : WebSocketException (" + e.toString() + ")");
+ FayeConfigurations.logException(e);
// wrap the exception and notify master
notify(new WebSocketMessage.ProtocolViolation(e));
} catch (Exception e) {
- if (DEBUG) Log.d(TAG, "run() : Exception (" + e.toString() + ")");
+ FayeConfigurations.logException(e);
// wrap the exception and notify master
notify(new WebSocketMessage.Error(e));
@@ -604,6 +602,6 @@ public void run() {
mStopped = true;
}
- if (DEBUG) Log.d(TAG, "ended");
+ FayeConfigurations.tracker(this, "ended");
}
}
diff --git a/src/com/b3rwynmobile/fayeclient/autobahn/WebSocketWriter.java b/src/com/b3rwynmobile/fayeclient/autobahn/WebSocketWriter.java
index 1a1cf31..c17dc34 100644
--- a/src/com/b3rwynmobile/fayeclient/autobahn/WebSocketWriter.java
+++ b/src/com/b3rwynmobile/fayeclient/autobahn/WebSocketWriter.java
@@ -22,11 +22,12 @@
import java.nio.channels.SocketChannel;
import java.util.Random;
+import com.b3rwynmobile.fayeclient.config.FayeConfigurations;
+
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Base64;
-import android.util.Log;
/**
* WebSocket writer, the sending leg of a WebSockets connection.
@@ -37,10 +38,7 @@
* underlying TCP socket.
*/
public class WebSocketWriter extends Handler {
-
- private static final boolean DEBUG = true;
- private static final String TAG = WebSocketWriter.class.getName();
-
+
/// Random number generator for handshake key and frame mask generation.
private final Random mRng = new Random();
@@ -79,7 +77,7 @@ public WebSocketWriter(Looper looper, Handler master, SocketChannel socket, WebS
mOptions = options;
mBuffer = new ByteBufferOutputStream(options.getMaxFramePayloadSize() + 14, 4*64*1024);
- if (DEBUG) Log.d(TAG, "created");
+ FayeConfigurations.tracker(this, "created");
}
@@ -392,7 +390,7 @@ public void handleMessage(Message msg) {
} catch (Exception e) {
- if (DEBUG) e.printStackTrace();
+ FayeConfigurations.logException(e);
// wrap the exception and notify master
notify(new WebSocketMessage.Error(e));
@@ -442,7 +440,7 @@ protected void processMessage(Object msg) throws IOException, WebSocketException
mLooper.quit();
- if (DEBUG) Log.d(TAG, "ended");
+ FayeConfigurations.tracker(this, "ended");
return;
diff --git a/src/com/b3rwynmobile/fayeclient/config/FayeConfigurations.java b/src/com/b3rwynmobile/fayeclient/config/FayeConfigurations.java
new file mode 100644
index 0000000..a174cd7
--- /dev/null
+++ b/src/com/b3rwynmobile/fayeclient/config/FayeConfigurations.java
@@ -0,0 +1,57 @@
+package com.b3rwynmobile.fayeclient.config;
+
+import android.util.Log;
+
+/**
+ * @author Ademar Alves de Oliveira
+ * @Apr 23, 2013
+ * @email ademar111190@gmail.com
+ */
+public class FayeConfigurations {
+
+ // TODO a way to force an override the shared instance and FAYE_xx variables
+ /**
+ * Singleton access
+ */
+ public static FayeConfigurations shared = new FayeConfigurations();
+
+ public String FAYE_URL = "ws://your.url:80/mount";
+ public String FAYE_INITIAL_CHANNEL = "/your_channel";
+ public String FAYE_AUTH_TOKEN = "";
+
+ public boolean logEnabled = false;
+ public boolean logMethodTrackerEnabled = false;
+ public boolean logExceptionsEnabled = false;
+ public String logTag = "FayeAndroid";
+ public String logMethodTrackerTag = "FayeAndroidMethodTracer";
+ public String logExceptionTag = "FayeAndroidException";
+
+ public static void log(Object... args) {
+ if (shared.logEnabled) {
+ String message = new String();
+ for (Object o : args)
+ message += o + " - ";
+ android.util.Log.d(shared.logTag, message);
+ }
+ }
+
+ public static void tracker(Object instance, Object... params) {
+ if (shared.logMethodTrackerEnabled) {
+ String s = "";
+ int i = 1;
+ for (Object string : params) {
+ s += i + ":" + string + " , ";
+ i++;
+ }
+ android.util.Log.d(shared.logMethodTrackerTag, "Method: "
+ + Thread.currentThread().getStackTrace()[3] + " instance: "
+ + (instance == null ? "Null" : instance) + " params: " + s);
+ }
+ }
+
+ public static void logException(Exception e) {
+ if (shared.logEnabled) {
+ Log.e(shared.logExceptionTag, e.toString());
+ }
+ }
+}
diff --git a/src/com/b3rwynmobile/fayeclient/models/FayeAdvice.java b/src/com/b3rwynmobile/fayeclient/models/FayeAdvice.java
index 64786a6..82ded25 100644
--- a/src/com/b3rwynmobile/fayeclient/models/FayeAdvice.java
+++ b/src/com/b3rwynmobile/fayeclient/models/FayeAdvice.java
@@ -20,10 +20,10 @@
package com.b3rwynmobile.fayeclient.models;
-public class FayeAdvice {
+public class FayeAdvice extends FayeModelAbstract {
private String reconnect;
- private int interval;
+ private int interval;
private long timeout;
public String getReconnect() {
diff --git a/src/com/b3rwynmobile/fayeclient/models/FayeData.java b/src/com/b3rwynmobile/fayeclient/models/FayeData.java
index d3bedcb..fc1f992 100644
--- a/src/com/b3rwynmobile/fayeclient/models/FayeData.java
+++ b/src/com/b3rwynmobile/fayeclient/models/FayeData.java
@@ -20,12 +20,12 @@
package com.b3rwynmobile.fayeclient.models;
-public class FayeData {
+public class FayeData extends FayeModelAbstract {
- private String timestamp;
- private String content;
+ private String timestamp;
+ private String content;
private FayeTopic topic;
- private String id;
+ private String id;
public String getTimestamp() {
return timestamp;
diff --git a/src/com/b3rwynmobile/fayeclient/models/FayeMessage.java b/src/com/b3rwynmobile/fayeclient/models/FayeMessage.java
index 3e97b2c..0946b70 100644
--- a/src/com/b3rwynmobile/fayeclient/models/FayeMessage.java
+++ b/src/com/b3rwynmobile/fayeclient/models/FayeMessage.java
@@ -22,27 +22,27 @@
import com.google.gson.annotations.SerializedName;
-public class FayeMessage {
+public class FayeMessage extends FayeModelAbstract {
// General
- private String channel;
+ private String channel;
// Handshake
- private String version;
+ private String version;
private String[] supportedConnectionTypes;
private FayeAdvice advice;
// Event
- private Object data;
+ private Object data;
// (Un-)Subscribe
- private String subscription;
- private String error;
+ private String subscription;
+ private String error;
// Handshake + Subscribe
- private boolean successful;
+ private boolean successful;
@SerializedName("clientId")
- private String clientId;
+ private String clientId;
public String getChannel() {
return channel;
diff --git a/src/com/b3rwynmobile/fayeclient/models/FayeModelAbstract.java b/src/com/b3rwynmobile/fayeclient/models/FayeModelAbstract.java
new file mode 100644
index 0000000..3297834
--- /dev/null
+++ b/src/com/b3rwynmobile/fayeclient/models/FayeModelAbstract.java
@@ -0,0 +1,20 @@
+package com.b3rwynmobile.fayeclient.models;
+
+import com.google.gson.Gson;
+
+/**
+ * @author Ademar Alves de Oliveira
+ * @Apr 23, 2013
+ * @email ademar111190@gmail.com
+ */
+public class FayeModelAbstract {
+
+ /**
+ * to string automatically generate a json string
+ */
+ @Override
+ public String toString() {
+ return new Gson().toJson(this);
+ }
+
+}
diff --git a/src/com/b3rwynmobile/fayeclient/models/FayeTopic.java b/src/com/b3rwynmobile/fayeclient/models/FayeTopic.java
index 3551e6c..00165ec 100644
--- a/src/com/b3rwynmobile/fayeclient/models/FayeTopic.java
+++ b/src/com/b3rwynmobile/fayeclient/models/FayeTopic.java
@@ -20,20 +20,23 @@
package com.b3rwynmobile.fayeclient.models;
-public class FayeTopic {
+public class FayeTopic extends FayeModelAbstract {
private String type;
private String id;
-
+
public String getType() {
return type;
}
+
public void setType(String type) {
this.type = type;
}
+
public String getId() {
return id;
}
+
public void setId(String id) {
this.id = id;
}