/**********************************************************************************************
 * This example code is provided for illustrative purposes only and provided 'AS IS' without 
 * warranty of any kind.
 * 
 * Copyright ©2014 Chrysler Group LLC.  All Rights Reserved.  All information contained herein is,
 * and remains the property of Chrysler Group LLC and its suppliers, if any.  The intellectual and
 * technical concepts contained herein are proprietary to Chrysler Group LLC and its suppliers
 * and may be covered by U.S. and Foreign Patents, patents in process, and are protected by trade
 * secret or copyright law. Dissemination of this information or reproduction of this material is
 * strictly forbidden unless prior written permission is obtained from Chrysler Group LLC.
 *
 * Chrysler, Jeep, Dodge, Ram, SRT, Mopar and the Pentastar logo are registered trademarks of
 * Chrysler Group LLC. FIAT is a registered trademark of Fiat group Marketing & Corporate
 * Communication S.p.A. used under license by Chrysler Group LLC.
 *********************************************************************************************/
package com.fca.uconnect.global;

import com.amazonaws.services.iot.client.AWSIotException;
import com.amazonaws.services.iot.client.AWSIotMessage;
import com.amazonaws.services.iot.client.AWSIotMqttClient;
import com.amazonaws.services.iot.client.AWSIotQos;
import com.amazonaws.services.iot.client.AWSIotTopic;
import com.fca.uconnect.global.GlobalUconnectControl.UconnectAny;
import com.fca.uconnect.global.GlobalUconnectControl.UconnectMessage;
import com.fca.uconnect.global.GlobalUconnectExtAuth.LoginRequest;
import com.fca.uconnect.global.GlobalUconnectExtAuth.LoginResponse;
import com.google.protobuf.ByteString;
import com.google.protobuf.ExtensionRegistry;
import com.google.protobuf.InvalidProtocolBufferException;

/**
 * This example class demonstrates how to use the AWS IoT mqtt client to send a Uconnect Login/Logout message to the SDP and wait for a response message.   
 * This code is only for reference and is furnished without warranty.....
 * 
 * @author FCA Global V2C API Team
 *
 */
public class TBMExampleForAuthorization {

	private String clientId; // The clientId is unique to the device and obtained from the client X.509 certificate CN.
	private ByteString sessionId; // The sessionId is assigned by the SDP to maintain a session independent of connection protocols.
	private int messageId; // The messageId is a sequential number incremented and assigned to each message sent from the client.
	private AWSIotMqttClient mqttClient; // The mqtt client object from the AWS IoT client library. 
	private boolean receivedResponse = false; // flag to wait for the response as part of this example.
	private AWSIotTopic iotTopic; // The Topic object to subscribe for inbound messages.
	private ExtensionRegistry extRegistry; // Google protocol buffers extension registry instance.
	private Semaphore semaphore;//The semaphore object is used to wait for a response.
	/**
	 * Constructor - initialize protocol buffer extension registry for parsing incoming Uconnect Messages.
	 */
	public TBMExampleForAuthorization() {
		extRegistry = ExtensionRegistry.newInstance();
		extRegistry.add(GlobalUconnectExtAuth.loginResponse);
		this.semaphore = new Semaphore();
	}
	
	/**
	 * This method generates a Protocol Buffer Uconnect Message given the required inputs for Login.
	 * @param userId
	 * @param credentials
	 * @return
	 */
	public UconnectMessage getLoginReqMsg(String userId,String credentials) {
		this.messageId++;
	
		LoginRequest lr = LoginRequest.newBuilder()
				.setIdentifier(userId)
				.setCredentials(credentials)
				.build();
		UconnectMessage msg = UconnectMessage.newBuilder()
			.setTimestamp(System.currentTimeMillis())
			.setMessageId(messageId)
			.addMessages(UconnectAny.newBuilder().
			 setExtension(GlobalUconnectExtAuth.loginRequest, lr))
			.build();

		return msg;		
	}
	
	/**
	 * This method demonstrates connecting to the AWS IoT mqtt broker and publishing an Login message to the ULIO topic.
	 */
	public void process() {
		
		mqttClient = new AWSIotMqttClient("endpoint", clientId, "awsAccessKeyId", "awsSecretAccessKey");
		
		try {			
			mqttClient.connect();						
						
			iotTopic = new AWSIotTopic(clientId+"/ULIO/", AWSIotQos.QOS1) {
				public void onMessage(AWSIotMessage msg) {

					UconnectMessage msgIn = null;
					try {
						msgIn = UconnectMessage.parseFrom(msg.getPayload(),extRegistry);
					} catch (InvalidProtocolBufferException e) {					
					}
					if (msgIn.getMessages(0).hasExtension(GlobalUconnectExtAuth.loginResponse)) {
						LoginResponse loginMsg = msgIn.getMessages(0).getExtension(GlobalUconnectExtAuth.loginResponse);
						semaphore.unlock();// Releasing the lock as it received response
					}
				}	
			};
			mqttClient.subscribe(iotTopic);
			UconnectMessage msg = getLoginReqMsg("userId","password");

			AWSIotMessage message = new 
					MessagePublisherListener("/ULIO/"+clientId,AWSIotQos.QOS1,msg.toByteArray());
			mqttClient.publish(message);
			this.semaphore.lock();	//Wait for response, lock thread
			
		} catch (AWSIotException ex) {
			System.out.println("Caught AWS Exception "+ex);
			ex.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}	
	/**
	 * Example main to launch example.
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		TBMExampleForAuthorization example = new TBMExampleForAuthorization();
		example.process();
	}
}
      
      

Here's an example of how Service Connects to AWS IOT MQTT for Login/Logout topics and process Login Request , send Provision Push and Logout Request.

Service Example Code (SDP):

      
    package com.fca.uconnect.global;



import com.amazonaws.services.iot.client.AWSIotException;
import com.amazonaws.services.iot.client.AWSIotMessage;
import com.amazonaws.services.iot.client.AWSIotMqttClient;
import com.amazonaws.services.iot.client.AWSIotQos;
import com.amazonaws.services.iot.client.AWSIotTopic;
import com.fca.uconnect.global.GlobalUconnectControl.DRM;
import com.fca.uconnect.global.GlobalUconnectControl.UconnectAny;
import com.fca.uconnect.global.GlobalUconnectControl.UconnectMessage;
import com.fca.uconnect.global.GlobalUconnectExtAuth.LoginResponse;
import com.fca.uconnect.global.GlobalUconnectExtProvision.ProvisioningPush;
import com.google.protobuf.ByteString;
import com.google.protobuf.ExtensionRegistry;

public class SDPExampleForAuthorization {
private String clientId; // The clientId is unique to the device and obtained from the client X.509 certificate CN.
private ByteString sessionId; // The sessionId is assigned by the SDP to maintain a session independent of connection protocols.
private int messageId; // The messageId is a sequential number incremented and assigned to each message sent from the client.
private AWSIotMqttClient mqttClient; // The mqtt client object from the AWS IoT client library. 
private AWSIotTopic iotTopic; // The Topic object to subscribe for inbound messages.
private ExtensionRegistry extRegistry; // Google protocol buffers extension registry instance.  
private int correlationId = 0;// The correlationId is a sender messageId so that Sender can recognize the message once its received response.
private boolean messageReceived = false; // flag to wait for the message as part of this example.
 

public SDPExampleForAuthorization() {
	extRegistry = ExtensionRegistry.newInstance();
	extRegistry.add(GlobalUconnectExtAuth.loginRequest);
	extRegistry.add(GlobalUconnectExtAuth.loginResponse);
	extRegistry.add(GlobalUconnectExtProvision.provisioningPush);
}

public UconnectMessage getLoginRespMsg(int correlationId,boolean loginSuccessful) {
	messageId++;

	GlobalUconnectExtAuth.LoginResponse.ResponseEnum resp = null;  
	if(loginSuccessful)
	resp = GlobalUconnectExtAuth.LoginResponse.ResponseEnum.SUCCESS;
	else
		resp = GlobalUconnectExtAuth.LoginResponse.ResponseEnum.NOT_AUTHORIZED;
	LoginResponse loginResp = LoginResponse.newBuilder()
			.setResponse(resp)
			.build();
	sessionId = ByteString.copyFrom(new byte[18]);
	UconnectMessage msg = UconnectMessage.newBuilder()
		.setTimestamp(System.currentTimeMillis())
		.setSessionId(sessionId)
		.setMessageId(messageId)
		.setCorrelationId(correlationId)
		.addMessages(UconnectAny.newBuilder().
		 setExtension(GlobalUconnectExtAuth.loginResponse, loginResp))
		.build();

	return msg;		
}

public void process() {

mqttClient = new AWSIotMqttClient("endpoint", clientId, "awsAccessKeyId", "awsSecretAccessKey");
try {			
mqttClient.connect();						
 iotTopic = new AWSIotTopic("/ULIO/#",AWSIotQos.QOS1){
	public void onMessage(AWSIotMessage msg) {
try {
	
	UconnectMessage	msgIn = UconnectMessage.parseFrom(msg.getPayload(),extRegistry);								
	GlobalUconnectExtAuth.LoginRequest loginReqMsg = msgIn.getMessages(0).getExtension(GlobalUconnectExtAuth.loginRequest);
	if (loginReqMsg.getCredentials()!=null && loginReqMsg.getIdentifier().trim().length()>0) {
		correlationId=msgIn.getMessageId();
		sendMessage(getLoginRespMsg(correlationId,true));
		try {
			Thread.sleep(1000);//simulating a delay between the login response message and pushing an updated provisioning message to the vehicle.  The delay represents additional processing time to lookup the services for the use.
		} catch (InterruptedException e) {
		}
		sendMessage(getProvisionPushMsg( sessionId));
	}
	
} catch( Exception ex) {
	ex.printStackTrace();
	System.out.println("Err processing message: "+ex+", try parsing Login/Logout.");
}
}
};

mqttClient.subscribe(iotTopic);

} catch (AWSIotException e) {
	System.out.println("Caught Exception "+e);
	e.printStackTrace();
}

while(!messageReceived) {
 try {
        Thread.sleep(1000);
    } catch (InterruptedException e){
    }
	 
 }

}
public UconnectMessage getProvisionPushMsg(ByteString sessionId) {
	messageId++;
	ByteString drmFile = ByteString.copyFrom(new byte[18]);
	DRM drm = DRM.newBuilder()
			.setDrmFile(drmFile)
			.build();
		 ProvisioningPush provisioningPush = ProvisioningPush.newBuilder()
				 .setDrm(drm)
				 .build();
 

UconnectMessage msg = UconnectMessage.newBuilder()
		.setTimestamp(System.currentTimeMillis())
		.setMessageId(messageId)
		.addMessages(UconnectAny.newBuilder().
		setExtension(GlobalUconnectExtProvision.provisioningPush, provisioningPush))					
		.build();
	return msg;		
}
public void disconnect(){
	try {
		mqttClient.disconnect();
	} catch (AWSIotException e) {
		e.printStackTrace();
	}
}
public void sendMessage(UconnectMessage msg) {
final byte[] msgOut = msg.toByteArray();
new Thread(new Runnable() {

    @Override
public void run() {
try {						
	mqttClient.publish(clientId+"/ULIO/", AWSIotQos.QOS1, msgOut);	
} catch (AWSIotException e) {
	System.out.println("Caught Exception "+e);
				e.printStackTrace();
			}		    	
	    }
	    
	}).start();
}
public static void main(String[] args) {
	SDPExampleForAuthorization m = new SDPExampleForAuthorization();
	m.process();
}	
}
      
      

The example code demonstrates how to connect with AWS IoT for publishing and subscribing to the Login/Logout topic.

Download Client Example Code here

Download Service Example Code here