Commit 2a383afd authored by Yusuke Iwaki's avatar Yusuke Iwaki

fix checkstyle issues

parent 4e101ae7
...@@ -5,7 +5,7 @@ import android.content.Intent; ...@@ -5,7 +5,7 @@ import android.content.Intent;
import chat.rocket.android.activity.ServerConfigActivity; import chat.rocket.android.activity.ServerConfigActivity;
/** /**
* utility class for launching Activity * utility class for launching Activity.
*/ */
public class LaunchUtil { public class LaunchUtil {
/** /**
......
...@@ -24,11 +24,11 @@ import jp.co.crowdworks.realm_java_helpers.RealmObjectObserver; ...@@ -24,11 +24,11 @@ import jp.co.crowdworks.realm_java_helpers.RealmObjectObserver;
*/ */
public class ServerConfigActivity extends AbstractFragmentActivity { public class ServerConfigActivity extends AbstractFragmentActivity {
private String mServerConfigId; private String serverConfigId;
private RealmObjectObserver<ServerConfig> mServerConfigObserver = private RealmObjectObserver<ServerConfig> serverConfigObserver =
new RealmObjectObserver<ServerConfig>() { new RealmObjectObserver<ServerConfig>() {
@Override protected RealmQuery<ServerConfig> query(Realm realm) { @Override protected RealmQuery<ServerConfig> query(Realm realm) {
return realm.where(ServerConfig.class).equalTo("id", mServerConfigId); return realm.where(ServerConfig.class).equalTo("id", serverConfigId);
} }
@Override protected void onChange(ServerConfig config) { @Override protected void onChange(ServerConfig config) {
...@@ -93,8 +93,8 @@ public class ServerConfigActivity extends AbstractFragmentActivity { ...@@ -93,8 +93,8 @@ public class ServerConfigActivity extends AbstractFragmentActivity {
return; return;
} }
mServerConfigId = intent.getStringExtra("id"); serverConfigId = intent.getStringExtra("id");
if (TextUtils.isEmpty(mServerConfigId)) { if (TextUtils.isEmpty(serverConfigId)) {
finish(); finish();
return; return;
} }
...@@ -105,11 +105,11 @@ public class ServerConfigActivity extends AbstractFragmentActivity { ...@@ -105,11 +105,11 @@ public class ServerConfigActivity extends AbstractFragmentActivity {
@Override protected void onResume() { @Override protected void onResume() {
super.onResume(); super.onResume();
RocketChatService.keepalive(this); RocketChatService.keepalive(this);
mServerConfigObserver.sub(); serverConfigObserver.sub();
} }
@Override protected void onPause() { @Override protected void onPause() {
mServerConfigObserver.unsub(); serverConfigObserver.unsub();
super.onPause(); super.onPause();
} }
...@@ -152,21 +152,21 @@ public class ServerConfigActivity extends AbstractFragmentActivity { ...@@ -152,21 +152,21 @@ public class ServerConfigActivity extends AbstractFragmentActivity {
} }
@Override protected void showFragment(Fragment fragment) { @Override protected void showFragment(Fragment fragment) {
injectIdArgTo(fragment); injectServerConfigIdArgTo(fragment);
super.showFragment(fragment); super.showFragment(fragment);
} }
@Override protected void showFragmentWithBackStack(Fragment fragment) { @Override protected void showFragmentWithBackStack(Fragment fragment) {
injectIdArgTo(fragment); injectServerConfigIdArgTo(fragment);
super.showFragmentWithBackStack(fragment); super.showFragmentWithBackStack(fragment);
} }
private void injectIdArgTo(Fragment fragment) { private void injectServerConfigIdArgTo(Fragment fragment) {
Bundle args = fragment.getArguments(); Bundle args = fragment.getArguments();
if (args == null) { if (args == null) {
args = new Bundle(); args = new Bundle();
} }
args.putString("id", mServerConfigId); args.putString("id", serverConfigId);
fragment.setArguments(args); fragment.setArguments(args);
} }
......
...@@ -12,18 +12,19 @@ import android.view.ViewGroup; ...@@ -12,18 +12,19 @@ import android.view.ViewGroup;
* Fragment base class for this Application. * Fragment base class for this Application.
*/ */
public abstract class AbstractFragment extends Fragment { public abstract class AbstractFragment extends Fragment {
protected View mRootView; protected View rootView;
protected abstract @LayoutRes int getLayout(); protected abstract @LayoutRes int getLayout();
protected abstract void onSetupView(); protected abstract void onSetupView();
@Nullable @Override @Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) { @Nullable Bundle savedInstanceState) {
mRootView = inflater.inflate(getLayout(), container, false); rootView = inflater.inflate(getLayout(), container, false);
onSetupView(); onSetupView();
return mRootView; return rootView;
} }
protected void finish() { protected void finish() {
......
...@@ -6,7 +6,7 @@ import chat.rocket.android.fragment.AbstractFragment; ...@@ -6,7 +6,7 @@ import chat.rocket.android.fragment.AbstractFragment;
import chat.rocket.android.helper.TextUtils; import chat.rocket.android.helper.TextUtils;
abstract class AbstractServerConfigFragment extends AbstractFragment { abstract class AbstractServerConfigFragment extends AbstractFragment {
protected String mServerConfigId; protected String serverConfigId;
@Override public void onCreate(@Nullable Bundle savedInstanceState) { @Override public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
...@@ -17,8 +17,8 @@ abstract class AbstractServerConfigFragment extends AbstractFragment { ...@@ -17,8 +17,8 @@ abstract class AbstractServerConfigFragment extends AbstractFragment {
return; return;
} }
mServerConfigId = args.getString("id"); serverConfigId = args.getString("id");
if (TextUtils.isEmpty(mServerConfigId)) { if (TextUtils.isEmpty(serverConfigId)) {
finish(); finish();
return; return;
} }
......
...@@ -18,14 +18,14 @@ import org.json.JSONObject; ...@@ -18,14 +18,14 @@ import org.json.JSONObject;
* Input server host. * Input server host.
*/ */
public class InputHostnameFragment extends AbstractServerConfigFragment { public class InputHostnameFragment extends AbstractServerConfigFragment {
private Handler mShowError = new Handler() { private Handler errorShowingHandler = new Handler() {
@Override public void handleMessage(Message msg) { @Override public void handleMessage(Message msg) {
Toast.makeText(mRootView.getContext(), (String) msg.obj, Toast.LENGTH_SHORT).show(); Toast.makeText(rootView.getContext(), (String) msg.obj, Toast.LENGTH_SHORT).show();
} }
}; };
RealmObjectObserver<ServerConfig> mObserver = new RealmObjectObserver<ServerConfig>() { RealmObjectObserver<ServerConfig> serverConfigObserver = new RealmObjectObserver<ServerConfig>() {
@Override protected RealmQuery<ServerConfig> query(Realm realm) { @Override protected RealmQuery<ServerConfig> query(Realm realm) {
return realm.where(ServerConfig.class).equalTo("id", mServerConfigId); return realm.where(ServerConfig.class).equalTo("id", serverConfigId);
} }
@Override protected void onChange(ServerConfig config) { @Override protected void onChange(ServerConfig config) {
...@@ -41,42 +41,42 @@ public class InputHostnameFragment extends AbstractServerConfigFragment { ...@@ -41,42 +41,42 @@ public class InputHostnameFragment extends AbstractServerConfigFragment {
} }
@Override protected void onSetupView() { @Override protected void onSetupView() {
mRootView.findViewById(R.id.btn_connect).setOnClickListener(view -> handleConnect()); rootView.findViewById(R.id.btn_connect).setOnClickListener(view -> handleConnect());
mObserver.sub(); serverConfigObserver.sub();
} }
private void handleConnect() { private void handleConnect() {
final TextView editor = (TextView) mRootView.findViewById(R.id.editor_hostname); final TextView editor = (TextView) rootView.findViewById(R.id.editor_hostname);
final String hostname = final String hostname =
TextUtils.or(TextUtils.or(editor.getText(), editor.getHint()), "").toString(); TextUtils.or(TextUtils.or(editor.getText(), editor.getHint()), "").toString();
RealmHelperBolts.executeTransaction( RealmHelperBolts.executeTransaction(
realm -> realm.createOrUpdateObjectFromJson(ServerConfig.class, realm -> realm.createOrUpdateObjectFromJson(ServerConfig.class,
new JSONObject().put("id", mServerConfigId) new JSONObject().put("id", serverConfigId)
.put("hostname", hostname) .put("hostname", hostname)
.put("connectionError", JSONObject.NULL))).continueWith(new LogcatIfError()); .put("connectionError", JSONObject.NULL))).continueWith(new LogcatIfError());
} }
@Override public void onResume() { @Override public void onResume() {
super.onResume(); super.onResume();
mObserver.keepalive(); serverConfigObserver.keepalive();
} }
@Override public void onDestroyView() { @Override public void onDestroyView() {
mObserver.unsub(); serverConfigObserver.unsub();
super.onDestroyView(); super.onDestroyView();
} }
private void showError(String errString) { private void showError(String errString) {
mShowError.removeMessages(0); errorShowingHandler.removeMessages(0);
Message msg = Message.obtain(mShowError, 0, errString); Message msg = Message.obtain(errorShowingHandler, 0, errString);
mShowError.sendMessageDelayed(msg, 160); errorShowingHandler.sendMessageDelayed(msg, 160);
} }
private void onRenderServerConfig(ServerConfig config) { private void onRenderServerConfig(ServerConfig config) {
final TextView editor = (TextView) mRootView.findViewById(R.id.editor_hostname); final TextView editor = (TextView) rootView.findViewById(R.id.editor_hostname);
if (!TextUtils.isEmpty(config.getHostname())) { if (!TextUtils.isEmpty(config.getHostname())) {
editor.setText(config.getHostname()); editor.setText(config.getHostname());
...@@ -90,7 +90,7 @@ public class InputHostnameFragment extends AbstractServerConfigFragment { ...@@ -90,7 +90,7 @@ public class InputHostnameFragment extends AbstractServerConfigFragment {
private void clearConnectionErrorAndHostname() { private void clearConnectionErrorAndHostname() {
RealmHelperBolts.executeTransaction( RealmHelperBolts.executeTransaction(
realm -> realm.createOrUpdateObjectFromJson(ServerConfig.class, realm -> realm.createOrUpdateObjectFromJson(ServerConfig.class,
new JSONObject().put("id", mServerConfigId) new JSONObject().put("id", serverConfigId)
.put("hostname", JSONObject.NULL) .put("hostname", JSONObject.NULL)
.put("connectionError", JSONObject.NULL))).continueWith(new LogcatIfError()); .put("connectionError", JSONObject.NULL))).continueWith(new LogcatIfError());
} }
......
...@@ -19,7 +19,8 @@ public class TextUtils { ...@@ -19,7 +19,8 @@ public class TextUtils {
/** /**
* Returns str if it is not empty; otherwise defaultValue is returned. * Returns str if it is not empty; otherwise defaultValue is returned.
*/ */
@SuppressWarnings("PMD.ShortMethodName") public static CharSequence or(CharSequence str, @SuppressWarnings("PMD.ShortMethodName")
public static CharSequence or(CharSequence str,
CharSequence defaultValue) { CharSequence defaultValue) {
if (isEmpty(str)) { if (isEmpty(str)) {
return defaultValue; return defaultValue;
......
...@@ -4,9 +4,10 @@ import io.realm.RealmObject; ...@@ -4,9 +4,10 @@ import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey; import io.realm.annotations.PrimaryKey;
/** /**
* subscription model for "meteor_accounts_loginServiceConfiguration" * subscription model for "meteor_accounts_loginServiceConfiguration".
*/ */
@SuppressWarnings("PMD.ShortVariable") public class MeteorLoginServiceConfiguration @SuppressWarnings("PMD.ShortVariable")
public class MeteorLoginServiceConfiguration
extends RealmObject { extends RealmObject {
@PrimaryKey private String id; @PrimaryKey private String id;
private String service; private String service;
......
...@@ -12,9 +12,10 @@ import jp.co.crowdworks.realm_java_helpers_bolts.RealmHelperBolts; ...@@ -12,9 +12,10 @@ import jp.co.crowdworks.realm_java_helpers_bolts.RealmHelperBolts;
import org.json.JSONObject; import org.json.JSONObject;
/** /**
* Server configuration * Server configuration.
*/ */
@SuppressWarnings("PMD.ShortVariable") public class ServerConfig extends RealmObject { @SuppressWarnings("PMD.ShortVariable")
public class ServerConfig extends RealmObject {
@PrimaryKey private String id; @PrimaryKey private String id;
private String hostname; private String hostname;
private String connectionError; private String connectionError;
......
package chat.rocket.android.service; package chat.rocket.android.service;
/** /**
* interface for observer and ddp_subscription * interface for observer and ddp_subscription.
*/ */
public interface Registerable { public interface Registerable {
/** /**
* register * register.
*/ */
void register(); void register();
/** /**
* keepalive * keepalive.
*/ */
void keepalive(); void keepalive();
/** /**
* unregister * unregister.
*/ */
void unregister(); void unregister();
} }
...@@ -20,8 +20,8 @@ import jp.co.crowdworks.realm_java_helpers.RealmListObserver; ...@@ -20,8 +20,8 @@ import jp.co.crowdworks.realm_java_helpers.RealmListObserver;
*/ */
public class RocketChatService extends Service { public class RocketChatService extends Service {
private HashMap<String, RocketChatWebSocketThread> mWebSocketThreads; private HashMap<String, RocketChatWebSocketThread> webSocketThreads;
private RealmListObserver<ServerConfig> mConnectionRequiredServerConfigObserver = private RealmListObserver<ServerConfig> connectionRequiredServerConfigObserver =
new RealmListObserver<ServerConfig>() { new RealmListObserver<ServerConfig>() {
@Override protected RealmResults<ServerConfig> queryItems(Realm realm) { @Override protected RealmResults<ServerConfig> queryItems(Realm realm) {
return realm.where(ServerConfig.class) return realm.where(ServerConfig.class)
...@@ -51,17 +51,17 @@ public class RocketChatService extends Service { ...@@ -51,17 +51,17 @@ public class RocketChatService extends Service {
@Override public void onCreate() { @Override public void onCreate() {
super.onCreate(); super.onCreate();
mWebSocketThreads = new HashMap<>(); webSocketThreads = new HashMap<>();
} }
@Override public int onStartCommand(Intent intent, int flags, int startId) { @Override public int onStartCommand(Intent intent, int flags, int startId) {
mConnectionRequiredServerConfigObserver.keepalive(); connectionRequiredServerConfigObserver.keepalive();
return START_STICKY; return START_STICKY;
} }
private void syncWebSocketThreadsWith(List<ServerConfig> configList) { private void syncWebSocketThreadsWith(List<ServerConfig> configList) {
final Iterator<Map.Entry<String, RocketChatWebSocketThread>> iterator = final Iterator<Map.Entry<String, RocketChatWebSocketThread>> iterator =
mWebSocketThreads.entrySet().iterator(); webSocketThreads.entrySet().iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
Map.Entry<String, RocketChatWebSocketThread> entry = iterator.next(); Map.Entry<String, RocketChatWebSocketThread> entry = iterator.next();
...@@ -90,18 +90,20 @@ public class RocketChatService extends Service { ...@@ -90,18 +90,20 @@ public class RocketChatService extends Service {
private Task<RocketChatWebSocketThread> findOrCreateWebSocketThread(final ServerConfig config) { private Task<RocketChatWebSocketThread> findOrCreateWebSocketThread(final ServerConfig config) {
final String serverConfigId = config.getId(); final String serverConfigId = config.getId();
if (mWebSocketThreads.containsKey(serverConfigId)) { if (webSocketThreads.containsKey(serverConfigId)) {
return Task.forResult(mWebSocketThreads.get(serverConfigId)); return Task.forResult(webSocketThreads.get(serverConfigId));
} else { } else {
return RocketChatWebSocketThread.getStarted(getApplicationContext(), config) return RocketChatWebSocketThread.getStarted(getApplicationContext(), config)
.onSuccessTask(task -> { .onSuccessTask(task -> {
mWebSocketThreads.put(serverConfigId, task.getResult()); webSocketThreads.put(serverConfigId, task.getResult());
return task; return task;
}); });
} }
} }
@Nullable @Override public IBinder onBind(Intent intent) { @Nullable
@Override
public IBinder onBind(Intent intent) {
return null; return null;
} }
} }
...@@ -24,17 +24,17 @@ public class RocketChatWebSocketThread extends HandlerThread { ...@@ -24,17 +24,17 @@ public class RocketChatWebSocketThread extends HandlerThread {
private static final Class[] REGISTERABLE_CLASSES = { private static final Class[] REGISTERABLE_CLASSES = {
LoginServiceConfigurationSubscriber.class LoginServiceConfigurationSubscriber.class
}; };
private final Context mAppContext; private final Context appContext;
private final String mServerConfigId; private final String serverConfigId;
private final ArrayList<Registerable> mListeners = new ArrayList<>(); private final ArrayList<Registerable> listeners = new ArrayList<>();
private RocketChatWebSocketAPI mWebSocketAPI; private RocketChatWebSocketAPI webSocketAPI;
private boolean mSocketExists; private boolean socketExists;
private boolean mListenersRegistered; private boolean listenersRegistered;
private RocketChatWebSocketThread(Context appContext, String serverConfigId) { private RocketChatWebSocketThread(Context appContext, String serverConfigId) {
super("RC_thread_" + serverConfigId); super("RC_thread_" + serverConfigId);
mServerConfigId = serverConfigId; this.serverConfigId = serverConfigId;
mAppContext = appContext; this.appContext = appContext;
} }
/** /**
...@@ -57,14 +57,14 @@ public class RocketChatWebSocketThread extends HandlerThread { ...@@ -57,14 +57,14 @@ public class RocketChatWebSocketThread extends HandlerThread {
} }
/** /**
* terminate the thread * terminate the thread.
*/ */
@DebugLog public static void terminate(RocketChatWebSocketThread thread) { @DebugLog public static void terminate(RocketChatWebSocketThread thread) {
thread.quit(); thread.quit();
} }
private Task<Void> ensureConnection() { private Task<Void> ensureConnection() {
if (mWebSocketAPI == null || !mWebSocketAPI.isConnected()) { if (webSocketAPI == null || !webSocketAPI.isConnected()) {
return registerListeners(); return registerListeners();
} else { } else {
return Task.forResult(null); return Task.forResult(null);
...@@ -113,21 +113,21 @@ public class RocketChatWebSocketThread extends HandlerThread { ...@@ -113,21 +113,21 @@ public class RocketChatWebSocketThread extends HandlerThread {
private void prepareWebSocket() { private void prepareWebSocket() {
ServerConfig config = RealmHelper.executeTransactionForRead( ServerConfig config = RealmHelper.executeTransactionForRead(
realm -> realm.where(ServerConfig.class).equalTo("id", mServerConfigId).findFirst()); realm -> realm.where(ServerConfig.class).equalTo("id", serverConfigId).findFirst());
if (mWebSocketAPI == null || !mWebSocketAPI.isConnected()) { if (webSocketAPI == null || !webSocketAPI.isConnected()) {
mWebSocketAPI = RocketChatWebSocketAPI.create(config.getHostname()); webSocketAPI = RocketChatWebSocketAPI.create(config.getHostname());
} }
} }
@DebugLog private Task<Void> registerListeners() { @DebugLog private Task<Void> registerListeners() {
if (mSocketExists) { if (socketExists) {
return Task.forResult(null); return Task.forResult(null);
} }
mSocketExists = true; socketExists = true;
prepareWebSocket(); prepareWebSocket();
return mWebSocketAPI.connect().onSuccess(task -> { return webSocketAPI.connect().onSuccess(task -> {
registerListenersActually(); registerListenersActually();
DDPClient client = task.getResult().client; DDPClient client = task.getResult().client;
...@@ -146,7 +146,7 @@ public class RocketChatWebSocketThread extends HandlerThread { ...@@ -146,7 +146,7 @@ public class RocketChatWebSocketThread extends HandlerThread {
return null; return null;
}).continueWith(task -> { }).continueWith(task -> {
if (task.isFaulted()) { if (task.isFaulted()) {
ServerConfig.logError(mServerConfigId, task.getError()); ServerConfig.logError(serverConfigId, task.getError());
} }
return null; return null;
}); });
...@@ -154,20 +154,20 @@ public class RocketChatWebSocketThread extends HandlerThread { ...@@ -154,20 +154,20 @@ public class RocketChatWebSocketThread extends HandlerThread {
//@DebugLog //@DebugLog
private void registerListenersActually() { private void registerListenersActually() {
if (mListenersRegistered) { if (listenersRegistered) {
return; return;
} }
mListenersRegistered = true; listenersRegistered = true;
for (Class clazz : REGISTERABLE_CLASSES) { for (Class clazz : REGISTERABLE_CLASSES) {
try { try {
Constructor ctor = clazz.getConstructor(Context.class, RocketChatWebSocketAPI.class); Constructor ctor = clazz.getConstructor(Context.class, RocketChatWebSocketAPI.class);
Object obj = ctor.newInstance(mAppContext, mWebSocketAPI); Object obj = ctor.newInstance(appContext, webSocketAPI);
if (obj instanceof Registerable) { if (obj instanceof Registerable) {
Registerable registerable = (Registerable) obj; Registerable registerable = (Registerable) obj;
registerable.register(); registerable.register();
mListeners.add(registerable); listeners.add(registerable);
} }
} catch (Exception exception) { } catch (Exception exception) {
Timber.w(exception, "Failed to register listeners!!"); Timber.w(exception, "Failed to register listeners!!");
...@@ -177,32 +177,32 @@ public class RocketChatWebSocketThread extends HandlerThread { ...@@ -177,32 +177,32 @@ public class RocketChatWebSocketThread extends HandlerThread {
//@DebugLog //@DebugLog
private void keepaliveListeners() { private void keepaliveListeners() {
if (!mSocketExists || !mListenersRegistered) { if (!socketExists || !listenersRegistered) {
return; return;
} }
for (Registerable registerable : mListeners) { for (Registerable registerable : listeners) {
registerable.keepalive(); registerable.keepalive();
} }
} }
//@DebugLog //@DebugLog
private void unregisterListeners() { private void unregisterListeners() {
if (!mSocketExists || !mListenersRegistered) { if (!socketExists || !listenersRegistered) {
return; return;
} }
Iterator<Registerable> iterator = mListeners.iterator(); Iterator<Registerable> iterator = listeners.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
Registerable registerable = iterator.next(); Registerable registerable = iterator.next();
registerable.unregister(); registerable.unregister();
iterator.remove(); iterator.remove();
} }
if (mWebSocketAPI != null) { if (webSocketAPI != null) {
mWebSocketAPI.close(); webSocketAPI.close();
mWebSocketAPI = null; webSocketAPI = null;
} }
mListenersRegistered = false; listenersRegistered = false;
mSocketExists = false; socketExists = false;
} }
} }
...@@ -16,14 +16,14 @@ import rx.Subscription; ...@@ -16,14 +16,14 @@ import rx.Subscription;
import timber.log.Timber; import timber.log.Timber;
abstract class AbstractDDPDocEventSubscriber implements Registerable { abstract class AbstractDDPDocEventSubscriber implements Registerable {
protected final Context mContext; protected final Context context;
protected final RocketChatWebSocketAPI mAPI; protected final RocketChatWebSocketAPI webSocketAPI;
private String mID; private String subscriptionId;
private Subscription mSubscription; private Subscription rxSubscription;
protected AbstractDDPDocEventSubscriber(Context context, RocketChatWebSocketAPI api) { protected AbstractDDPDocEventSubscriber(Context context, RocketChatWebSocketAPI api) {
mContext = context; this.context = context;
mAPI = api; this.webSocketAPI = api;
} }
protected abstract String getSubscriptionName(); protected abstract String getSubscriptionName();
...@@ -32,13 +32,13 @@ abstract class AbstractDDPDocEventSubscriber implements Registerable { ...@@ -32,13 +32,13 @@ abstract class AbstractDDPDocEventSubscriber implements Registerable {
protected abstract Class<? extends RealmObject> getModelClass(); protected abstract Class<? extends RealmObject> getModelClass();
protected JSONObject customizeFieldJSON(JSONObject json) { protected JSONObject customizeFieldJson(JSONObject json) {
return json; return json;
} }
@Override public void register() { @Override public void register() {
mAPI.subscribe(getSubscriptionName(), null).onSuccess(task -> { webSocketAPI.subscribe(getSubscriptionName(), null).onSuccess(task -> {
mID = task.getResult().id; subscriptionId = task.getResult().id;
return null; return null;
}).continueWith(task -> { }).continueWith(task -> {
if (task.isFaulted()) { if (task.isFaulted()) {
...@@ -57,7 +57,7 @@ abstract class AbstractDDPDocEventSubscriber implements Registerable { ...@@ -57,7 +57,7 @@ abstract class AbstractDDPDocEventSubscriber implements Registerable {
} }
private void registerSubscriptionCallback() { private void registerSubscriptionCallback() {
mSubscription = mAPI.getSubscriptionCallback() rxSubscription = webSocketAPI.getSubscriptionCallback()
.filter(event -> event instanceof DDPSubscription.DocEvent) .filter(event -> event instanceof DDPSubscription.DocEvent)
.cast(DDPSubscription.DocEvent.class) .cast(DDPSubscription.DocEvent.class)
.filter(event -> getSubscriptionCallbackName().equals(event.collection)) .filter(event -> getSubscriptionCallbackName().equals(event.collection))
...@@ -74,8 +74,8 @@ abstract class AbstractDDPDocEventSubscriber implements Registerable { ...@@ -74,8 +74,8 @@ abstract class AbstractDDPDocEventSubscriber implements Registerable {
} else if (docEvent instanceof DDPSubscription.MovedBefore) { } else if (docEvent instanceof DDPSubscription.MovedBefore) {
//ignore movedBefore //ignore movedBefore
} }
} catch (Exception e) { } catch (Exception exception) {
Timber.w(e, "failed to handle subscription callback"); Timber.w(exception, "failed to handle subscription callback");
} }
}); });
} }
...@@ -87,35 +87,20 @@ abstract class AbstractDDPDocEventSubscriber implements Registerable { ...@@ -87,35 +87,20 @@ abstract class AbstractDDPDocEventSubscriber implements Registerable {
}).continueWith(new LogcatIfError()); }).continueWith(new LogcatIfError());
} }
protected void onDocumentChanged(DDPSubscription.Changed docEvent) { private void onDocumentAdded(Realm realm, DDPSubscription.Added docEvent) throws JSONException {
RealmHelperBolts.executeTransaction(realm -> { //executed in RealmTransaction
onDocumentChanged(realm, docEvent); JSONObject json = new JSONObject().put("id", docEvent.docID);
return null; mergeJson(json, docEvent.fields);
}).continueWith(new LogcatIfError()); realm.createOrUpdateObjectFromJson(getModelClass(), customizeFieldJson(json));
} }
protected void onDocumentRemoved(DDPSubscription.Removed docEvent) { protected void onDocumentChanged(DDPSubscription.Changed docEvent) {
RealmHelperBolts.executeTransaction(realm -> { RealmHelperBolts.executeTransaction(realm -> {
onDocumentRemoved(realm, docEvent); onDocumentChanged(realm, docEvent);
return null; return null;
}).continueWith(new LogcatIfError()); }).continueWith(new LogcatIfError());
} }
private void mergeJSON(JSONObject target, JSONObject src) throws JSONException {
Iterator<String> iterator = src.keys();
while (iterator.hasNext()) {
String key = iterator.next();
target.put(key, src.get(key));
}
}
private void onDocumentAdded(Realm realm, DDPSubscription.Added docEvent) throws JSONException {
//executed in RealmTransaction
JSONObject json = new JSONObject().put("id", docEvent.docID);
mergeJSON(json, docEvent.fields);
realm.createOrUpdateObjectFromJson(getModelClass(), customizeFieldJSON(json));
}
private void onDocumentChanged(Realm realm, DDPSubscription.Changed docEvent) private void onDocumentChanged(Realm realm, DDPSubscription.Changed docEvent)
throws JSONException { throws JSONException {
//executed in RealmTransaction //executed in RealmTransaction
...@@ -124,8 +109,15 @@ abstract class AbstractDDPDocEventSubscriber implements Registerable { ...@@ -124,8 +109,15 @@ abstract class AbstractDDPDocEventSubscriber implements Registerable {
String fieldToDelete = docEvent.cleared.getString(i); String fieldToDelete = docEvent.cleared.getString(i);
json.remove(fieldToDelete); json.remove(fieldToDelete);
} }
mergeJSON(json, docEvent.fields); mergeJson(json, docEvent.fields);
realm.createOrUpdateObjectFromJson(getModelClass(), customizeFieldJSON(json)); realm.createOrUpdateObjectFromJson(getModelClass(), customizeFieldJson(json));
}
protected void onDocumentRemoved(DDPSubscription.Removed docEvent) {
RealmHelperBolts.executeTransaction(realm -> {
onDocumentRemoved(realm, docEvent);
return null;
}).continueWith(new LogcatIfError());
} }
private void onDocumentRemoved(Realm realm, DDPSubscription.Removed docEvent) private void onDocumentRemoved(Realm realm, DDPSubscription.Removed docEvent)
...@@ -134,16 +126,24 @@ abstract class AbstractDDPDocEventSubscriber implements Registerable { ...@@ -134,16 +126,24 @@ abstract class AbstractDDPDocEventSubscriber implements Registerable {
realm.where(getModelClass()).equalTo("id", docEvent.docID).findAll().deleteAllFromRealm(); realm.where(getModelClass()).equalTo("id", docEvent.docID).findAll().deleteAllFromRealm();
} }
private void mergeJson(JSONObject target, JSONObject src) throws JSONException {
Iterator<String> iterator = src.keys();
while (iterator.hasNext()) {
String key = iterator.next();
target.put(key, src.get(key));
}
}
@Override public void keepalive() { @Override public void keepalive() {
} }
@Override public void unregister() { @Override public void unregister() {
if (mSubscription != null) { if (rxSubscription != null) {
mSubscription.unsubscribe(); rxSubscription.unsubscribe();
} }
if (!TextUtils.isEmpty(mID)) { if (!TextUtils.isEmpty(subscriptionId)) {
mAPI.unsubscribe(mID).continueWith(new LogcatIfError()); webSocketAPI.unsubscribe(subscriptionId).continueWith(new LogcatIfError());
} }
} }
} }
...@@ -9,12 +9,12 @@ import jp.co.crowdworks.realm_java_helpers.RealmListObserver; ...@@ -9,12 +9,12 @@ import jp.co.crowdworks.realm_java_helpers.RealmListObserver;
abstract class AbstractModelObserver<T extends RealmObject> extends RealmListObserver<T> abstract class AbstractModelObserver<T extends RealmObject> extends RealmListObserver<T>
implements Registerable { implements Registerable {
protected final Context mContext; protected final Context context;
protected final RocketChatWebSocketAPI mAPI; protected final RocketChatWebSocketAPI webSocketAPI;
protected AbstractModelObserver(Context context, RocketChatWebSocketAPI api) { protected AbstractModelObserver(Context context, RocketChatWebSocketAPI api) {
mContext = context; this.context = context;
mAPI = api; webSocketAPI = api;
} }
@Override public void register() { @Override public void register() {
......
...@@ -4,7 +4,7 @@ import android.content.Context; ...@@ -4,7 +4,7 @@ import android.content.Context;
import android.util.AttributeSet; import android.util.AttributeSet;
/** /**
* TextView with font-awesome * TextView with font-awesome.
*/ */
public class FontAwesomeTextView extends AbstractCustomFontTextView { public class FontAwesomeTextView extends AbstractCustomFontTextView {
public FontAwesomeTextView(Context context, AttributeSet attrs, int defStyle) { public FontAwesomeTextView(Context context, AttributeSet attrs, int defStyle) {
......
...@@ -4,7 +4,7 @@ import android.content.Context; ...@@ -4,7 +4,7 @@ import android.content.Context;
import android.util.AttributeSet; import android.util.AttributeSet;
/** /**
* TextView with fontello * TextView with fontello.
*/ */
public class FontelloTextView extends AbstractCustomFontTextView { public class FontelloTextView extends AbstractCustomFontTextView {
public FontelloTextView(Context context, AttributeSet attrs, int defStyle) { public FontelloTextView(Context context, AttributeSet attrs, int defStyle) {
......
...@@ -18,7 +18,7 @@ import java.util.ArrayList; ...@@ -18,7 +18,7 @@ import java.util.ArrayList;
* View for indicating "waiting for connection ..." and so on. * View for indicating "waiting for connection ..." and so on.
*/ */
public class WaitingView extends LinearLayout { public class WaitingView extends LinearLayout {
private ArrayList<View> mDots; private ArrayList<View> dots;
public WaitingView(Context context) { public WaitingView(Context context) {
super(context); super(context);
...@@ -53,7 +53,7 @@ public class WaitingView extends LinearLayout { ...@@ -53,7 +53,7 @@ public class WaitingView extends LinearLayout {
array.recycle(); array.recycle();
} }
mDots = new ArrayList<>(); dots = new ArrayList<>();
setOrientation(HORIZONTAL); setOrientation(HORIZONTAL);
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
addDot(context, size); addDot(context, size);
...@@ -78,12 +78,12 @@ public class WaitingView extends LinearLayout { ...@@ -78,12 +78,12 @@ public class WaitingView extends LinearLayout {
dot.setLayoutParams(new FrameLayout.LayoutParams(size, size, Gravity.CENTER)); dot.setLayoutParams(new FrameLayout.LayoutParams(size, size, Gravity.CENTER));
frameLayout.addView(dot); frameLayout.addView(dot);
addView(frameLayout); addView(frameLayout);
mDots.add(dot); dots.add(dot);
} }
private void start() { private void start() {
for (int i = 0; i < mDots.size(); i++) { for (int i = 0; i < dots.size(); i++) {
animateDot(mDots.get(i), 160 * i, 480, 480); animateDot(dots.get(i), 160 * i, 480, 480);
} }
} }
...@@ -111,7 +111,7 @@ public class WaitingView extends LinearLayout { ...@@ -111,7 +111,7 @@ public class WaitingView extends LinearLayout {
} }
private void cancel() { private void cancel() {
for (View dot : mDots) { for (View dot : dots) {
dot.clearAnimation(); dot.clearAnimation();
} }
} }
......
...@@ -13,12 +13,12 @@ import rx.Observable; ...@@ -13,12 +13,12 @@ import rx.Observable;
* API for several POST actions. * API for several POST actions.
*/ */
public class RocketChatWebSocketAPI { public class RocketChatWebSocketAPI {
private final DDPClient mDDPClient; private final DDPClient ddpClient;
private final String mHostName; private final String hostname;
private RocketChatWebSocketAPI(String hostname) { private RocketChatWebSocketAPI(String hostname) {
mDDPClient = new DDPClient(OkHttpHelper.getClientForWebSocket()); ddpClient = new DDPClient(OkHttpHelper.getClientForWebSocket());
mHostName = hostname; this.hostname = hostname;
} }
/** /**
...@@ -32,41 +32,41 @@ public class RocketChatWebSocketAPI { ...@@ -32,41 +32,41 @@ public class RocketChatWebSocketAPI {
* Connect to WebSocket server with DDP client. * Connect to WebSocket server with DDP client.
*/ */
public Task<DDPClientCallback.Connect> connect() { public Task<DDPClientCallback.Connect> connect() {
return mDDPClient.connect("wss://" + mHostName + "/websocket"); return ddpClient.connect("wss://" + hostname + "/websocket");
} }
/** /**
* Returns whether DDP client is connected to WebSocket server. * Returns whether DDP client is connected to WebSocket server.
*/ */
public boolean isConnected() { public boolean isConnected() {
return mDDPClient.isConnected(); return ddpClient.isConnected();
} }
/** /**
* close connection. * close connection.
*/ */
public void close() { public void close() {
mDDPClient.close(); ddpClient.close();
} }
/** /**
* Subscribe with DDP client. * Subscribe with DDP client.
*/ */
public Task<DDPSubscription.Ready> subscribe(final String name, JSONArray param) { public Task<DDPSubscription.Ready> subscribe(final String name, JSONArray param) {
return mDDPClient.sub(UUID.randomUUID().toString(), name, param); return ddpClient.sub(UUID.randomUUID().toString(), name, param);
} }
/** /**
* Unsubscribe with DDP client. * Unsubscribe with DDP client.
*/ */
public Task<DDPSubscription.NoSub> unsubscribe(final String subscriptionId) { public Task<DDPSubscription.NoSub> unsubscribe(final String subscriptionId) {
return mDDPClient.unsub(subscriptionId); return ddpClient.unsub(subscriptionId);
} }
/** /**
* Returns Observable for handling DDP subscription. * Returns Observable for handling DDP subscription.
*/ */
public Observable<DDPSubscription.Event> getSubscriptionCallback() { public Observable<DDPSubscription.Event> getSubscriptionCallback() {
return mDDPClient.getSubscriptionCallback(); return ddpClient.getSubscriptionCallback();
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment