use of utils.commandlineutils.CommandLineUtils in project aws-iot-device-sdk-java-v2 by aws.
the class Pkcs11Connect method main.
public static void main(String[] args) {
cmdUtils = new CommandLineUtils();
cmdUtils.registerProgramName("Pkcs11PubSub");
cmdUtils.addCommonMQTTCommands();
cmdUtils.registerCommand("cert", "<path>", "Path to your client certificate in PEM format.");
cmdUtils.registerCommand("client_id", "<int>", "Client id to use (optional, default='test-*').");
cmdUtils.registerCommand("port", "<int>", "Port to connect to on the endpoint (optional, default='8883').");
cmdUtils.registerCommand("pkcs11_lib", "<path>", "Path to PKCS#11 library.");
cmdUtils.registerCommand("pin", "<int>", "User PIN for logging into PKCS#11 token.");
cmdUtils.registerCommand("token_label", "<str>", "Label of PKCS#11 token to use (optional).");
cmdUtils.registerCommand("slot_id", "<int>", "Slot ID containing PKCS#11 token to use (optional).");
cmdUtils.registerCommand("key_label", "<str>", "Label of private key on the PKCS#11 token (optional).");
cmdUtils.registerCommand("help", "", "Prints this message");
cmdUtils.sendArguments(args);
if (cmdUtils.hasCommand("help")) {
cmdUtils.printHelp();
System.exit(1);
}
String endpoint = cmdUtils.getCommandRequired("endpoint", "");
String certPath = cmdUtils.getCommandRequired("cert", "");
String CaPath = cmdUtils.getCommandOrDefault("ca_file", "");
String clientId = cmdUtils.getCommandOrDefault("client_id", "test-" + UUID.randomUUID().toString());
int port = Integer.parseInt(cmdUtils.getCommandOrDefault("port", "8883"));
String pkcs11LibPath = cmdUtils.getCommandRequired("pkcs11_lib", "");
String pkcs11UserPin = cmdUtils.getCommandRequired("pin", "");
String pkcs11TokenLabel = cmdUtils.getCommandOrDefault("key_label", "");
Long pkcs11SlotId = null;
if (cmdUtils.hasCommand("slot_id")) {
Long.parseLong(cmdUtils.getCommandOrDefault("slot_id", "-1"));
}
String pkcs11KeyLabel = cmdUtils.getCommandOrDefault("key_label", "");
MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() {
@Override
public void onConnectionInterrupted(int errorCode) {
if (errorCode != 0) {
System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode));
}
}
@Override
public void onConnectionResumed(boolean sessionPresent) {
System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session"));
}
};
// Load PKCS#11 library
try (Pkcs11Lib pkcs11Lib = new Pkcs11Lib(pkcs11LibPath);
TlsContextPkcs11Options pkcs11Options = new TlsContextPkcs11Options(pkcs11Lib)) {
pkcs11Options.withCertificateFilePath(certPath);
pkcs11Options.withUserPin(pkcs11UserPin);
if (pkcs11TokenLabel != null && pkcs11TokenLabel != "") {
pkcs11Options.withTokenLabel(pkcs11TokenLabel);
}
if (pkcs11SlotId != null) {
pkcs11Options.withSlotId(pkcs11SlotId);
}
if (pkcs11KeyLabel != null && pkcs11KeyLabel != "") {
pkcs11Options.withPrivateKeyObjectLabel(pkcs11KeyLabel);
}
try (AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsPkcs11Builder(pkcs11Options)) {
if (CaPath != null) {
builder.withCertificateAuthorityFromPath(null, CaPath);
}
builder.withConnectionEventCallbacks(callbacks).withClientId(clientId).withEndpoint(endpoint).withPort((short) port).withCleanSession(true).withProtocolOperationTimeoutMs(60000);
try (MqttClientConnection connection = builder.build()) {
CompletableFuture<Boolean> connected = connection.connect();
try {
boolean sessionPresent = connected.get();
System.out.println("Connected to " + (!sessionPresent ? "new" : "existing") + " session!");
} catch (Exception ex) {
throw new RuntimeException("Exception occurred during connect", ex);
}
System.out.println("Disconnecting...");
CompletableFuture<Void> disconnected = connection.disconnect();
disconnected.get();
System.out.println("Disconnected.");
}
} catch (CrtRuntimeException | InterruptedException | ExecutionException ex) {
onApplicationFailure(ex);
}
}
CrtResource.waitForNoResources();
System.out.println("Complete!");
}
use of utils.commandlineutils.CommandLineUtils in project aws-iot-device-sdk-java-v2 by aws.
the class RawConnect method main.
public static void main(String[] args) {
cmdUtils = new CommandLineUtils();
cmdUtils.registerProgramName("RawConnect");
cmdUtils.addCommonMQTTCommands();
cmdUtils.registerCommand("key", "<path>", "Path to your key in PEM format.");
cmdUtils.registerCommand("cert", "<path>", "Path to your client certificate in PEM format.");
cmdUtils.addCommonProxyCommands();
cmdUtils.registerCommand("client_id", "<int>", "Client id to use (optional, default='test-*').");
cmdUtils.registerCommand("username", "<str>", "Username to use as part of the connection/authentication process.");
cmdUtils.registerCommand("password", "<str>", "Password to use as part of the connection/authentication process.");
cmdUtils.registerCommand("protocol", "<str>", "ALPN protocol to use (optional, default='x-amzn-mqtt-ca').");
cmdUtils.registerCommand("auth_params", "<comma delimited list>", "Comma delimited list of auth parameters. For websockets these will be set as headers. " + "For raw mqtt these will be appended to user_name. (optional)");
cmdUtils.sendArguments(args);
String endpoint = cmdUtils.getCommandRequired("endpoint", "");
String clientId = cmdUtils.getCommandOrDefault("client_id", "test-" + UUID.randomUUID().toString());
String caPath = cmdUtils.getCommandOrDefault("ca_file", "");
String certPath = cmdUtils.getCommandRequired("cert", "");
String keyPath = cmdUtils.getCommandRequired("key", "");
String proxyHost = cmdUtils.getCommandOrDefault("proxy_host", "");
int proxyPort = Integer.parseInt(cmdUtils.getCommandOrDefault("proxy_port", "8080"));
String userName = cmdUtils.getCommandRequired("username", "");
String password = cmdUtils.getCommandRequired("password", "");
String protocolName = cmdUtils.getCommandOrDefault("protocol", "x-amzn-mqtt-ca");
List<String> authParams = null;
if (cmdUtils.hasCommand("auth_params")) {
authParams = Arrays.asList(cmdUtils.getCommand("auth_params").split("\\s*,\\s*"));
}
MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() {
@Override
public void onConnectionInterrupted(int errorCode) {
if (errorCode != 0) {
System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode));
}
}
@Override
public void onConnectionResumed(boolean sessionPresent) {
System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session"));
}
};
if (authParams != null && authParams.size() > 0) {
if (userName.length() > 0) {
StringBuilder usernameBuilder = new StringBuilder();
usernameBuilder.append(userName);
usernameBuilder.append("?");
for (int i = 0; i < authParams.size(); ++i) {
usernameBuilder.append(authParams.get(i));
if (i + 1 < authParams.size()) {
usernameBuilder.append("&");
}
}
userName = usernameBuilder.toString();
}
}
try (TlsContextOptions tlsContextOptions = TlsContextOptions.createWithMtlsFromPath(certPath, keyPath)) {
if (caPath != null) {
tlsContextOptions.overrideDefaultTrustStoreFromPath(null, caPath);
}
int port = 8883;
if (TlsContextOptions.isAlpnSupported()) {
port = 443;
tlsContextOptions.withAlpnList(protocolName);
}
try (TlsContext tlsContext = new TlsContext(tlsContextOptions);
MqttClient client = new MqttClient(tlsContext);
MqttConnectionConfig config = new MqttConnectionConfig()) {
config.setMqttClient(client);
config.setClientId(clientId);
config.setConnectionCallbacks(callbacks);
config.setCleanSession(true);
config.setEndpoint(endpoint);
config.setPort(port);
if (userName != null && userName.length() > 0) {
config.setLogin(userName, password);
}
try (MqttClientConnection connection = new MqttClientConnection(config)) {
// Connect and disconnect using the connection we created
// (see sampleConnectAndDisconnect for implementation)
cmdUtils.sampleConnectAndDisconnect(connection);
}
}
} catch (CrtRuntimeException | InterruptedException | ExecutionException ex) {
System.out.println("Exception encountered: " + ex.toString());
}
CrtResource.waitForNoResources();
System.out.println("Complete!");
}
use of utils.commandlineutils.CommandLineUtils in project aws-iot-device-sdk-java-v2 by aws.
the class ShadowSample method main.
public static void main(String[] args) {
cmdUtils = new CommandLineUtils();
cmdUtils.registerProgramName("ShadowSample");
cmdUtils.addCommonMQTTCommands();
cmdUtils.registerCommand("key", "<path>", "Path to your key in PEM format.");
cmdUtils.registerCommand("cert", "<path>", "Path to your client certificate in PEM format.");
cmdUtils.registerCommand("port", "<int>", "Port to use (optional, default='8883').");
cmdUtils.registerCommand("thing_name", "<str>", "The name of the IoT thing.");
cmdUtils.registerCommand("client_id", "<int>", "Client id to use (optional, default='test-*')");
cmdUtils.sendArguments(args);
thingName = cmdUtils.getCommandRequired("thing_name", "");
MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() {
@Override
public void onConnectionInterrupted(int errorCode) {
if (errorCode != 0) {
System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode));
}
}
@Override
public void onConnectionResumed(boolean sessionPresent) {
System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session"));
}
};
try {
MqttClientConnection connection = cmdUtils.buildMQTTConnection(callbacks);
shadow = new IotShadowClient(connection);
CompletableFuture<Boolean> connected = connection.connect();
try {
boolean sessionPresent = connected.get();
System.out.println("Connected to " + (!sessionPresent ? "clean" : "existing") + " session!");
} catch (Exception ex) {
throw new RuntimeException("Exception occurred during connect", ex);
}
System.out.println("Subscribing to shadow delta events...");
ShadowDeltaUpdatedSubscriptionRequest requestShadowDeltaUpdated = new ShadowDeltaUpdatedSubscriptionRequest();
requestShadowDeltaUpdated.thingName = thingName;
CompletableFuture<Integer> subscribedToDeltas = shadow.SubscribeToShadowDeltaUpdatedEvents(requestShadowDeltaUpdated, QualityOfService.AT_LEAST_ONCE, ShadowSample::onShadowDeltaUpdated);
subscribedToDeltas.get();
System.out.println("Subscribing to update respones...");
UpdateShadowSubscriptionRequest requestUpdateShadow = new UpdateShadowSubscriptionRequest();
requestUpdateShadow.thingName = thingName;
CompletableFuture<Integer> subscribedToUpdateAccepted = shadow.SubscribeToUpdateShadowAccepted(requestUpdateShadow, QualityOfService.AT_LEAST_ONCE, ShadowSample::onUpdateShadowAccepted);
CompletableFuture<Integer> subscribedToUpdateRejected = shadow.SubscribeToUpdateShadowRejected(requestUpdateShadow, QualityOfService.AT_LEAST_ONCE, ShadowSample::onUpdateShadowRejected);
subscribedToUpdateAccepted.get();
subscribedToUpdateRejected.get();
System.out.println("Subscribing to get responses...");
GetShadowSubscriptionRequest requestGetShadow = new GetShadowSubscriptionRequest();
requestGetShadow.thingName = thingName;
CompletableFuture<Integer> subscribedToGetShadowAccepted = shadow.SubscribeToGetShadowAccepted(requestGetShadow, QualityOfService.AT_LEAST_ONCE, ShadowSample::onGetShadowAccepted);
CompletableFuture<Integer> subscribedToGetShadowRejected = shadow.SubscribeToGetShadowRejected(requestGetShadow, QualityOfService.AT_LEAST_ONCE, ShadowSample::onGetShadowRejected);
subscribedToGetShadowAccepted.get();
subscribedToGetShadowRejected.get();
gotResponse = new CompletableFuture<>();
System.out.println("Requesting current shadow state...");
GetShadowRequest getShadowRequest = new GetShadowRequest();
getShadowRequest.thingName = thingName;
CompletableFuture<Integer> publishedGetShadow = shadow.PublishGetShadow(getShadowRequest, QualityOfService.AT_LEAST_ONCE);
publishedGetShadow.get();
gotResponse.get();
String newValue = "";
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print(SHADOW_PROPERTY + "> ");
System.out.flush();
newValue = scanner.next();
if (newValue.compareToIgnoreCase("quit") == 0) {
break;
}
gotResponse = new CompletableFuture<>();
changeShadowValue(newValue).get();
gotResponse.get();
}
scanner.close();
CompletableFuture<Void> disconnected = connection.disconnect();
disconnected.get();
} catch (CrtRuntimeException | InterruptedException | ExecutionException ex) {
System.out.println("Exception encountered: " + ex.toString());
}
System.out.println("Complete!");
CrtResource.waitForNoResources();
}
use of utils.commandlineutils.CommandLineUtils in project aws-iot-device-sdk-java-v2 by aws.
the class BasicConnect method main.
public static void main(String[] args) {
cmdUtils = new CommandLineUtils();
cmdUtils.registerProgramName("BasicConnect");
cmdUtils.addCommonMQTTCommands();
cmdUtils.addCommonProxyCommands();
cmdUtils.registerCommand("key", "<path>", "Path to your key in PEM format.");
cmdUtils.registerCommand("cert", "<path>", "Path to your client certificate in PEM format.");
cmdUtils.registerCommand("client_id", "<int>", "Client id to use (optional, default='test-*').");
cmdUtils.registerCommand("port", "<int>", "Port to connect to on the endpoint (optional, default='8883').");
cmdUtils.sendArguments(args);
MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() {
@Override
public void onConnectionInterrupted(int errorCode) {
if (errorCode != 0) {
System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode));
}
}
@Override
public void onConnectionResumed(boolean sessionPresent) {
System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session"));
}
};
try {
// Create a connection using a certificate and key
// Note: The data for the connection is gotten from cmdUtils.
// (see buildDirectMQTTConnection for implementation)
MqttClientConnection connection = cmdUtils.buildDirectMQTTConnection(callbacks);
if (connection == null) {
onApplicationFailure(new RuntimeException("MQTT connection creation failed!"));
}
// Connect and disconnect using the connection we created
// (see sampleConnectAndDisconnect for implementation)
cmdUtils.sampleConnectAndDisconnect(connection);
} catch (CrtRuntimeException | InterruptedException | ExecutionException ex) {
onApplicationFailure(ex);
}
CrtResource.waitForNoResources();
System.out.println("Complete!");
}
use of utils.commandlineutils.CommandLineUtils in project aws-iot-device-sdk-java-v2 by aws.
the class BasicDiscovery method main.
public static void main(String[] args) {
cmdUtils = new CommandLineUtils();
cmdUtils.registerProgramName("BasicDiscovery");
cmdUtils.addCommonMQTTCommands();
cmdUtils.removeCommand("endpoint");
cmdUtils.registerCommand("thing_name", "<str>", "The name of the IoT thing.");
cmdUtils.registerCommand("region", "<str>", "AWS IoT service region (optional, default='us-east-1').");
cmdUtils.registerCommand("topic", "<str>", "Topic to subscribe/publish to (optional, default='test/topic').");
cmdUtils.registerCommand("mode", "<str>", "Mode options: 'both', 'publish', or 'subscribe' (optional, default='both').");
cmdUtils.registerCommand("proxy_host", "<str>", "Websocket proxy host to use (optional, required if --proxy_port is set).");
cmdUtils.registerCommand("proxy_port", "<int>", "Websocket proxy port to use (optional, required if --proxy_host is set).");
cmdUtils.registerCommand("help", "", "Prints this message");
cmdUtils.sendArguments(args);
if (cmdUtils.hasCommand("help")) {
cmdUtils.printHelp();
System.exit(1);
}
thingName = cmdUtils.getCommandRequired("thing_name", "");
region = cmdUtils.getCommandOrDefault("region", region);
rootCaPath = cmdUtils.getCommandOrDefault("ca_file", rootCaPath);
certPath = cmdUtils.getCommandRequired("cert", "");
keyPath = cmdUtils.getCommandRequired("key", "");
topic = cmdUtils.getCommandOrDefault("topic", topic);
mode = cmdUtils.getCommandOrDefault("mode", mode);
proxyHost = cmdUtils.getCommandOrDefault("proxy_host", proxyHost);
proxyPort = Integer.parseInt(cmdUtils.getCommandOrDefault("proxy_port", String.valueOf(proxyPort)));
// ---- Verify file loads ----
// Get the absolute CA file path
final File rootCaFile = new File(rootCaPath);
if (!rootCaFile.isFile()) {
throw new RuntimeException("Cannot load root CA from path: " + rootCaFile.getAbsolutePath());
}
rootCaPath = rootCaFile.getAbsolutePath();
final File certFile = new File(certPath);
if (!certFile.isFile()) {
throw new RuntimeException("Cannot load certificate from path: " + certFile.getAbsolutePath());
}
certPath = certFile.getAbsolutePath();
final File keyFile = new File(keyPath);
if (!keyFile.isFile()) {
throw new RuntimeException("Cannot load private key from path: " + keyFile.getAbsolutePath());
}
keyPath = keyFile.getAbsolutePath();
try (final TlsContextOptions tlsCtxOptions = TlsContextOptions.createWithMtlsFromPath(certPath, keyPath)) {
if (TlsContextOptions.isAlpnSupported()) {
tlsCtxOptions.withAlpnList(TLS_EXT_ALPN);
}
if (rootCaPath != null) {
tlsCtxOptions.overrideDefaultTrustStoreFromPath(null, rootCaPath);
}
HttpProxyOptions proxyOptions = null;
if (proxyHost != null && proxyPort > 0) {
proxyOptions = new HttpProxyOptions();
proxyOptions.setHost(proxyHost);
proxyOptions.setPort(proxyPort);
}
try (final DiscoveryClientConfig discoveryClientConfig = new DiscoveryClientConfig(tlsCtxOptions, new SocketOptions(), region, 1, proxyOptions);
final DiscoveryClient discoveryClient = new DiscoveryClient(discoveryClientConfig);
final MqttClientConnection connection = getClientFromDiscovery(discoveryClient)) {
if ("subscribe".equals(mode) || "both".equals(mode)) {
final CompletableFuture<Integer> subFuture = connection.subscribe(topic, QualityOfService.AT_MOST_ONCE, message -> {
System.out.println(String.format("Message received on topic %s: %s", message.getTopic(), new String(message.getPayload(), StandardCharsets.UTF_8)));
});
subFuture.get();
}
final Scanner scanner = new Scanner(System.in);
while (true) {
String input = null;
if ("publish".equals(mode) || "both".equals(mode)) {
System.out.println("Enter the message you want to publish to topic " + topic + " and press Enter. " + "Type 'exit' or 'quit' to exit this program: ");
input = scanner.nextLine();
}
if ("exit".equals(input) || "quit".equals(input)) {
System.out.println("Terminating...");
break;
}
if ("publish".equals(mode) || "both".equals(mode)) {
final CompletableFuture<Integer> publishResult = connection.publish(new MqttMessage(topic, input.getBytes(StandardCharsets.UTF_8), QualityOfService.AT_MOST_ONCE, false));
Integer result = publishResult.get();
}
}
}
} catch (CrtRuntimeException | InterruptedException | ExecutionException ex) {
System.out.println("Exception thrown: " + ex.toString());
ex.printStackTrace();
}
CrtResource.waitForNoResources();
System.out.println("Complete!");
}
Aggregations