<commit_before>/*   Copyright (c) 2015 Magnet Systems, Inc.
 *
 *  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.
 */
package com.magnet.demo.mmx.starter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.magnet.mmx.client.api.MMXMessage;
import com.magnet.mmx.client.api.MMXUser;
import com.magnet.mmx.client.api.MagnetMessage;
import com.magnet.mmx.client.common.MMXid;

import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * This is the primary activity for this application.  It establishes a
 * connection to the MMX server, registers a global listener
 * <code>MyMMXListener</code> to receive incoming messages from this connection,
 * and shows received messages in a List view. The global listener
 * <code>MyMMXListener</code> extending from AbstractMMXListener automatically
 * dispatches the incoming messages to this activity registered as a local
 * listener.  It also saves the messages to an in-memory
 * <code>MyMessageStore</code> and posts a notification to the Status Bar in
 * case this activity is not available to show the incoming message.  Furthermore,
 * user can also send a message to self or one of the two bots from this
 * activity.
 */
public class MyActivity extends Activity {
  static final String QUICKSTART_USERNAME = "QuickstartUser1";
  static final byte[] QUICKSTART_PASSWORD = "<PASSWORD>".getBytes();
  static final String KEY_MESSAGE_TEXT = "textContent";

  private static final String TAG = MyActivity.class.getSimpleName();
  private static final String[] TO_LIST = {QUICKSTART_USERNAME, "amazing_bot", "echo_bot"};
  private TextView mStatus = null;
  private ImageButton mSendButton = null;
  private EditText mSendText = null;
  private ListView mMessageListView = null;
  private MessageListAdapter mMessageListAdapter = null;
  private String mToUsername = QUICKSTART_USERNAME;
  private AtomicBoolean mLoginSuccess = new AtomicBoolean(false);

  private MagnetMessage.OnMessageReceivedListener mMessageListener =
          new MagnetMessage.OnMessageReceivedListener() {
    public boolean onMessageReceived(MMXMessage mmxMessage) {
      updateViewState();
      return false;
    }
  };

  /**
   * On creating this activity, register this activity as a local listener to
   * the global listener, establish a connection to the MMX server and register
   * the global listener to the connection.
   * @see #onDestroy()
   */
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Register this activity as a listener to receive and show incoming
    // messages.  See #onDestroy for the unregister call.
    MagnetMessage.registerListener(mMessageListener);
    MMXUser.login(QUICKSTART_USERNAME, QUICKSTART_PASSWORD, new MagnetMessage.OnFinishedListener<Void>() {
      public void onSuccess(Void aVoid) {
        mLoginSuccess.set(true);
        updateViewState();
      }

      public void onFailure(MagnetMessage.FailureCode failureCode, Exception e) {
        mLoginSuccess.set(false);
        updateViewState();
      }
    });
    setContentView(R.layout.activity_my_activity);

    //Setup the views
    mStatus = (TextView) findViewById(R.id.status_field);
    mSendText = (EditText) findViewById(R.id.message_text);
    mSendButton = (ImageButton) findViewById(R.id.btn_send);
    mMessageListView = (ListView) findViewById(R.id.message_list_view);
    mMessageListAdapter = new MessageListAdapter(this, MyMessageStore.getMessageList(), QUICKSTART_USERNAME);
    mMessageListView.setAdapter(mMessageListAdapter);
    mSendText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
      public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (event != null
                && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                || actionId == EditorInfo.IME_ACTION_DONE) {
          doSendMessage(v);
        }
        return false;
      }
    });
    updateViewState();
  }

  /**
   * On destroying of this activity, unregister this activity as a listener
   * so it won't process any incoming messages.
   */
  @Override
  public void onDestroy() {
    MagnetMessage.unregisterListener(mMessageListener);
    super.onDestroy();
  }

  /**
   * On resuming of this activity, just update the view state.
   */
  @Override
  public void onResume() {
    updateViewState();
    super.onResume();
  }

  /**
   * This can be called from anywhere to make sure that the view is updated.
   */
  private void updateViewState() {
    runOnUiThread(new Runnable() {
      public void run() {
        if (mLoginSuccess.get()) {
          String username = MagnetMessage.getCurrentUser().getUserId();
          String status = getString(R.string.status_connected) +
                  (username != null ? " as " + username : " " + getString(R.string.user_anonymously));
          mStatus.setText(status);
          mSendButton.setEnabled(true);
        } else {
          mStatus.setText(R.string.status_disconnected);
          mSendButton.setEnabled(false);
        }

        List<MyMessageStore.Message> messageList = MyMessageStore.getMessageList();
        mMessageListAdapter.setMessageList(messageList);
        mMessageListView.smoothScrollToPosition(mMessageListAdapter.getCount());
      }
    });
  }

  private static class MessageListAdapter extends BaseAdapter {<commit_msg>Fixed a bug with an API that didn't get updated after getCurrentUser was moved to MMXUser.<commit_after>/*   Copyright (c) 2015 Magnet Systems, Inc.
 *
 *  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.
 */
package com.magnet.demo.mmx.starter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.magnet.mmx.client.api.MMXMessage;
import com.magnet.mmx.client.api.MMXUser;
import com.magnet.mmx.client.api.MagnetMessage;
import com.magnet.mmx.client.common.MMXid;

import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * This is the primary activity for this application.  It establishes a
 * connection to the MMX server, registers a global listener
 * <code>MyMMXListener</code> to receive incoming messages from this connection,
 * and shows received messages in a List view. The global listener
 * <code>MyMMXListener</code> extending from AbstractMMXListener automatically
 * dispatches the incoming messages to this activity registered as a local
 * listener.  It also saves the messages to an in-memory
 * <code>MyMessageStore</code> and posts a notification to the Status Bar in
 * case this activity is not available to show the incoming message.  Furthermore,
 * user can also send a message to self or one of the two bots from this
 * activity.
 */
public class MyActivity extends Activity {
  static final String QUICKSTART_USERNAME = "QuickstartUser1";
  static final byte[] QUICKSTART_PASSWORD = "<PASSWORD>".getBytes();
  static final String KEY_MESSAGE_TEXT = "textContent";

  private static final String TAG = MyActivity.class.getSimpleName();
  private static final String[] TO_LIST = {QUICKSTART_USERNAME, "amazing_bot", "echo_bot"};
  private TextView mStatus = null;
  private ImageButton mSendButton = null;
  private EditText mSendText = null;
  private ListView mMessageListView = null;
  private MessageListAdapter mMessageListAdapter = null;
  private String mToUsername = QUICKSTART_USERNAME;
  private AtomicBoolean mLoginSuccess = new AtomicBoolean(false);

  private MagnetMessage.OnMessageReceivedListener mMessageListener =
          new MagnetMessage.OnMessageReceivedListener() {
    public boolean onMessageReceived(MMXMessage mmxMessage) {
      updateViewState();
      return false;
    }
  };

  /**
   * On creating this activity, register this activity as a local listener to
   * the global listener, establish a connection to the MMX server and register
   * the global listener to the connection.
   * @see #onDestroy()
   */
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Register this activity as a listener to receive and show incoming
    // messages.  See #onDestroy for the unregister call.
    MagnetMessage.registerListener(mMessageListener);
    MMXUser.login(QUICKSTART_USERNAME, QUICKSTART_PASSWORD, new MagnetMessage.OnFinishedListener<Void>() {
      public void onSuccess(Void aVoid) {
        mLoginSuccess.set(true);
        updateViewState();
      }

      public void onFailure(MagnetMessage.FailureCode failureCode, Exception e) {
        mLoginSuccess.set(false);
        updateViewState();
      }
    });
    setContentView(R.layout.activity_my_activity);

    //Setup the views
    mStatus = (TextView) findViewById(R.id.status_field);
    mSendText = (EditText) findViewById(R.id.message_text);
    mSendButton = (ImageButton) findViewById(R.id.btn_send);
    mMessageListView = (ListView) findViewById(R.id.message_list_view);
    mMessageListAdapter = new MessageListAdapter(this, MyMessageStore.getMessageList(), QUICKSTART_USERNAME);
    mMessageListView.setAdapter(mMessageListAdapter);
    mSendText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
      public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (event != null
                && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                || actionId == EditorInfo.IME_ACTION_DONE) {
          doSendMessage(v);
        }
        return false;
      }
    });
    updateViewState();
  }

  /**
   * On destroying of this activity, unregister this activity as a listener
   * so it won't process any incoming messages.
   */
  @Override
  public void onDestroy() {
    MagnetMessage.unregisterListener(mMessageListener);
    super.onDestroy();
  }

  /**
   * On resuming of this activity, just update the view state.
   */
  @Override
  public void onResume() {
    updateViewState();
    super.onResume();
  }

  /**
   * This can be called from anywhere to make sure that the view is updated.
   */
  private void updateViewState() {
    runOnUiThread(new Runnable() {
      public void run() {
        if (mLoginSuccess.get()) {
          String username = MMXUser.getCurrentUser().getUsername();
          String status = getString(R.string.status_connected) +
                  (username != null ? " as " + username : " " + getString(R.string.user_anonymously));
          mStatus.setText(status);
          mSendButton.setEnabled(true);
        } else {
          mStatus.setText(R.string.status_disconnected);
          mSendButton.setEnabled(false);
        }

        List<MyMessageStore.Message> messageList = MyMessageStore.getMessageList();
        mMessageListAdapter.setMessageList(messageList);
        mMessageListView.smoothScrollToPosition(mMessageListAdapter.getCount());
      }
    });
  }

  private static class MessageListAdapter extends BaseAdapter {
{'fraction_non_alphanumeric': 0.08678471008435291, 'fraction_numerical': 0.0013678850976517973, 'mean_word_length': 3.797666788188115, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6441746', 'n_tokens_mistral': 3640, 'n_tokens_neox': 3565, 'n_words': 1075}