Example usage for com.amazonaws.services.iot.model CreateKeysAndCertificateResult getCertificateId

List of usage examples for com.amazonaws.services.iot.model CreateKeysAndCertificateResult getCertificateId

Introduction

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

Prototype


public String getCertificateId() 

Source Link

Document

The ID of the certificate.

Usage

From source file:com.erudika.para.iot.AWSIoTService.java

License:Apache License

@Override
public Thing createThing(Thing thing) {
    if (thing == null || StringUtils.isBlank(thing.getName()) || StringUtils.isBlank(thing.getAppid())
            || existsThing(thing)) {/*from   ww  w.java2s .  c  o  m*/
        return null;
    }
    thing.setId(Utils.getNewId());
    String id = cloudIDForThing(thing);
    String appid = thing.getAppid();

    // STEP 1: Create thing
    CreateThingResult resp1 = getClient().createThing(new CreateThingRequest().withThingName(id)
            .withAttributePayload(new AttributePayload().addAttributesEntry(Config._APPID, appid)));

    // STEP 2: Create certificate
    CreateKeysAndCertificateResult resp2 = getClient()
            .createKeysAndCertificate(new CreateKeysAndCertificateRequest().withSetAsActive(true));

    String accountId = getAccountIdFromARN(resp1.getThingArn());
    String policyString = (String) (thing.getDeviceMetadata().containsKey("policyJSON")
            ? thing.getDeviceMetadata().get("policyJSON")
            : getDefaultPolicyDocument(accountId, id));

    // STEP 3: Create policy
    getClient().createPolicy(
            new CreatePolicyRequest().withPolicyDocument(policyString).withPolicyName(id + "-Policy"));

    // STEP 4: Attach policy to certificate
    getClient().attachPrincipalPolicy(new AttachPrincipalPolicyRequest()
            .withPrincipal(resp2.getCertificateArn()).withPolicyName(id + "-Policy"));

    // STEP 5: Attach thing to certificate
    getClient().attachThingPrincipal(
            new AttachThingPrincipalRequest().withPrincipal(resp2.getCertificateArn()).withThingName(id));

    thing.getDeviceMetadata().remove("policyJSON");

    thing.setServiceBroker("AWS");
    thing.getDeviceMetadata().put("thingId", thing.getId());
    thing.getDeviceMetadata().put("thingName", id);
    thing.getDeviceMetadata().put("thingARN", resp1.getThingArn());
    thing.getDeviceMetadata().put("clientId", id);
    thing.getDeviceMetadata().put("clientCertId", resp2.getCertificateId());
    thing.getDeviceMetadata().put("clientCertARN", resp2.getCertificateArn());
    thing.getDeviceMetadata().put("clientCert", resp2.getCertificatePem());
    thing.getDeviceMetadata().put("privateKey", resp2.getKeyPair().getPrivateKey());
    thing.getDeviceMetadata().put("publicKey", resp2.getKeyPair().getPublicKey());
    thing.getDeviceMetadata().put("region", Config.AWS_REGION);
    thing.getDeviceMetadata().put("port", 8883);
    thing.getDeviceMetadata().put("host",
            getClient().describeEndpoint(new DescribeEndpointRequest()).getEndpointAddress());

    return thing;
}

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);/* w  w  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();
    }
}