The following is a set of custom objects that will trigger from an Expression Rule, and cause a file uploaded by a remote agent to be sent on to the Thingworx platform instance of your choice once completed. The expression rules should be configured as so:
SendUploadedFiles.groovy:
import com.axeda.drm.sdk.data.UploadedFile
import static com.axeda.sdk.v2.dsl.Bridges.*
logger.info("Executing AsyncExecutor")
//Spawn async thread for each upload
compressedFile.getFiles().each {
UploadedFile upFile ->
// last parameter is a timeout for the execution measured in seconds (200 minutes)
customObjectBridge.initiateAsync("SendToThingWorx",
[
fileID: upFile.id,
hint: parameters.hint,
deviceID: context.device.id
], 200 * 60)
}
SendToThingworx.groovy:
import static com.axeda.sdk.v2.dsl.Bridges.*
import com.axeda.services.v2.*
import com.axeda.sdk.v2.exception.*
import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
import com.axeda.drm.sdk.data.* // UploadedFileFinder stuff.
import com.axeda.drm.sdk.Context
import com.axeda.common.sdk.id.Identifier
import org.apache.commons.codec.binary.Base64
def retStr = "this is a sample groovy script. your username: ${parameters.username}\n"
def context = Context.getAdminContext()
def thingName = 'ExampleThing'def thingworxHost = 'sample.cloud.thingworx.com'
def twxApplicationKey = '00000000-0000-0000-0000-00000000000'
def fileid = parameters.fileID
def finder = new UploadedFileFinder(context)
finder.setId( new Identifier( fileid.toLong()) )
UploadedFile uf = finder.find()
def is = new FileInputStream( uf.extractFile() )
retStr += "UF: ${uf.name} ${uf.fileSize} ${uf.actualFileName}\n"
logger.info "UF: ${uf.name} ${uf.fileSize} ${uf.actualFileName}\n"
def bOut = new ByteArrayOutputStream()
int b = 0
int count = 0
while ( (b = is.read()) != -1 ) {
count ++
bOut.write(b)
}
is?.close()
byte[] bRes = bOut.toByteArray()
logger.info "Length: ${bRes.length}"
retStr += "Count: ${count} Length: ${bRes.length}\n"
def b64 = new Base64()
def outputStr = b64.encodeBase64String(bRes)
retStr += "Length of base64 string: ${outputStr.length()}\n"
logger.info "Length of base64 string: ${outputStr.length()}\n"
logger.info "==========================================="
logger.info outputStr
logger.info "==========================================="
def http = new HTTPBuilder("https://${thingworxHost}")
http.request(POST, JSON) {
uri.path = "/Thingworx/Things/${thingName}/Services/SaveBinary"
body = [path: uf.name, content: outputStr ]
headers = [appKey: twxApplicationKey ,
Accept: 'application/json',
"content-type": "application/json"
]
response.success = { resp ->
println "POST response status: ${resp.statusLine}"
logger.info "POST RESPONSE status: ${resp.statusLine}"
}
response.failure = { resp ->
logger.info "RequestMessage: ${resp.statusLine}"
logger.info "Request failed: ${resp.status}"
}
}
return retStr