Bosch IoT Insights

Java

You can download the following code examples as cloud-examples-java.zip and import them to your development IDE.

Make sure to set your username and password as well as the appropriate proxy and the desired Bosch IoT Insights project before running the applications.

This examples requires some external java libraries:

For the basic authentication, use the credentials of the API user. To create an API user, refer to Creating an API user or Creating an API user via API.

We recommend you to use preemptive authentication. That way, the basic authentication request is sent before the server returns an unauthorized response. Also refer to the Apache documentation.

Sending data

The following Java code example shows you how to send data to the Data Recorder Service of the Bosch IoT Insights backend using Java code.

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.Base64;
 
public class DataRecorderServiceExample {
public static void main( String[] args ) throws UnsupportedEncodingException {
 
final String proxyHost = "rb-proxy-de.bosch.com";
final String proxyPort = "8080";
//If you are inside your company network, proxy authentication may be required. Otherwise, you can remove this from the example. This is an example for a Bosch internal proxy.
 
String resourceUrl = "https://bosch-iot-insights.com/data-recorder-service/v2/";
String insightsProject = "demo";
 
String username = "your_username";
String password = "your_password";
String authorizationCredentials = generateAuthorizationToken( username, password );
 
String contentType = "text/plain";
String payload = "Hello World";
 
System.setProperty( "https.proxyHost", proxyHost );
System.setProperty( "https.proxyPort", proxyPort );
 
WebResource service = Client.create().resource( resourceUrl + insightsProject );
ClientResponse response = service.header( "Authorization", authorizationCredentials ).header( "Content-Type", contentType )
.post( ClientResponse.class, payload );
 
System.out.println( response );
}
 
private static String generateAuthorizationToken( String username, String password )
throws UnsupportedEncodingException {
 
return "Basic " + new String( Base64.encode( username + ":" + password ), StandardCharsets.UTF_8 );
}
}

Synchronous query execution

This code example shows you how to execute a MongoDB aggregation query against a demo collection.

In this example the aggregation query is sourced out to the separate file queryParametersSync.json which is read by the main program in MongoDBQueryServiceSyncExample.java.

Please note that a synchronous call returns the query result immediately and might lead to HTTP timeouts if the query takes too long.

queryParametersSync.json

{
"collection": "demo_processed_data",
"query": [
{"$limit":1}
]
}

MongoDBQueryServiceSyncExample.java

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
 
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.Base64;
 
public class MongoDBQueryServiceSyncExample {
 
public static void main( String[] args ) throws IOException {
final String proxyHost = "rb-proxy-de.bosch.com";
final String proxyPort = "8080";
//If you are inside your company network, proxy authentication may be required. Otherwise, you can remove this from the example. This is an example for a Bosch internal proxy.
 
String insightsProject = "demo";
String resourceUrl = "https://bosch-iot-insights.com/mongodb-query-service/v2/" + insightsProject + "/execute-aggregation-query";
 
String username = "your_username";
String password = "your_password";
String authorizationCredentials = generateAuthorizationToken( username, password );
 
String contentType = "application/json";
String payload = new String( Files.readAllBytes( Paths.get( "src/main/resources/queryParametersSync.json" ) ) );
 
System.setProperty( "https.proxyHost", proxyHost );
System.setProperty( "https.proxyPort", proxyPort );
 
WebResource service = Client.create().resource( resourceUrl );
ClientResponse response = service.header( "Authorization", authorizationCredentials )
.header( "Content-Type", contentType )
.post( ClientResponse.class, payload );
 
System.out.println( response );
 
if ( response.getStatus() == 200 ) {
System.out.println( parseJson( response.getEntity( String.class ) ) );
}
}
 
private static String generateAuthorizationToken( String username, String password )
throws UnsupportedEncodingException {
 
return "Basic " + new String( Base64.encode( username + ":" + password ), StandardCharsets.UTF_8 );
}
 
private static String parseJson( String plainString ) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement json = new JsonParser().parse( plainString );
return gson.toJson( json );
}
}

Asynchronous query execution

The following example shows the entire sequence of an asynchronous MongoDB aggregation query execution.

Please note that an asynchronous call returns the query result not immediately. You have to poll the status of the query until it changes to SUCCESSFUL. Then you can fetch the results.

The status of the query must be polled within a certain interval. Otherwise, the status of the query request will be changed to EXPIRED.

In this example, the aggregation query is sourced out to the separate file queryParametersAsync.json which is read by the main program in MongoDBQueryServiceAsyncExample.java.

queryParametersAsync.json

{
"collection": "demo_processed_data",
"query": [
{"$limit":10}
]
}

MongoDBQueryServiceAsyncExample.java

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
 
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.Base64;
 
public class MongoDBQueryServiceAsyncExample {
 
public static void main( String[] args ) throws IOException {
final String proxyHost = "rb-proxy-de.bosch.com";
final String proxyPort = "8080";
//If you are inside your company network, proxy authentication may be required. Otherwise, you can remove this from the example. This is an example for a Bosch internal proxy.
 
String insightsProject = "demo";
String resourceUrl = "https://bosch-iot-insights.com/mongodb-query-service/v2/" + insightsProject;
 
String username = "your_username";
String password = "your_password";
String authorizationCredentials = generateAuthorizationToken( username, password );
 
String contentType = "application/json";
String payload = new String( Files.readAllBytes( Paths.get( "src/main/resources/queryParametersAsync.json" ) ) );
 
System.setProperty( "https.proxyHost", proxyHost );
System.setProperty( "https.proxyPort", proxyPort );
 
ClientResponse response = httpRequestPost( resourceUrl + "/submit-aggregation-query", authorizationCredentials, contentType, payload );
 
System.out.println( response );
 
if ( response.getStatus() == 200 ) {
Boolean queryError = false;
String responseContent = response.getEntity( String.class );
 
JsonObject json = new Gson().fromJson( responseContent, JsonObject.class );
String requestId = json.get( "queryId" ).getAsString();
String queryStatus = json.get( "status" ).getAsString();
 
System.out.println( "Status: " + queryStatus );
 
while ( !queryStatus.equals( "SUCCESSFUL" ) ) {
InputStream responseStream = httpRequestGet( resourceUrl + "/queries" + "/" + requestId, authorizationCredentials,
contentType );
Reader reader = new InputStreamReader( responseStream );
JsonObject jsonRes2 = new Gson().fromJson( reader, JsonObject.class );
queryStatus = jsonRes2.get( "status" ).getAsString();
System.out.println( "Status: " + queryStatus );
 
if ( queryStatus.equals( "FAILED" ) || queryStatus.equals( "INCORRECT" ) ) {
queryError = true;
break;
}
}
 
if ( !queryError ) {
InputStream responseStream = httpRequestGet( resourceUrl + "/queries" + "/" + requestId + "/result",
authorizationCredentials,
contentType );
System.out.println( "Status: LOADING DATA..." );
Path path = Paths.get( System.getProperty( "user.home" ) + "/queryResponse.txt" );
Files.copy( responseStream, path, StandardCopyOption.REPLACE_EXISTING );
System.out.println( "Status: DONE" );
System.out.println( "Response data was saved at " + path );
}
}
}
 
private static ClientResponse httpRequestPost( String url, String auth, String cType, String payload ) {
WebResource service = Client.create().resource( url );
ClientResponse response = service.header( "Authorization", auth )
.header( "Content-Type", cType )
.post( ClientResponse.class, payload );
return response;
}
 
private static InputStream httpRequestGet( String url, String auth, String cType ) {
WebResource service = Client.create().resource( url );
InputStream response = service.header( "Authorization", auth ).header( "Content-Type", cType )
.get( InputStream.class );
return response;
}
 
private static String generateAuthorizationToken( String username, String password )
throws UnsupportedEncodingException {
 
return "Basic " + new String( Base64.encode( username + ":" + password ), StandardCharsets.UTF_8 );
}
}

Data Decoder Service

The following code shows how to upload a new decoder file for making it available within the Data Decoder Service.

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
 
import javax.ws.rs.core.MediaType;
 
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
import org.glassfish.jersey.media.multipart.internal.MultiPartWriter;
 
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.DefaultClientConfig;
 
public class DecoderServiceUploadExample {
 
public static void main( String[] args ) throws Exception {
// set proxy settings
final String PROXY_HOST = "rb-proxy-de.bosch.com";
final String PROXY_PORT = "8080";
setProxySettings( PROXY_HOST, PROXY_PORT );
//If you are inside your company network, proxy authentication may be required. Otherwise, you can remove this from the example. This is an example for a Bosch internal proxy.
 
// set user credentials
String username = "your_username";
String password = "your_password";
String authorizationCredentials = generateAuthorizationToken( username, password );
 
// prepare form data upload
String project = "demo";
String type = "FIBEX";
String name = "my-new-decoder-file";
String comment = "new new decoder file";
File file = new File( "path_to_your_decoder_spec_file" );
 
String resourceUrl = "https://www.bosch-iot-insights.com/data-decoder-service/v1/" + project + "/decoders";
 
DefaultClientConfig defaultClientConfig = new DefaultClientConfig();
defaultClientConfig.getClasses().add( MultiPartWriter.class );
WebResource webResource = Client.create( defaultClientConfig ).resource( resourceUrl );
 
FormDataMultiPart formDataMultiPart = (FormDataMultiPart) new FormDataMultiPart()
.field( "type", type )
.field( "project", project )
.field( "name", name )
.field( "comment", comment )
.bodyPart( new FileDataBodyPart( "file", file ) );
 
// send http post request
ClientResponse clientResponse = webResource
.accept( MediaType.WILDCARD_TYPE )
.type( MediaType.MULTIPART_FORM_DATA_TYPE )
.header( "Authorization", authorizationCredentials )
.post( ClientResponse.class, formDataMultiPart );
formDataMultiPart.close();
 
System.out.println( clientResponse.getStatus() );
System.out.println( clientResponse.getEntity( String.class ) );
}
 
private static void setProxySettings( String host, String port ) {
System.setProperty( "http.proxyHost", host );
System.setProperty( "http.proxyPort", port );
System.setProperty( "https.proxyHost", host );
System.setProperty( "https.proxyPort", port );
}
 
private static String generateAuthorizationToken( String username, String password )
throws UnsupportedEncodingException {
return "Basic " +
new String( Base64.getEncoder().encode( (username + ":" + password).getBytes() ), StandardCharsets.UTF_8 );
}
 
}

Next, this code sends a CAN trace line against an already uploaded and available decoder.

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
 
import javax.ws.rs.core.MediaType;
 
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
 
public class DecoderServiceDecodingExample {
 
public static void main( String[] args ) throws Exception {
// set proxy settings
final String PROXY_HOST = "rb-proxy-de.bosch.com";
final String PROXY_PORT = "8080";
setProxySettings( PROXY_HOST, PROXY_PORT );
//If you are inside your company network, proxy authentication may be required. Otherwise, you can remove this from the example. This is an example for a Bosch internal proxy.
 
// set user credentials
String username = "your_username";
String password = "your_password";
String authorizationCredentials = generateAuthorizationToken( username, password );
 
// prepare and send http post request
String project = "demo";
String type = "fibex";
String decoderId = "your_decoder_ID";
String hexInput = "your_HEX_input";
 
String resourceUrl = "https://www.bosch-iot-insights.com/data-decoder-service/v1/"
+ project + "/decoders/" + decoderId + "/" + type + "/test";
 
WebResource webResource = Client.create().resource( resourceUrl );
ClientResponse clientResponse = webResource
.accept( MediaType.WILDCARD_TYPE )
.type( MediaType.APPLICATION_JSON_TYPE )
.header( "Authorization", authorizationCredentials )
.post( ClientResponse.class, "{\"testDataWithPdu\":[\"" + hexInput + "\"]}" );
 
System.out.println( clientResponse.getStatus() );
System.out.println( clientResponse.getEntity( String.class ) );
}
 
private static void setProxySettings( String host, String port ) {
System.setProperty( "http.proxyHost", host );
System.setProperty( "http.proxyPort", port );
System.setProperty( "https.proxyHost", host );
System.setProperty( "https.proxyPort", port );
}
 
private static String generateAuthorizationToken( String username, String password )
throws UnsupportedEncodingException {
return "Basic " +
new String( Base64.getEncoder().encode( (username + ":" + password).getBytes() ), StandardCharsets.UTF_8 );
}
 
}