use of utils.commandlineutils.CommandLineUtils in project aws-iot-device-sdk-java-v2 by aws.
the class FleetProvisioningSample method main.
public static void main(String[] args) {
cmdUtils = new CommandLineUtils();
cmdUtils.registerProgramName("FleetProvisioningSample");
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("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("template_name", "<str>", "Provisioning template name.");
cmdUtils.registerCommand("template_parameters", "<json>", "Provisioning template parameters.");
cmdUtils.registerCommand("csr", "<path>", "Path to the CSR file (optional).");
cmdUtils.sendArguments(args);
templateName = cmdUtils.getCommandRequired("template_name", "");
templateParameters = cmdUtils.getCommandRequired("template_parameters", "");
csrPath = cmdUtils.getCommandOrDefault("csr", csrPath);
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);
iotIdentityClient = new IotIdentityClient(connection);
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);
}
try {
if (csrPath == null) {
createKeysAndCertificateWorkflow();
} else {
createCertificateFromCsrWorkflow();
}
} catch (Exception e) {
throw new RuntimeException("Exception occurred during connect", e);
}
CompletableFuture<Void> disconnected = connection.disconnect();
disconnected.get();
} 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 JobsSample method main.
public static void main(String[] args) {
cmdUtils = new CommandLineUtils();
cmdUtils.registerProgramName("JobsSample");
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("client_id", "<int>", "Client id to use (optional, default='test-*').");
cmdUtils.registerCommand("thing_name", "<str>", "The name of the IoT thing.");
cmdUtils.registerCommand("port", "<int>", "Port to connect to on the endpoint (optional, default='8883').");
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);
IotJobsClient jobs = new IotJobsClient(connection);
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);
}
{
gotResponse = new CompletableFuture<>();
GetPendingJobExecutionsSubscriptionRequest subscriptionRequest = new GetPendingJobExecutionsSubscriptionRequest();
subscriptionRequest.thingName = thingName;
CompletableFuture<Integer> subscribed = jobs.SubscribeToGetPendingJobExecutionsAccepted(subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobsSample::onGetPendingJobExecutionsAccepted);
try {
subscribed.get();
System.out.println("Subscribed to GetPendingJobExecutionsAccepted");
} catch (Exception ex) {
throw new RuntimeException("Failed to subscribe to GetPendingJobExecutions", ex);
}
subscribed = jobs.SubscribeToGetPendingJobExecutionsRejected(subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobsSample::onRejectedError);
subscribed.get();
System.out.println("Subscribed to GetPendingJobExecutionsRejected");
GetPendingJobExecutionsRequest publishRequest = new GetPendingJobExecutionsRequest();
publishRequest.thingName = thingName;
CompletableFuture<Integer> published = jobs.PublishGetPendingJobExecutions(publishRequest, QualityOfService.AT_LEAST_ONCE);
try {
published.get();
gotResponse.get();
} catch (Exception ex) {
throw new RuntimeException("Exception occurred during publish", ex);
}
}
if (availableJobs.isEmpty()) {
System.out.println("No jobs queued, no further work to do");
}
for (String jobId : availableJobs) {
gotResponse = new CompletableFuture<>();
DescribeJobExecutionSubscriptionRequest subscriptionRequest = new DescribeJobExecutionSubscriptionRequest();
subscriptionRequest.thingName = thingName;
subscriptionRequest.jobId = jobId;
jobs.SubscribeToDescribeJobExecutionAccepted(subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobsSample::onDescribeJobExecutionAccepted);
jobs.SubscribeToDescribeJobExecutionRejected(subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobsSample::onRejectedError);
DescribeJobExecutionRequest publishRequest = new DescribeJobExecutionRequest();
publishRequest.thingName = thingName;
publishRequest.jobId = jobId;
publishRequest.includeJobDocument = true;
publishRequest.executionNumber = 1L;
jobs.PublishDescribeJobExecution(publishRequest, QualityOfService.AT_LEAST_ONCE);
gotResponse.get();
}
for (int jobIdx = 0; jobIdx < availableJobs.size(); ++jobIdx) {
{
gotResponse = new CompletableFuture<>();
// Start the next pending job
StartNextPendingJobExecutionSubscriptionRequest subscriptionRequest = new StartNextPendingJobExecutionSubscriptionRequest();
subscriptionRequest.thingName = thingName;
jobs.SubscribeToStartNextPendingJobExecutionAccepted(subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobsSample::onStartNextPendingJobExecutionAccepted);
jobs.SubscribeToStartNextPendingJobExecutionRejected(subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobsSample::onRejectedError);
StartNextPendingJobExecutionRequest publishRequest = new StartNextPendingJobExecutionRequest();
publishRequest.thingName = thingName;
publishRequest.stepTimeoutInMinutes = 15L;
jobs.PublishStartNextPendingJobExecution(publishRequest, QualityOfService.AT_LEAST_ONCE);
gotResponse.get();
}
{
// Update the service to let it know we're executing
gotResponse = new CompletableFuture<>();
UpdateJobExecutionSubscriptionRequest subscriptionRequest = new UpdateJobExecutionSubscriptionRequest();
subscriptionRequest.thingName = thingName;
subscriptionRequest.jobId = currentJobId;
jobs.SubscribeToUpdateJobExecutionAccepted(subscriptionRequest, QualityOfService.AT_LEAST_ONCE, (response) -> {
System.out.println("Marked job " + currentJobId + " IN_PROGRESS");
gotResponse.complete(null);
});
jobs.SubscribeToUpdateJobExecutionRejected(subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobsSample::onRejectedError);
UpdateJobExecutionRequest publishRequest = new UpdateJobExecutionRequest();
publishRequest.thingName = thingName;
publishRequest.jobId = currentJobId;
publishRequest.executionNumber = currentExecutionNumber;
publishRequest.status = JobStatus.IN_PROGRESS;
publishRequest.expectedVersion = currentVersionNumber++;
jobs.PublishUpdateJobExecution(publishRequest, QualityOfService.AT_LEAST_ONCE);
gotResponse.get();
}
// Fake doing something
Thread.sleep(1000);
{
// Update the service to let it know we're done
gotResponse = new CompletableFuture<>();
UpdateJobExecutionSubscriptionRequest subscriptionRequest = new UpdateJobExecutionSubscriptionRequest();
subscriptionRequest.thingName = thingName;
subscriptionRequest.jobId = currentJobId;
jobs.SubscribeToUpdateJobExecutionAccepted(subscriptionRequest, QualityOfService.AT_LEAST_ONCE, (response) -> {
System.out.println("Marked job " + currentJobId + " SUCCEEDED");
gotResponse.complete(null);
});
jobs.SubscribeToUpdateJobExecutionRejected(subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobsSample::onRejectedError);
UpdateJobExecutionRequest publishRequest = new UpdateJobExecutionRequest();
publishRequest.thingName = thingName;
publishRequest.jobId = currentJobId;
publishRequest.executionNumber = currentExecutionNumber;
publishRequest.status = JobStatus.SUCCEEDED;
publishRequest.expectedVersion = currentVersionNumber++;
jobs.PublishUpdateJobExecution(publishRequest, QualityOfService.AT_LEAST_ONCE);
gotResponse.get();
}
}
CompletableFuture<Void> disconnected = connection.disconnect();
disconnected.get();
} 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 PubSubStress method main.
public static void main(String[] args) {
cmdUtils = new CommandLineUtils();
cmdUtils.registerProgramName("PubSubStress");
cmdUtils.addCommonMQTTCommands();
cmdUtils.addCommonTopicMessageCommands();
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("count", "<int>", "Number of messages to publish (optional, default='10').");
cmdUtils.registerCommand("connections", "<int>", "Number of connections to make (optional, default='1000').");
cmdUtils.registerCommand("threads", "<int>", "Number of IO threads to use (optional, default='1').");
cmdUtils.registerCommand("iterations", "<int>", "Number of times to repeat the basic stress test logic (optional, default='1').");
cmdUtils.registerCommand("signing_region", "<str>", "Use websockets (optional). Sets the Websocket signing region to use (default='us-east-1').");
cmdUtils.registerCommand("proxy_host", "<str>", "Websocket proxy host to use (optional, required for websockets).");
cmdUtils.registerCommand("proxy_port", "<int>", "Websocket proxy port to use (optional, required for websockets).");
cmdUtils.sendArguments(args);
topic = cmdUtils.getCommandOrDefault("topic", topic);
message = cmdUtils.getCommandOrDefault("message", message);
messagesToPublish = Integer.parseInt(cmdUtils.getCommandOrDefault("count", String.valueOf(messagesToPublish)));
connectionCount = Integer.parseInt(cmdUtils.getCommandOrDefault("connections", String.valueOf(connectionCount)));
eventLoopThreadCount = Integer.parseInt(cmdUtils.getCommandOrDefault("threads", String.valueOf(eventLoopThreadCount)));
testIterations = Integer.parseInt(cmdUtils.getCommandOrDefault("iterations", String.valueOf(testIterations)));
int iteration = 0;
while (iteration < testIterations) {
System.out.println(String.format("Starting iteration %d", iteration));
try {
try {
initConnections();
Log.log(Log.LogLevel.Info, Log.LogSubject.MqttGeneral, "START OF PUBLISH......");
Random rng = new Random(0);
List<CompletableFuture<Integer>> publishFutures = new ArrayList<>();
for (int count = 0; count < messagesToPublish; ++count) {
String messageContent = String.format("%s #%d", message, count + 1);
// Pick a random connection to publish from
String connectionId = validClientIds.get(Math.abs(rng.nextInt()) % validClientIds.size());
MqttClientConnection connection = connections.get(connectionId);
// Pick a random subscribed topic to publish to
String publishTopic = validTopics.get(Math.abs(rng.nextInt()) % validTopics.size());
try {
publishFutures.add(connection.publish(new MqttMessage(publishTopic, messageContent.getBytes(), QualityOfService.AT_LEAST_ONCE, false)));
} catch (Exception e) {
System.out.println(String.format("Publishing Exception: %s", e.getMessage()));
}
if (count % PROGRESS_OP_COUNT == 0) {
System.out.println(String.format("(Main Thread) Message publish count: %d", count));
}
}
for (CompletableFuture<Integer> publishFuture : publishFutures) {
publishFuture.get();
}
System.out.println("zzzzz");
Thread.sleep(1000);
} catch (Exception e) {
System.out.println(String.format("Exception: %s", e.getMessage()));
} finally {
cleanupConnections();
}
} catch (Exception e) {
System.out.println("Exception encountered: " + e.toString());
}
System.out.println("Complete! Waiting on managed cleanup");
CrtResource.waitForNoResources();
System.out.println("Managed cleanup complete");
/* Not particularly effective, but psychologically reassuring to do before checking memory */
for (int i = 0; i < 10; ++i) {
System.gc();
}
long nativeMemoryInUse = CRT.nativeMemory();
System.out.println(String.format("Native memory: %d", nativeMemoryInUse));
long javaMemoryInUse = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
System.out.println(String.format("Java memory: %d", javaMemoryInUse));
iteration++;
validClientIds.clear();
validTopics.clear();
}
}
use of utils.commandlineutils.CommandLineUtils in project aws-iot-device-sdk-java-v2 by aws.
the class WebsocketConnect method main.
public static void main(String[] args) {
cmdUtils = new CommandLineUtils();
cmdUtils.registerProgramName("WebsocketConnect");
cmdUtils.addCommonMQTTCommands();
cmdUtils.addCommonProxyCommands();
cmdUtils.registerCommand("signing_region", "<str>", "AWS IoT service region.");
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.buildWebsocketMQTTConnection(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 WindowsCertConnect method main.
public static void main(String[] args) {
cmdUtils = new CommandLineUtils();
cmdUtils.registerProgramName("WindowsCertConnect");
cmdUtils.addCommonMQTTCommands();
cmdUtils.registerCommand("cert", "<str>", "Path to certificate in Windows cert store. " + "e.g. \"CurrentUser\\MY\\6ac133ac58f0a88b83e9c794eba156a98da39b4c\"");
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("help", "", "Prints this message");
cmdUtils.sendArguments(args);
String endpoint = cmdUtils.getCommandRequired("endpoint", "");
String windowsCertStorePath = cmdUtils.getCommandRequired("cert", "");
String rootCaPath = cmdUtils.getCommandOrDefault("ca_file", "");
String clientId = cmdUtils.getCommandOrDefault("client_id", "test-" + UUID.randomUUID().toString());
int port = Integer.parseInt(cmdUtils.getCommandOrDefault("port", "8883"));
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 (AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsWindowsCertStorePathBuilder(windowsCertStorePath)) {
if (rootCaPath != null && rootCaPath != "") {
builder.withCertificateAuthorityFromPath(null, rootCaPath);
}
builder.withConnectionEventCallbacks(callbacks).withClientId(clientId).withEndpoint(endpoint).withPort((short) port).withCleanSession(true).withProtocolOperationTimeoutMs(60000);
try (MqttClientConnection connection = builder.build()) {
// 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!");
}
Aggregations