Axeda Groovy Script: Retrieving Binary Uploaded File

    This is an example to show returning an uploaded file as a binary from a Groovy Script.

     

    Parameters:

    1. model_name
    2. serial_number

     

    import java.io.StringWriter
    import java.io.PrintWriter
    import com.axeda.drm.sdk.Context
    import com.axeda.drm.sdk.data.*
    import com.axeda.drm.sdk.device.*
    import javax.activation.MimetypesFileTypeMap
    
    try {
    
        Context ctx = Context.getUserContext()
    
        ModelFinder modelFinder = new ModelFinder(ctx)
        modelFinder.setName(parameters.model_name)
        Model model = modelFinder.find()
    
        DeviceFinder dfinder = new DeviceFinder(ctx)
    
        dfinder.setModel(model)
    
        dfinder.setSerialNumber(parameters.serial_number)
        Device d = dfinder.find()
    
        UploadedFileFinder uff = new UploadedFileFinder(ctx)
        uff.device = d
    
        def ufiles = uff.findAll()
    
        UploadedFile ufile
        if (ufiles.size() > 0) {
            ufile = ufiles[0]
            File f = ufile.extractFile()
        def type = getType(f)
        return ['Content-Type': type, 'Content': new FileInputStream(f)]
    
         }
    else {
        return ['Content-Type': 'text/plain', 'Content': 'No files have been uploaded']
    }
    
    }
    catch (Exception e) {
        logger.info(e.message)
        StringWriter logStringWriter = new StringWriter();
        PrintWriter logPrintWriter = new PrintWriter(logStringWriter)
        e.printStackTrace(logPrintWriter)
        logger.info(logStringWriter.toString())
    }
    
    static String getType(File f) {
      MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap()
      return mimeTypesMap.getContentType(f);
    }