Bosch IoT Insights

Scala

You can download the following code examples as cloud-examples-scala.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.

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 Scala code example shows you how to send data to the HTTP Data Recorder Service of the Insights backend using Scala code.

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
 
object DataRecorderServiceExample {
 
def main( args: Array[String] ): Unit = {
 
val proxyHost: String = "rb-proxy-de.bosch.com"
val proxyPort: String = "8080"
// If you are inside your company network, a proxy authentication may be required. Otherwise, you can remove this from the example. This is an example for a Bosch internal proxy.
 
val resourceUrl: String = "https://bosch-iot-insights.com/data-recorder-service/v2/"
val insightsProject: String = "demo"
 
val username: String = "your_username"
val password: String = "your_password"
val authorizationCredentials: String = generateAuthorizationToken( username, password )
 
val contentType: String = "text/plain"
val payload: String = "Hello World"
 
System.setProperty( "https.proxyHost", proxyHost )
System.setProperty( "https.proxyPort", proxyPort )
 
val service: WebResource = Client.create().resource( resourceUrl + insightsProject )
val response: ClientResponse = service.header( "Authorization", authorizationCredentials )
.header( "Content-Type", contentType )
.post( classOf[ClientResponse], payload )
 
println( response )
}
 
private def generateAuthorizationToken( username: String, password: String ): String =
"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.

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

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
 
object MongoDBQueryServiceSyncExample {
 
def main( args: Array[String] ): Unit = {
 
val proxyHost: String = "rb-proxy-de.bosch.com"
val proxyPort: String = "8080"
// If you are inside your company network, a proxy authentication may be required. Otherwise, you can remove this from the example. This is an example for a Bosch internal proxy.
 
val insightsProject: String = "demo"
val resourceUrl: String = "https://bosch-iot-insights.com/mongodb-query-service/v2/" + insightsProject + "/execute-aggregation-query"
 
val username: String = "your_username"
val password: String = "your_password"
val authorizationCredentials: String = generateAuthorizationToken( username, password )
 
val contentType: String = "application/json"
val payload: String = new String( Files.readAllBytes( Paths.get( "src/resources/queryParametersSync.json" )))
 
System.setProperty( "https.proxyHost", proxyHost )
System.setProperty( "https.proxyPort", proxyPort )
 
val service: WebResource = Client.create().resource( resourceUrl )
val response: ClientResponse = service.header( "Authorization", authorizationCredentials )
.header( "Content-Type", contentType )
.post( classOf[ClientResponse ], payload)
 
println( response )
 
if ( response.getStatus == 200 ) {
println( parseJson( response.getEntity( classOf[String] ) ) )
}
}
 
private def generateAuthorizationToken( username: String, password: String ): String =
"Basic " + new String( Base64.encode( username + ":" + password ), StandardCharsets.UTF_8 )
 
private def parseJson(plainString: String): String = {
val gson: Gson = new GsonBuilder().setPrettyPrinting().create()
val json: JsonElement = new JsonParser().parse( plainString )
gson.toJson( json )
}
 
}

Asynchronous query execution

The following example shows the entire sequence of an asynchronous MongoDB aggregation query execution. Please note that a asynchronous call returns the query result not immediately.

You have to poll the status of the query till it changes to SUCCESSFUL. Then you can fetch the results.

MongoDBQueryServiceAsyncExample.scala

import java.io.InputStream
import java.io.InputStreamReader
import java.io.Reader
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
 
object MongoDBQueryServiceAsyncExample {
 
def main( args: Array[String] ): Unit = {
 
val proxyHost: String = "rb-proxy-de.bosch.com"
val proxyPort: String = "8080"
// If you are inside your company network, a proxy authentication may be required. Otherwise, you can remove this from the example. This is an example for a Bosch internal proxy.
val insightsProject: String = "demo"
val resourceUrl: String = "https://bosch-iot-insights.com/mongodb-query-service/v2/" + insightsProject
 
val username: String = "your_username"
val password: String = "your_password"
val authorizationCredentials: String = generateAuthorizationToken(username, password)
 
val contentType: String = "application/json"
val payload: String = new String( Files.readAllBytes( Paths.get( "src/resources/queryParametersAsync.json" ) ) )
 
System.setProperty( "https.proxyHost", proxyHost )
System.setProperty( "https.proxyPort", proxyPort )
 
val response: ClientResponse = httpRequestPost( resourceUrl + "/submit-aggregation-query", authorizationCredentials, contentType, payload )
 
println( response )
 
if ( response.getStatus == 200 ) {
var queryError: Boolean = false
val responseContent: String = response.getEntity( classOf[String] )
 
val json: JsonObject = new Gson().fromJson( responseContent, classOf[JsonObject] )
val requestId: String = json.get( "queryId" ).getAsString
var queryStatus: String = json.get( "status" ).getAsString
 
println( "Status: " + queryStatus )
 
while ( queryStatus.!=( "SUCCESSFUL" ) ) {
val responseStream: InputStream = httpRequestGet( resourceUrl + "/queries" + "/" + requestId, authorizationCredentials,
contentType )
val reader: Reader = new InputStreamReader( responseStream )
val jsonRes2: JsonObject = new Gson().fromJson( reader, classOf[JsonObject] )
queryStatus = jsonRes2.get( "status" ).getAsString
println( "Status: " + queryStatus )
 
if ( queryStatus.==( "FAILED" ) || queryStatus.==( "INCORRECT" ) ) {
queryError = true
}
}
 
if ( !queryError ) {
val responseStream: InputStream = httpRequestGet( resourceUrl + "/queries" + "/" + requestId + "/result", authorizationCredentials,
contentType )
println( "Status: LOADING DATA..." )
val path: Path = Paths.get(System.getProperty( "user.home" ) + "/queryResponse.txt" )
Files.copy( responseStream, path, StandardCopyOption.REPLACE_EXISTING )
println( "Status: DONE" )
println( "Response data was saved at " + path )
}
}
}
 
private def httpRequestPost( url: String, auth: String, cType: String, payload: String ): ClientResponse = {
val service: WebResource = Client.create().resource( url )
val response: ClientResponse =
service.header( "Authorization", auth).header( "Content-Type", cType ).post( classOf[ClientResponse], payload )
response
}
 
private def httpRequestGet( url: String, auth: String, cType: String ): InputStream = {
val service: WebResource = Client.create().resource( url )
val response: InputStream =
service.header( "Authorization", auth ).header( "Content-Type", cType).get( classOf[InputStream] )
response
}
 
private def generateAuthorizationToken( username: String, password: String ): String =
"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.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
 
object DecoderServiceUploadExample {
 
def main( args: Array[String] ): Unit = {
// set proxy settings
// If you are inside your company network, a proxy authentication may be required. Otherwise, you can remove this from the example. This is an example for a Bosch internal proxy.
val PROXY_HOST: String = "rb-proxy-de.bosch.com"
val PROXY_PORT: String = "8080"
setProxySettings(PROXY_HOST, PROXY_PORT)
 
// set user credentials
val username: String = "your_username"
val password: String = "your_password"
val authorizationCredentials: String = generateAuthorizationToken( username, password )
 
// prepare form data upload
val project: String = "demo"
val `type`: String = "FIBEX"
val name: String = "my-new-decoder-file"
val comment: String = "new new decoder file"
val file: File = new File( "path_to_your_decoder_spec_file" )
 
val resourceUrl: String = "https://www.bosch-iot-insights.com/data-decoder-service/v1/" + project + "/decoders"
 
val defaultClientConfig: DefaultClientConfig = new DefaultClientConfig()
defaultClientConfig.getClasses.add( classOf[MultiPartWriter] )
val webResource: WebResource = Client.create( defaultClientConfig ).resource( resourceUrl )
 
val formDataMultiPart: FormDataMultiPart = new FormDataMultiPart()
.field( "type", `type` )
.field( "project", project )
.field( "name", name )
.field( "comment", comment )
.bodyPart( new FileDataBodyPart( "file", file ) )
.asInstanceOf[FormDataMultiPart]
 
// send http post request
val clientResponse: ClientResponse = webResource
.accept( MediaType.WILDCARD_TYPE )
.`type`( MediaType.MULTIPART_FORM_DATA_TYPE )
.header("Authorization", authorizationCredentials )
.post( classOf[ClientResponse], formDataMultiPart )
formDataMultiPart.close()
 
println( clientResponse.getStatus )
println( clientResponse.getEntity( classOf[String] ) )
}
 
private def setProxySettings( host: String, port: String ): Unit = {
System.setProperty( "http.proxyHost", host )
System.setProperty( "http.proxyPort", port )
System.setProperty( "https.proxyHost", host )
System.setProperty( "https.proxyPort", port )
}
 
private def generateAuthorizationToken( username: String, password: String ): String =
"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.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
 
object DecoderServiceDecodingExample {
 
def main( args: Array[String] ): Unit = {
 
// set proxy setting
// If you are inside your company network, a proxy authentication may be required. Otherwise, you can remove this from the example. This is an example for a Bosch internal proxy.
val PROXY_HOST: String = "rb-proxy-de.bosch.com"
val PROXY_PORT: String = "8080"
setProxySettings( PROXY_HOST, PROXY_PORT )
 
// set user credentials
val username: String = "your_username"
val password: String = "your_password"
val authorizationCredentials: String = generateAuthorizationToken(username, password)
 
// prepare and send http post request
val project: String = "demo"
val `type`: String = "FIBEX"
val decoderId: String = "your_decoder_ID"
val hexInput: String = "your_HEX_input"
 
val resourceUrl: String = "https://www.bosch-iot-insights.com/data-decoder-service/v1/" +
project + "/decoders/" + decoderId + "/" + `type` + "/test"
 
val webResource: WebResource = Client.create().resource( resourceUrl )
val clientResponse: ClientResponse = webResource.accept( MediaType.WILDCARD_TYPE).`type`(MediaType.APPLICATION_JSON_TYPE )
.header("Authorization", authorizationCredentials )
.post( classOf[ClientResponse], "{\"testDataWithPdu\":[\"" + hexInput + "\"]}" )
 
println( clientResponse.getStatus )
println( clientResponse.getEntity( classOf[String] ) )
 
}
 
private def setProxySettings( host: String, port: String ): Unit = {
System.setProperty( "http.proxyHost", host )
System.setProperty( "http.proxyPort", port )
System.setProperty( "https.proxyHost", host )
System.setProperty( "https.proxyPort", port )
}
 
private def generateAuthorizationToken( username: String, password: String ): String =
"Basic " + new String( Base64.getEncoder.encode( (username + ":" + password).getBytes ), StandardCharsets.UTF_8 )
 
}