/** Deletes the connection, disconnecting if required. */
    private void delete() {
      connection = arrayAdapter.getItem(selected);
      if (connection.isConnectedOrConnecting()) {

        // display a dialog
        AlertDialog.Builder builder = new AlertDialog.Builder(clientConnections);
        builder
            .setTitle(R.string.disconnectClient)
            .setMessage(getString(R.string.deleteDialog))
            .setNegativeButton(
                R.string.cancelBtn,
                new OnClickListener() {

                  @Override
                  public void onClick(DialogInterface arg0, int arg1) {
                    // do nothing user cancelled action
                  }
                })
            .setPositiveButton(R.string.continueBtn, this)
            .show();
      } else {
        arrayAdapter.remove(connection);
        Connections.getInstance(clientConnections).removeConnection(connection);
      }
    }
  /** @see ListActivity#onDestroy() */
  @Override
  protected void onDestroy() {

    Map<String, Connection> connections = Connections.getInstance(this).getConnections();

    for (String s : connections.keySet()) {
      connections.get(s).removeChangeListener(changeListener);
    }
    super.onDestroy();
  }
 @Override
 public void onClick(DialogInterface dialog, int which) {
   // user pressed continue disconnect client and delete
   try {
     connection.getClient().disconnect();
   } catch (MqttException e) {
     e.printStackTrace();
   }
   arrayAdapter.remove(connection);
   Connections.getInstance(clientConnections).removeConnection(connection);
 }
  /** @see android.app.ListActivity#onCreate(Bundle) */
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ListView connectionList = getListView();
    connectionList.setOnItemLongClickListener(new LongClickItemListener());
    connectionList.setTextFilterEnabled(true);
    arrayAdapter = new ArrayAdapter<Connection>(this, R.layout.connection_text_view);
    setListAdapter(arrayAdapter);

    // get all the available connections
    Map<String, Connection> connections = Connections.getInstance(this).getConnections();

    if (connections != null) {
      for (String s : connections.keySet()) {
        arrayAdapter.add(connections.get(s));
      }
    }
  }
  /**
   * Process data from the connect action
   *
   * @param data the {@link Bundle} returned by the {@link NewConnection} Acitivty
   */
  private void connectAction(Bundle data) {
    MqttConnectOptions conOpt = new MqttConnectOptions();
    /*
     * Mutal Auth connections could do something like this
     *
     *
     * SSLContext context = SSLContext.getDefault();
     * context.init({new CustomX509KeyManager()},null,null); //where CustomX509KeyManager proxies calls to keychain api
     * SSLSocketFactory factory = context.getSSLSocketFactory();
     *
     * MqttConnectOptions options = new MqttConnectOptions();
     * options.setSocketFactory(factory);
     *
     * client.connect(options);
     *
     */

    //    public Properties getSSLSettings() {
    //        final Properties properties = new Properties();
    //        properties.setProperty("com.ibm.ssl.keyStore",
    //            "C:/BKSKeystore/mqttclientkeystore.keystore");
    //        properties.setProperty("com.ibm.ssl.keyStoreType", "BKS");
    //        properties.setProperty("com.ibm.ssl.keyStorePassword", "passphrase");
    //        properties.setProperty("com.ibm.ssl.trustStore",
    //            "C:/BKSKeystore/mqttclienttrust.keystore");
    //        properties.setProperty("com.ibm.ssl.trustStoreType", "BKS");
    //        properties.setProperty("com.ibm.ssl.trustStorePassword", "passphrase ");
    //
    //        return properties;
    //    }

    try {

      SSLContext context;
      KeyStore ts = KeyStore.getInstance("BKS");
      ts.load(getResources().openRawResource(R.raw.test), "123456".toCharArray());
      TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
      tmf.init(ts);
      TrustManager[] tm = tmf.getTrustManagers();
      context = SSLContext.getInstance("TLS");
      context.init(null, tm, null);

      // SocketFactory factory= SSLSocketFactory.getDefault();
      // Socket socket =factory.createSocket("localhost", 10000);
      SocketFactory factory = context.getSocketFactory();
      conOpt.setSocketFactory(factory);

    } catch (Exception e) {
      // TODO: handle exception
    }

    // The basic client information
    String server = (String) data.get(ActivityConstants.server);
    String clientId = (String) data.get(ActivityConstants.clientId);
    int port = Integer.parseInt((String) data.get(ActivityConstants.port));
    boolean cleanSession = (Boolean) data.get(ActivityConstants.cleanSession);

    boolean ssl = (Boolean) data.get(ActivityConstants.ssl);
    String uri = null;
    if (ssl) {
      Log.e("SSLConnection", "Doing an SSL Connect");
      uri = "ssl://";

    } else {
      uri = "tcp://";
    }

    uri = uri + server + ":" + port;

    MqttClientAndroidService client;
    client = Connections.getInstance(this).createClient(this, uri, clientId);
    // create a client handle
    String clientHandle = uri + clientId;

    // last will message
    String message = (String) data.get(ActivityConstants.message);
    String topic = (String) data.get(ActivityConstants.topic);
    Integer qos = (Integer) data.get(ActivityConstants.qos);
    Boolean retained = (Boolean) data.get(ActivityConstants.retained);

    // connection options

    String username = (String) data.get(ActivityConstants.username);

    String password = (String) data.get(ActivityConstants.password);

    int timeout = (Integer) data.get(ActivityConstants.timeout);
    int keepalive = (Integer) data.get(ActivityConstants.keepalive);

    Connection connection = new Connection(clientHandle, clientId, server, port, this, client, ssl);
    arrayAdapter.add(connection);

    connection.registerChangeListener(changeListener);
    // connect client

    String[] actionArgs = new String[1];
    actionArgs[0] = clientId;
    connection.changeConnectionStatus(ConnectionStatus.CONNECTING);

    conOpt.setCleanSession(cleanSession);
    conOpt.setConnectionTimeout(timeout);
    conOpt.setKeepAliveInterval(keepalive);
    if (!username.equals(ActivityConstants.empty)) {
      conOpt.setUserName(username);
    }
    if (!password.equals(ActivityConstants.empty)) {
      conOpt.setPassword(password.toCharArray());
    }

    final ActionListener callback =
        new ActionListener(this, ActionListener.Action.CONNECT, clientHandle, actionArgs);

    boolean doConnect = true;

    if ((!message.equals(ActivityConstants.empty)) || (!topic.equals(ActivityConstants.empty))) {
      // need to make a message since last will is set
      try {
        conOpt.setWill(topic, message.getBytes(), qos.intValue(), retained.booleanValue());
      } catch (Exception e) {
        doConnect = false;
        callback.onFailure(null, e);
      }
    }
    client.setCallback(new MqttCallbackHandler(this, clientHandle));
    connection.addConnectionOptions(conOpt);
    Connections.getInstance(this).addConnection(connection);
    if (doConnect) {
      try {
        client.connect(conOpt, null, callback);
      } catch (MqttException e) {
        Log.e(this.getClass().getCanonicalName(), "MqttException Occured", e);
      }
    }
  }