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.StandardCharsetsimport com.sun.jersey.api.client.Clientimport com.sun.jersey.api.client.ClientResponseimport com.sun.jersey.api.client.WebResourceimport com.sun.jersey.core.util.Base64object 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.StandardCharsetsimport java.nio.file.Filesimport java.nio.file.Pathsimport com.google.gson.Gsonimport com.google.gson.GsonBuilderimport com.google.gson.JsonElementimport com.google.gson.JsonParserimport com.sun.jersey.api.client.Clientimport com.sun.jersey.api.client.ClientResponseimport com.sun.jersey.api.client.WebResourceimport com.sun.jersey.core.util.Base64object 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.InputStreamimport java.io.InputStreamReaderimport java.io.Readerimport java.nio.charset.StandardCharsetsimport java.nio.file.Filesimport java.nio.file.Pathimport java.nio.file.Pathsimport java.nio.file.StandardCopyOptionimport com.google.gson.Gsonimport com.google.gson.JsonObjectimport com.sun.jersey.api.client.Clientimport com.sun.jersey.api.client.ClientResponseimport com.sun.jersey.api.client.WebResourceimport com.sun.jersey.core.util.Base64object 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.Fileimport java.nio.charset.StandardCharsetsimport java.util.Base64import javax.ws.rs.core.MediaTypeimport org.glassfish.jersey.media.multipart.FormDataMultiPartimport org.glassfish.jersey.media.multipart.file.FileDataBodyPartimport org.glassfish.jersey.media.multipart.internal.MultiPartWriterimport com.sun.jersey.api.client.Clientimport com.sun.jersey.api.client.ClientResponseimport com.sun.jersey.api.client.WebResourceimport com.sun.jersey.api.client.config.DefaultClientConfigobject 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.StandardCharsetsimport java.util.Base64import javax.ws.rs.core.MediaTypeimport com.sun.jersey.api.client.Clientimport com.sun.jersey.api.client.ClientResponseimport com.sun.jersey.api.client.WebResourceobject 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 )}