Example usage for com.amazonaws.services.iot.model AttachPrincipalPolicyRequest setPrincipal

List of usage examples for com.amazonaws.services.iot.model AttachPrincipalPolicyRequest setPrincipal

Introduction

In this page you can find the example usage for com.amazonaws.services.iot.model AttachPrincipalPolicyRequest setPrincipal.

Prototype


public void setPrincipal(String principal) 

Source Link

Document

The principal, which can be a certificate ARN (as returned from the CreateCertificate operation) or an Amazon Cognito ID.

Usage

From source file:com.zorba.bt.app.AwsIotActivity.java

License:Open Source License

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mtdebug);/*ww  w.  ja  v a  2s.co m*/

    txtSubcribe = (EditText) findViewById(R.id.txtSubcribe);
    txtMessage = (EditText) findViewById(R.id.txtMessage);

    Bundle bundle = this.getIntent().getExtras();
    String deviceName = bundle.getString("deviceName");
    //deviceName = "88:4A:EA:2E:1D:7B";
    txtSubcribe.setText(deviceName);
    tvLastMessage = (TextView) findViewById(R.id.tvLastMessage);
    tvClientId = (TextView) findViewById(R.id.tvClientId);
    tvStatus = (TextView) findViewById(R.id.tvStatus);

    btnConnect = (Button) findViewById(R.id.btnConnect);
    btnConnect.setOnClickListener(connectClick);
    btnConnect.setEnabled(false);

    btnPublish = (Button) findViewById(R.id.btnPublish);
    btnPublish.setOnClickListener(publishClick);

    btnDisconnect = (Button) findViewById(R.id.btnDisconnect);
    btnDisconnect.setOnClickListener(disconnectClick);

    // MQTT client IDs are required to be unique per AWS IoT account.
    // This UUID is "practically unique" but does not _guarantee_
    // uniqueness.
    clientId = UUID.randomUUID().toString();
    tvClientId.setText(clientId);

    // Initialize the AWS Cognito credentials provider
    credentialsProvider = new CognitoCachingCredentialsProvider(getApplicationContext(), // context
            AwsConnection.COGNITO_POOL_ID, // Identity Pool ID
            AwsConnection.MY_REGION // Region
    );

    Region region = Region.getRegion(AwsConnection.MY_REGION);

    // MQTT Client
    mqttManager = new AWSIotMqttManager(clientId, AwsConnection.CUSTOMER_SPECIFIC_ENDPOINT);

    // Set keepalive to 10 seconds.  Will recognize disconnects more quickly but will also send
    // MQTT pings every 10 seconds.
    mqttManager.setKeepAlive(10);

    // Set Last Will and Testament for MQTT.  On an unclean disconnect (loss of connection)
    // AWS IoT will publish this message to alert other clients.
    AWSIotMqttLastWillAndTestament lwt = new AWSIotMqttLastWillAndTestament("my/lwt/topic",
            "Android client lost connection", AWSIotMqttQos.QOS0);
    mqttManager.setMqttLastWillAndTestament(lwt);

    // IoT Client (for creation of certificate if needed)
    mIotAndroidClient = new AWSIotClient(credentialsProvider);
    mIotAndroidClient.setRegion(region);

    keystorePath = getFilesDir().getPath();
    keystoreName = AwsConnection.KEYSTORE_NAME;
    keystorePassword = AwsConnection.KEYSTORE_PASSWORD;
    certificateId = AwsConnection.CERTIFICATE_ID;

    // To load cert/key from keystore on filesystem
    try {
        if (AWSIotKeystoreHelper.isKeystorePresent(keystorePath, keystoreName)) {
            if (AWSIotKeystoreHelper.keystoreContainsAlias(certificateId, keystorePath, keystoreName,
                    keystorePassword)) {
                Log.i(LOG_TAG, "Certificate " + certificateId + " found in keystore - using for MQTT.");
                // load keystore from file into memory to pass on connection
                clientKeyStore = AWSIotKeystoreHelper.getIotKeystore(certificateId, keystorePath, keystoreName,
                        keystorePassword);
                btnConnect.setEnabled(true);
            } else {
                Log.i(LOG_TAG, "Key/cert " + certificateId + " not found in keystore.");
            }
        } else {
            Log.i(LOG_TAG, "Keystore " + keystorePath + "/" + keystoreName + " not found.");
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "An error occurred retrieving cert/key from keystore.", e);
    }

    if (clientKeyStore == null) {
        Log.i(LOG_TAG, "Cert/key was not found in keystore - creating new key and certificate.");

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // Create a new private key and certificate. This call
                    // creates both on the server and returns them to the
                    // device.
                    CreateKeysAndCertificateRequest createKeysAndCertificateRequest = new CreateKeysAndCertificateRequest();
                    createKeysAndCertificateRequest.setSetAsActive(true);
                    final CreateKeysAndCertificateResult createKeysAndCertificateResult;
                    createKeysAndCertificateResult = mIotAndroidClient
                            .createKeysAndCertificate(createKeysAndCertificateRequest);
                    Log.i(LOG_TAG,
                            "Cert ID: " + createKeysAndCertificateResult.getCertificateId() + " created.");

                    // store in keystore for use in MQTT client
                    // saved as alias "default" so a new certificate isn't
                    // generated each run of this application
                    AWSIotKeystoreHelper.saveCertificateAndPrivateKey(certificateId,
                            createKeysAndCertificateResult.getCertificatePem(),
                            createKeysAndCertificateResult.getKeyPair().getPrivateKey(), keystorePath,
                            keystoreName, keystorePassword);

                    // load keystore from file into memory to pass on
                    // connection
                    clientKeyStore = AWSIotKeystoreHelper.getIotKeystore(certificateId, keystorePath,
                            keystoreName, keystorePassword);

                    // Attach a policy to the newly created certificate.
                    // This flow assumes the policy was already created in
                    // AWS IoT and we are now just attaching it to the
                    // certificate.
                    AttachPrincipalPolicyRequest policyAttachRequest = new AttachPrincipalPolicyRequest();
                    policyAttachRequest.setPolicyName(AwsConnection.AWS_IOT_POLICY_NAME);
                    policyAttachRequest.setPrincipal(createKeysAndCertificateResult.getCertificateArn());
                    mIotAndroidClient.attachPrincipalPolicy(policyAttachRequest);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            btnConnect.setEnabled(true);
                        }
                    });
                } catch (Exception e) {
                    Log.e(LOG_TAG, "Exception occurred when generating new private key and certificate.", e);
                }
            }
        }).start();
    }
}