Java SDK quick start
Prepare for the quick start
First, obtain a Clearblade IoT Core account and credentials. Use the ClearBlade IoT Core or the ClearBlade IoT Core sandbox console for the quick start exercise.
Create a ClearBlade IoT Core account. Open the ClearBlade IoT Core sign-up page. Provide account information during sign-up. When the sign-up process is complete, the ClearBlade IoT Core console opens. If you already have a ClearBlade IoT Core account, sign in. You can explore the ClearBlade IoT Core APIs using the console and begin developing. Go to Migration from Google IoT Core or Creating registries and devices to migrate or create at least one device registry.
Generate RSA public/private key pairs using OpenSSL command-line tools:
private key: openssl genpkey -algorithm RSA -out rsa_private.pem -pkeyopt rsa_keygen_bits:2048
public key: openssl rsa -in rsa_private.pem -pubout -out rsa_public.pemCreate a device. Upload the RSA public key generated in step 2 for the RSA option in the ClearBlade IoT Core console for creating a device. This can be found by expanding the COMMUNICATION, LOGGING, AUTHENTICATION link, selecting the Upload radio button under Authentication, and browsing the RSA public key file.
Install the following: Java Development Kit. ClearBlade supports Java version 11 or later. Apache Maven for dependency management.
Create a project
Open a new terminal window. Use the Maven command-line interface (mvn) to create a simple project.
CODEmvn archetype:generate \ -DinteractiveMode=false \ -DgroupId=com.clearblade.examples \ -DartifactId=quickstart \ -DarchetypeArtifactId=maven-archetype-quickstart
After the command completes, go to your new project directory.
CODEcd ./quickstart
Familiarize yourself with the directory structure and supporting files.
Your project is defined by its project object model (POM). Open the pom.xml file in a text editor and replace its entire content with this:
CODE<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.clearblade.examples</groupId> <artifactId>quickstart</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>quickstart</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>io.github.clearblade</groupId> <artifactId>clearblade-cloud-iot</artifactId> <version>SDK_VERSION_HERE</version> <scope>compile</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>3.0.0</version> <configuration> <mainClass>com.clearblade.examples.Quickstart</mainClass> <cleanupDaemonThreads>false</cleanupDaemonThreads> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>8</source> <target>8</target> </configuration> </plugin> </plugins> </build> </project>
Replace SDK_VERSION_HERE with the latest version of the ClearBlade IoT Core Java SDK:
<version>1.0.3</version>
When finished, save the pom.xml file.
Write code
In your project's src/main/java/com/clearblade/examples subdirectory, create a new file named Quickstart.java with the following content from among a, b, and c:
Create a device: Async
CODEpackage com.clearblade.examples; import java.util.ArrayList; import java.util.HashMap; import java.util.Properties; import com.clearblade.cloud.iot.v1.DeviceManagerAsyncClient; import com.clearblade.cloud.iot.v1.createdevice.CreateDeviceRequest; import com.clearblade.cloud.iot.v1.devicetypes.Device; import com.clearblade.cloud.iot.v1.devicetypes.DeviceConfig; import com.clearblade.cloud.iot.v1.devicetypes.GatewayConfig; import com.clearblade.cloud.iot.v1.devicetypes.GatewayType; import com.clearblade.cloud.iot.v1.devicetypes.Status; import com.clearblade.cloud.iot.v1.registrytypes.RegistryName; import com.clearblade.cloud.iot.v1.utils.ConfigParameters; import com.clearblade.cloud.iot.v1.utils.LogLevel; public class Quickstart { public static String PROJECT = ""; public static String LOCATION = ""; public static String REGISTRY = ""; public static String DEVICE = ""; static ConfigParameters configParameters = ConfigParameters.getInstance(); public static void main(String[] args) { Properties systemProperties = System.getProperties(); systemProperties.put("projectName", "your-project-id"); systemProperties.put("location", "your-region"); systemProperties.put("registryName", "your first registry for switching"); //systemProperties.put("registryName", "your second registry for switching"); systemProperties.put("deviceName", "your-device-id"); System.setProperties(systemProperties); PROJECT = System.getProperty("projectName"); LOCATION = System.getProperty("location"); REGISTRY = System.getProperty("registryName"); DEVICE = System.getProperty("deviceName"); if(REGISTRY != null) { configParameters.setRegistry(REGISTRY); } if(LOCATION != null) { configParameters.setRegion(LOCATION); } asyncCreateDevice(); } public static void asyncCreateDevice() { DeviceManagerAsyncClient deviceManagerAsyncClient = new DeviceManagerAsyncClient(); RegistryName parent = RegistryName.of(PROJECT, LOCATION, REGISTRY); GatewayConfig gatewayCfg = new GatewayConfig(); gatewayCfg.setGatewayType(GatewayType.NON_GATEWAY); Device device = Device.newBuilder() .setId(DEVICE).setName(DEVICE) .setGatewayConfig(gatewayCfg) .setLogLevel(LogLevel.ERROR) .setCredentials(new ArrayList<>()) .setLastErrorStatus(new Status()) .setConfig(new DeviceConfig()) .setMetadata(new HashMap<>()) .build(); CreateDeviceRequest request = CreateDeviceRequest.Builder.newBuilder().setParent(parent).setDevice(device) .build(); Device response = deviceManagerAsyncClient.createDevice(request); if(response != null) { System.out.println("CreateDevice execution successful"); }else { System.out.println("CreateDevice execution failed"); } } }
Create a device: Sync
CODEpackage com.clearblade.examples; import java.util.ArrayList; import java.util.HashMap; import java.util.Properties; import com.clearblade.cloud.iot.v1.DeviceManagerClient; import com.clearblade.cloud.iot.v1.createdevice.CreateDeviceRequest; import com.clearblade.cloud.iot.v1.devicetypes.Device; import com.clearblade.cloud.iot.v1.devicetypes.DeviceConfig; import com.clearblade.cloud.iot.v1.devicetypes.GatewayConfig; import com.clearblade.cloud.iot.v1.devicetypes.GatewayType; import com.clearblade.cloud.iot.v1.devicetypes.Status; import com.clearblade.cloud.iot.v1.registrytypes.RegistryName; import com.clearblade.cloud.iot.v1.utils.ConfigParameters; import com.clearblade.cloud.iot.v1.utils.LogLevel; public class Quickstart { public static String PROJECT = ""; public static String LOCATION = ""; public static String REGISTRY = ""; public static String DEVICE = ""; public static String NUMID = ""; static ConfigParameters configParameters = ConfigParameters.getInstance(); public static void main(String[] args) { Properties systemProperties = System.getProperties(); systemProperties.put("projectName", "your-project-id"); systemProperties.put("location", "your-region"); systemProperties.put("registryName", "your first registry for switching"); // systemProperties.put("registryName", "your second registry for switching"); systemProperties.put("deviceName", "your-device-id"); System.setProperties(systemProperties); PROJECT = System.getProperty("projectName"); LOCATION = System.getProperty("location"); REGISTRY = System.getProperty("registryName"); DEVICE = System.getProperty("deviceName"); if (REGISTRY != null) { configParameters.setRegistry(REGISTRY); } if (LOCATION != null) { configParameters.setRegion(LOCATION); } syncCreateDevice(); } public static void syncCreateDevice() { DeviceManagerClient deviceManagerClient = new DeviceManagerClient(); RegistryName parent = RegistryName.of(PROJECT, LOCATION, REGISTRY); GatewayConfig gatewayCfg = new GatewayConfig(); gatewayCfg.setGatewayType(GatewayType.NON_GATEWAY); Device device = Device.newBuilder() .setId(DEVICE).setName(DEVICE) .setGatewayConfig(gatewayCfg) .setLogLevel(LogLevel.DEBUG) .setCredentials(new ArrayList<>()) .setLastErrorStatus(new Status()) .setConfig(new DeviceConfig()) .setMetadata(new HashMap<>()) .build(); CreateDeviceRequest request = CreateDeviceRequest.Builder.newBuilder().setParent(parent).setDevice(device) .build(); Device response = deviceManagerClient.createDevice(request); if (response != null) { System.out.println("CreateDevice execution successful"); } else { System.out.println("CreateDevice execution failed"); } } }
Send a command to a device
CODEpackage com.clearblade.examples; import com.clearblade.cloud.iot.v1.DeviceManagerAsyncClient; import com.clearblade.cloud.iot.v1.devicetypes.DeviceName; import com.clearblade.cloud.iot.v1.sendcommandtodevice.SendCommandToDeviceRequest; import com.clearblade.cloud.iot.v1.sendcommandtodevice.SendCommandToDeviceResponse; import com.clearblade.cloud.iot.v1.utils.ByteString; import com.clearblade.cloud.iot.v1.utils.ConfigParameters; public class Quickstart { public static String PROJECT = ""; public static String LOCATION = ""; public static String REGISTRY = ""; public static String DEVICE = ""; public static String BINARYDATA = ""; public static String SUBFOLDER = ""; static ConfigParameters configParameters = ConfigParameters.getInstance(); public static void main(String[] args) { PROJECT = System.getProperty("projectName"); LOCATION = System.getProperty("location"); REGISTRY = System.getProperty("registryName"); DEVICE = System.getProperty("deviceName"); BINARYDATA = System.getProperty("binaryData"); SUBFOLDER = System.getProperty("subFolder"); if (REGISTRY != null) { configParameters.setRegistry(REGISTRY); } if (LOCATION != null) { configParameters.setRegion(LOCATION); } asyncSendCommandToDevice(); } public static void asyncSendCommandToDevice() { DeviceManagerAsyncClient deviceManagerAsyncClient = new DeviceManagerAsyncClient(); SendCommandToDeviceRequest request = SendCommandToDeviceRequest.Builder.newBuilder() .setName(DeviceName.of(PROJECT, LOCATION, REGISTRY, DEVICE).toString()) .setBinaryData(new ByteString(BINARYDATA)).setSubfolder(SUBFOLDER).build(); try { SendCommandToDeviceResponse response = deviceManagerAsyncClient.sendCommandToDevice(request); if (response != null) { System.out.println("SendCommandToDevice execution successful"); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }
Save the Quickstart.java file.
Set your ClearBlade credentials
The Java SDK reads your ClearBlade credentials from a separate configuration file. This avoids hardcoded credentials. Do the following:
Add service accounts to a project and download the JSON file with your service account's credentials.
Use the following to set your terminal’s environment variables keys:
CODEexport CLEARBLADE_CONFIGURATION=/path/to/file.json
Optional (parameters can also be set within the application).
CODEexport CLEARBLADE_REGISTRY=[your-registry] export CLEARBLADE_REGION=[your-region]
Optional
CODEexport BINARYDATA_AND_TIME_GOOGLE_FORMAT=true
Replace
/path/to/file.json
with your JSON file path and press enter.
Run the application
Ensure your Java version is 11 or later.
CODEjava -version
Run this command:
CODEmvn package -DskipTests
Maven compiles your program into bytecode and prepares it for execution.
Run this command:
CODEmvn exec:java -Dexec.mainClass="com.clearblade.examples.Quickstart"
Verify the result.