/** Destroys destination - should be executed when the app is uninstalled */
 public void destroyReceiver(final String uriStr) {
   try {
     final Destination dest = DestinationFactory.getReceiverDestination(URI.create(uriStr));
     if (dest != null) {
       dest.destroy();
     }
   } catch (final Exception e) {
     alertDialog(e.toString());
   }
 }
    /**
     * Sends get request and receives response using BlockingSenderDestination
     *
     * @see Thread#run()
     */
    public void run() {
      BlockingSenderDestination blockSendDest = null;
      try {
        blockSendDest =
            (BlockingSenderDestination)
                DestinationFactory.getSenderDestination(_context.getName(), URI.create(_uriStr));
        if (blockSendDest == null) {
          blockSendDest =
              DestinationFactory.createBlockingSenderDestination(_context, URI.create(_uriStr));
        }

        // Send message and wait for response
        _response = blockSendDest.sendReceive();

        if (_response != null) {
          _completed = true;

          // For "http"
          final String alertString =
              "received Message [id:"
                  + _response.getMessageId()
                  + "]\n"
                  + "Response Code: "
                  + ((HttpMessage) _response).getResponseCode();
          alertDialog(alertString);
        }
      } catch (final Exception e) {
        _completed = true;
        alertDialog(e.toString());
      } finally {
        if (blockSendDest != null) {
          blockSendDest.release();
        }
      }
    }
  /** Registers/subscribes the application for receiving BPS pushes */
  public void registerBPSPush(
      final String appId, final String BPDSUri, final String contentUri, final String listenUri) {
    NonBlockingReceiverDestination listenDest = null;
    NonBlockingSenderDestination bpsServerDest = null;
    try {
      final MessageListener bpsListener = new DestinationListener("BPS", true);

      final InboundDestinationConfiguration config1 =
          InboundDestinationConfigurationFactory.createBPSConfiguration(
              true, true, false, appId, BPDSUri); // serverUrl

      listenDest =
          DestinationFactory.createNonBlockingReceiverDestination(
              config1, URI.create(listenUri), bpsListener);
      final MessageListener subscriptionListener = new SubscriptionResponseListener("Subscription");
      bpsServerDest =
          DestinationFactory.createNonBlockingSenderDestination(
              _context, URI.create(contentUri), subscriptionListener);

      final ByteMessage subscrMsg =
          BpsSubscriptionMessageBuilder.createByteSubscriptionMessage(
              bpsServerDest, listenDest, "user", "pwd");

      ((HttpMessage) subscrMsg).setQueryParam("field1", "xxxxx");
      ((HttpMessage) subscrMsg).setQueryParam("osversion", "6.0");
      bpsServerDest.send(subscrMsg);
    } catch (final Exception e) {
      alertDialog(e.toString());
    }
  }
  /**
   * Creates non-blocking receiver destination (IPC) for the URI and registers a listener.
   *
   * @param uriStr
   * @param autoStartEnabled Auto-start application on incoming messages
   */
  public void startNonBlockingReceiverIPC(final String uriStr, final boolean autoStartEnabled) {
    NonBlockingReceiverDestination nonBlockRecvDest = null;

    try {
      nonBlockRecvDest =
          (NonBlockingReceiverDestination)
              DestinationFactory.getReceiverDestination(URI.create(uriStr));

      if (nonBlockRecvDest == null) // Not registered yet
      {
        final SimpleListener responseListener = new SimpleListener("NonBlockingReceiverIPC");

        // Prepare the inbound destination for incoming
        // messages (Inter Process Communication).
        final InboundDestinationConfiguration config =
            InboundDestinationConfigurationFactory.createIPCConfiguration(
                autoStartEnabled, true, false);

        nonBlockRecvDest =
            DestinationFactory.createNonBlockingReceiverDestination(
                config, URI.create(uriStr), null, responseListener);
      }
    } catch (final Exception e) {
      alertDialog(e.toString());
    }
  }
  /**
   * Creates receiver destination (BES) for the URI and registers a listener
   *
   * @param uriStr URI of the receiver destination
   * @param autoStartEnabled Auto start application on incoming messages
   */
  public void startNonBlockingReceiverBES(final String uriStr, final boolean autoStartEnabled) {
    NonBlockingReceiverDestination nonBlockRecvDest = null;
    try {
      nonBlockRecvDest =
          (NonBlockingReceiverDestination)
              DestinationFactory.getReceiverDestination(URI.create(uriStr));
      if (nonBlockRecvDest == null) // Not registered yet
      {
        final MessageListener responseListener =
            new DestinationListener("NonBlockingReceiverBES", true);

        // Prepare the in-bound destination for incoming messages
        // (BES/http)
        final InboundDestinationConfiguration config =
            InboundDestinationConfigurationFactory.createBESConfiguration(
                autoStartEnabled, true, false);

        nonBlockRecvDest =
            DestinationFactory.createNonBlockingReceiverDestination(
                config, URI.create(uriStr), responseListener);
      }
    } catch (final Exception e) {
      alertDialog(e.toString());
    }
  }
    /** @see Thread#run() */
    public void run() {
      BlockingReceiverDestination blockRecvDest = null;
      try {
        blockRecvDest =
            (BlockingReceiverDestination)
                DestinationFactory.getReceiverDestination(URI.create(_uriStr));

        if (blockRecvDest == null) // Not registered yet
        {
          InboundDestinationConfiguration config;

          // Prepare the inbound destination for incoming messages
          if (_configType == InboundDestinationConfiguration.CONFIG_TYPE_BES) {
            config =
                InboundDestinationConfigurationFactory.createBESConfiguration(
                    _autoStartEnabled, true, false);
          } else if (_configType == InboundDestinationConfiguration.CONFIG_TYPE_IPC) {
            config =
                InboundDestinationConfigurationFactory.createIPCConfiguration(
                    _autoStartEnabled, true, false);
          } else {
            throw new IllegalArgumentException(
                "Invalid InboundDestinationConfiguration type! Implemented support of IPC and BES only.");
          }

          blockRecvDest =
              DestinationFactory.createBlockingReceiverDestination(config, URI.create(_uriStr));
        }

        String alertString = "";
        _response = blockRecvDest.receive(_timeout * 1000);

        if (_response != null) {
          alertString = "RECEIVED[id: " + _response.getMessageId() + "]:";
          final String stringPayload = ((ByteMessage) _response).getStringPayload();
          if (stringPayload != null) {
            alertString += "\n" + stringPayload;
          }
        } else {
          // No response received
          alertString = "No message has been received during timeout of " + _timeout + " sec.";
        }

        alertDialog(alertString);
      } catch (final Exception e) {
        alertDialog(e.toString());
      }
    }
  /** Sets the destination. Used by message cancellation test. */
  public void setNonBlockingSenderDestination(final String uriStr) {
    final MessageListener responseListener = new DestinationListener("Cancellation Listener", true);

    try {
      final URI uri = URI.create(uriStr);
      SenderDestination destination =
          DestinationFactory.getSenderDestination(_context.getName(), uri);
      if (destination == null) {
        // Destination not registered yet
        destination =
            DestinationFactory.createNonBlockingSenderDestination(_context, uri, responseListener);
      }
      _cancellationDest = (NonBlockingSenderDestination) destination;

    } catch (final Exception e) {
      alertDialog(e.toString());
    }
  }
  /**
   * Sends message to the URI using FireAndForget destination
   *
   * @param uriSenderStr Sender destination URI
   */
  public void sendFireForget(final String uriSenderStr) {
    FireAndForgetDestination fireForgetDest = null;
    try {
      fireForgetDest =
          (FireAndForgetDestination)
              DestinationFactory.getSenderDestination(_context.getName(), URI.create(uriSenderStr));

      if (fireForgetDest == null) {
        fireForgetDest =
            DestinationFactory.createFireAndForgetDestination(_context, URI.create(uriSenderStr));
      }
      final int msgId = fireForgetDest.sendNoResponse();

      alertDialog("Message [id:" + msgId + "] has been sent!");
    } catch (final Exception e) {
      alertDialog(e.toString());
    }
  }
  /**
   * Sends get request message using non-blocking destination and listens for the response in the
   * created listener.
   *
   * @param uriStr Uri where the request is sent to
   * @param releaseDestination Release destination on completion of the method
   * @param callback Callback object responsible for updating UI upon message delivery / request
   *     timeout
   */
  public void sendNonBlocking(
      final String uriStr, final boolean releaseDestination, final ResponseCallback callback) {
    MonitoredDestinationListener responseListener;

    try {
      final URI uri = URI.create(uriStr);

      responseListener =
          new MonitoredDestinationListener(
              "SendNonBlocking MessageListener [id: " + _listenerId++ + "]");
      final SenderDestination senderDestination =
          DestinationFactory.createNonBlockingSenderDestination(_context, uri, responseListener);

      final TimeoutMonitor timeoutThread =
          new TimeoutMonitor(senderDestination, releaseDestination, callback, responseListener);
      final Thread t1 = new Thread(timeoutThread, "monitor");
      t1.start();

    } catch (final Exception e) {
      alertDialog(e.toString());
    }
  }
  /**
   * Uploads data in the form of streams to a server
   *
   * @param callback Callback object responsible for updating UI upon message delivery / request
   *     timeout
   */
  public void uploadStream(final String uploadUri, final ResponseCallback callback) {

    MonitoredDestinationListener responseListener;

    try {
      final URI uri = URI.create(uploadUri + ";deviceSide=true");

      responseListener =
          new MonitoredDestinationListener(
              "StreamData MessageListener [id: " + _listenerId++ + "]");
      final SenderDestination senderDestination =
          DestinationFactory.createNonBlockingSenderDestination(_context, uri, responseListener);

      // Create a byte array of size 10000
      final byte[] input = new byte[10000];
      for (int i = 0; i < input.length; i++) {
        input[i] = '5';
      }

      final ByteArrayInputStream bais = new ByteArrayInputStream(input);

      final StreamMessage message = senderDestination.createStreamMessage();
      ((HttpMessage) message).setMethod(HttpMessage.POST);

      message.setStreamPayload(bais);
      message.setPriority(2);
      message.setTransportHeader("Transfer-Encoding", "chunked");

      final TimeoutMonitor timeoutThread =
          new TimeoutMonitor(senderDestination, true, callback, responseListener, message);
      final Thread t1 = new Thread(timeoutThread, "monitor");

      t1.start();

    } catch (final Exception e) {
      alertDialog(e.toString());
    }
  }
  /**
   * Gets response from a URI which requires credentials
   *
   * @param callback Callback object responsible for updating UI upon message delivery / request
   *     timeout
   */
  public void authenticate(
      final String uriStr,
      final String username,
      final String password,
      final ResponseCallback callback) {
    MonitoredDestinationListener responseListener;

    try {
      final URI uri = URI.create(uriStr);
      final String user = username;
      final String pass = password;

      final CredentialsCollector credentialsCollector =
          new CredentialsCollector() {
            public UsernamePasswordCredentials getBasicAuthenticationCredentials(
                final String authenticatedEntityID, final Hashtable properties) {
              return new UsernamePasswordCredentials(user, pass);
            }
          };

      final Context context = new Context("Authenticate", credentialsCollector);

      responseListener =
          new MonitoredDestinationListener(
              "Authentification MessageListener [id: " + _listenerId++ + "]");
      final SenderDestination senderDestination =
          DestinationFactory.createNonBlockingSenderDestination(context, uri, responseListener);

      final TimeoutMonitor timeoutThread =
          new TimeoutMonitor(senderDestination, true, callback, responseListener);
      final Thread t1 = new Thread(timeoutThread, "monitor");
      t1.start();

    } catch (final Exception e) {
      alertDialog(e.toString());
    }
  }