Skip to content

Commit

Permalink
Andyk/sample update with CommonsCLI (#1418)
Browse files Browse the repository at this point in the history
* standardize on command-line arguments (replace env variables)

* Updates based on PR feedbacks

* updated with TimeUnit and log based on feedback.

* update sample using commonsCli for command line argument processing

* update sample using commonsCli for command line argument processing

* updates from PR feedback

* updates from PR feedback #2

Co-authored-by: Andy Kwong <andykwong@microsoft.com>
  • Loading branch information
andyk-ms and Andy Kwong authored Nov 29, 2021
1 parent 1bdd832 commit e6145d4
Show file tree
Hide file tree
Showing 3 changed files with 225 additions and 55 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,6 @@
@Slf4j
public class DeviceClientManagerSample {

private static final String DEVICE_CONNECTION_STRING = System.getenv("IOTHUB_DEVICE_CONNECTION_STRING");
private static int NUM_REQUESTS = 3;
private static int SLEEP_DURATION_IN_SECONDS = 10;
private static int TIMEOUT_IN_MINUTES = 1;
private static String CMD_HELP = "\nUsage:\n"
+ "The program should be called with the following args:\n"
+ "1. [Device connection string]: (Required, default to environment variable \"IOTHUB_DEVICE_CONNECTION_STRING\")\n"
+ "2. [Transport protocol]: (default to \"mqtt\") Protocol choice [mqtt | https | amqps | amqps_ws | mqtt_ws]\n"
+ "3. [Number of requests]: (default to \"3\")\n"
+ "4. [Sleep duration in seconds]: (default to \"10\")\n"
+ "5. [Timeout in minutes]: (default to \"1\")\n"
+ "\n";
// Can be configured to use any protocol from HTTPS, AMQPS, MQTT, AMQPS_WS, MQTT_WS. Note: HTTPS does not support status callback, device methods and device twins.

final static List<String> failedMessageListOnClose = new ArrayList<>(); // List of messages that failed on close
private static DeviceClientManager deviceClientManager;

Expand All @@ -41,56 +27,43 @@ public class DeviceClientManagerSample {
public static void main(String[] args)
throws URISyntaxException, IOException {

log.info("Starting...");

String argDeviceConnectionString = (args.length >= 1) ? args[0] : DEVICE_CONNECTION_STRING;

if (argDeviceConnectionString == null && (args.length < 1 || args.length >=5) )
{
log.error("Expect arguments but received: {}\n" + CMD_HELP, args.length);
return;
}
SampleParameters params = new SampleParameters(args);

log.info("Starting...");
log.info("Setup parameters...");
log.debug("Setup parameter: Connection String from {}", (args.length >= 1) ? "command line" : "environment variable (\"IOTHUB_DEVICE_CONNECTION_STRING\")");

String argDeviceConnectionString = (params.getConnectionStrings())[0];

IotHubClientProtocol argProtocol;
if (args.length >= 2)
{
switch (args[1].toLowerCase())
{
case "https":
argProtocol = IotHubClientProtocol.HTTPS;
break;
case "amqps":
argProtocol = IotHubClientProtocol.AMQPS;
break;
case "amqps_ws":
argProtocol = IotHubClientProtocol.AMQPS_WS;
break;
case "mqtt":
argProtocol = IotHubClientProtocol.MQTT;
break;
case "mqtt_ws":
argProtocol = IotHubClientProtocol.MQTT_WS;
break;
default:
throw new IllegalArgumentException("[ERROR] Do not support protocol: [" + args[1] + "]");
}
}
else
String protocol = params.getTransport().toLowerCase();

switch (protocol)
{
argProtocol = IotHubClientProtocol.MQTT;
log.debug("Setup parameter: Did not specify protocol. Default transport protocol to [{}]", argProtocol.name());
log.debug(CMD_HELP);
case "https":
argProtocol = IotHubClientProtocol.HTTPS;
break;
case "amqps":
argProtocol = IotHubClientProtocol.AMQPS;
break;
case "amqps_ws":
argProtocol = IotHubClientProtocol.AMQPS_WS;
break;
case "mqtt":
argProtocol = IotHubClientProtocol.MQTT;
break;
case "mqtt_ws":
argProtocol = IotHubClientProtocol.MQTT_WS;
break;
default:
throw new IllegalArgumentException("Unsupported protocol: [" + protocol + "]");
}
log.debug("Setup parameter: Protocol = [{}]", argProtocol.name());
log.debug("Setup parameter: Protocol = [{}]", protocol);

int argNumRequest = (args.length > 2) ? Integer.parseInt(args[2]) : NUM_REQUESTS;
int argNumRequest = Integer.parseInt(params.getNumRequests());
log.debug("Setup parameter: Requests = [{}]", argNumRequest);
int argSleepDuration = (args.length > 3) ? Integer.parseInt(args[3]) : SLEEP_DURATION_IN_SECONDS;
int argSleepDuration = Integer.parseInt(params.getSleepDuration());
log.debug("Setup parameter: Sleep Duration = [{}]", argSleepDuration);
int argTimeout = (args.length > 4) ? Integer.parseInt(args[4]) : TIMEOUT_IN_MINUTES;
int argTimeout = Integer.parseInt(params.getTimeout());
log.debug("Setup parameter: Timeout = [{}]", argTimeout);

DeviceClient client = new DeviceClient(argDeviceConnectionString, argProtocol);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package samples.com.microsoft.azure.sdk.iot;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

import java.net.URISyntaxException;
import java.io.*;


public class SampleParameters {

private static final String DEVICE_CONNECTION_STRING = System.getenv("IOTHUB_DEVICE_CONNECTION_STRING");
private static final String TRANSPORT = "mqtt";
private static final String NUM_REQUESTS = "3";
private static final String SLEEP_DURATION_IN_SECONDS = "10";
private static final String TIMEOUT_IN_MINUTES = "1";

private static final String FOOTER = "\nFor more info, please refer to https://github.com/Azure/azure-iot-sdks";
private static final String APPEXE = "java -jar ";

private static CommandLine cmd = null;
private static String[] connections = new String[2];

/**
* Setup parameters from command line arguments
* @param string array from main()
*/
public SampleParameters(String[] args) {

//create options for cli
Options options = new Options()
.addOption(
Option.builder("h")
.longOpt("help")
.hasArg(false)
.desc("Prints this message")
.build()
)
.addOption(
Option.builder("p")
.longOpt("primaryConnectionString")
.hasArg()
.desc("Primary device connection string; required argument unless setup with environment variable \"IOTHUB_DEVICE_CONNECTION_STRING\"")
.build()
)
.addOption(
Option.builder("t")
.longOpt("transportProtocol")
.hasArg()
.desc("Transport protocol [mqtt | https | amqps| amqps_ws | mqtt_ws] (optional); defaults to \"mqtt\"")
.build()
)
.addOption(
Option.builder("r")
.longOpt("requests")
.hasArg()
.desc("Number of requests (optional); defaults to \"3\"")
.build()
)
.addOption(
Option.builder("d")
.longOpt("sleepDuration")
.hasArg()
.desc("Sleep duration between requests in seconds (optional); defaults to \"10\"")
.build()
)
.addOption(
Option.builder("o")
.longOpt("timeout")
.hasArg()
.desc("Timeout for each request in minutes (optional); defaults to \"1\"")
.build()
);

//Get command line string
String cmdLine = APPEXE;
try {
String jarPath = Options.class
.getProtectionDomain()
.getCodeSource()
.getLocation()
.toURI()
.getPath();
String jarName = jarPath.substring(jarPath.lastIndexOf("/") + 1);
cmdLine += jarName;
} catch (URISyntaxException e) {
e.printStackTrace();
cmdLine += "<sample.jar>";
}

//Parsing command line
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();

try {
//parse the command line arguments
cmd = parser.parse(options, args);

//Help option
if (cmd.hasOption("h"))
{
formatter.printHelp(cmdLine, "\nHelp:\n\n", options, FOOTER, true);
System.exit(0);
}

//Connection String, required unless there is environment variable
if (cmd.hasOption("p"))
{
connections[0] = cmd.getOptionValue("p");
if (connections[0] == null || connections[0].trim().isEmpty())
{
formatter.printHelp(cmdLine, "\nError: Connection is empty\n\n", options, FOOTER, true);
System.exit(0);
}
}
else
{
connections[0] = DEVICE_CONNECTION_STRING;
if (connections[0] == null || connections[0].trim().isEmpty())
{
formatter.printHelp(cmdLine, "\nError: Connection is required as argument or as environment variable\n\n", options, FOOTER, true);
System.exit(0);
}
}

//Connection String (secondary), optional
if (cmd.hasOption("s"))
{
connections[1] = cmd.getOptionValue("s");
}

} catch (ParseException e) {
//wrong parameters
formatter.printHelp(cmdLine, "\nError: "+e.getMessage()+"\n\n", options, FOOTER, true);

System.exit(0);
}
}

/**
* get connection string argument from command line
* @return string array of 2 (primary and secondary)
*/
public String[] getConnectionStrings()
{
return connections;
}

/**
* get transport argument from command line
* @return string value
*/
public String getTransport()
{
return cmd.getOptionValue("t", TRANSPORT);
}

/**
* get number of requests argument from command line
* @return string value
*/
public String getNumRequests()
{
return cmd.getOptionValue("r", NUM_REQUESTS);
}

/**
* get sleep duration between requests argument from command line
* @return string value (seconds)
*/
public String getSleepDuration()
{
return cmd.getOptionValue("d", SLEEP_DURATION_IN_SECONDS);
}

/**
* get timeout argument from command line
* @return string value (minutes)
*/
public String getTimeout()
{
return cmd.getOptionValue("o", TIMEOUT_IN_MINUTES);
}

}
5 changes: 5 additions & 0 deletions device/iot-device-samples/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.29</version>
</dependency>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.5.0</version>
</dependency>
</dependencies>
<build>
<plugins>
Expand Down

0 comments on commit e6145d4

Please sign in to comment.