Audit Entry to CSV

    This script creates a csv file from the audit log filtered by the User Access category, so dates of when users logged in or logged out.

     

    *** see update below *** Note:  The csv file has the same name as the Groovy script and does NOT have the .csv extension . To get the .csv extension, the Groovy script has to be renamed to AuditEntryToCSV.csv.groovy .  Suggestions on how to improve this are welcome.

    *** Update ***: The download works without the renamed groovy script by returning text instead of an input stream.  The script has been modified to illustrate this.

     

    Parameters:

    1. days - the number of days past to fetch audit logs
    2. model_name - the model name of the asset
    3. serial_number - the serial number of the asset

     

    import com.axeda.drm.sdk.device.ModelFinder
    import com.axeda.drm.sdk.Context
    import com.axeda.common.sdk.id.Identifier
    import com.axeda.drm.sdk.device.Model
    import com.axeda.drm.sdk.device.DeviceFinder
    import com.axeda.drm.sdk.device.Device
    import com.axeda.drm.sdk.audit.AuditCategoryList
    import com.axeda.drm.sdk.audit.AuditCategory
    import com.axeda.drm.sdk.audit.AuditEntryFinder
    import com.axeda.drm.sdk.audit.SortType
    import com.axeda.drm.sdk.audit.AuditEntry
    import groovy.xml.MarkupBuilder
    import com.axeda.platform.sdk.v1.services.ServiceFactory
    
    /*
    * AuditEntryToCSV.groovy
    *
    * Creates a csv file from the audit log filtered by the User Access category, so dates of when users logged in or logged out.
    *
    * @param days        -   (REQ):Str number of days to search.
    * @param model_name        -   (REQ):Str name of the model.
    * @param serial_number        -   (REQ):Str serial number of the device.
    *
    * @note - the csv file has the same name as the Groovy script and does NOT have the .csv extension . To get
    * the .csv extension, the Groovy script has to be renamed to AuditEntryToCSV.csv.groovy .
    *
    * @author Sara Streeter <sstreeter@axeda.com>
    */
    
    def writer = new StringWriter()
    def xml = new MarkupBuilder(writer)
    
    try {
       def ctx = Context.getUserContext()
       ModelFinder modelFinder = new ModelFinder(ctx)
       modelFinder.setName(parameters.model_name)
       Model model = modelFinder.find()
       DeviceFinder deviceFinder = new DeviceFinder(ctx)
       deviceFinder.setSerialNumber(parameters.serial_number)
       Device device = deviceFinder.find()
       AuditCategoryList acl = new AuditCategoryList()
       acl.add(AuditCategory.USER_ACCESS)
       long now = System.currentTimeMillis()
       Date today = new Date(now)
       def paramdays = parameters.days ? parameters.days: 5
       long days = 1000 * 60 * 60 * 24 * Integer.valueOf(paramdays)
    
       AuditEntryFinder aef = new AuditEntryFinder(ctx)
       aef.setCategories(acl)
       aef.setToDate(today)
       aef.setFromDate(new Date(now - (days)))
       aef.setSortType(SortType.DATE)
       aef.sortDescending()
       List<AuditEntry> audits = aef.findAll()
    
    // use a Data Accumulator to store the information
    def dataStoreIdentifier = "FILE-CSV-audit_log"
    
    def daSvc = new ServiceFactory().dataAccumulatorService
    
    if (daSvc.doesAccumulationExist(dataStoreIdentifier, device.id.value)) {
        daSvc.deleteAccumulation(dataStoreIdentifier, device.id.value)
    }
    
    // assemble the response
       audits.each { AuditEntry audit ->
      
               def row = [
                   audit?.id.value,
                   audit?.user?.username,
                   audit?.date,
                   audit?.category?.bundleKey,
                   audit?.message
               ]
            row = row.join(',')
            row += '\n'
            daSvc.writeChunk(dataStoreIdentifier, device.id.value, row);
           }
    // stream the data accumulator to create the file
       InputStream is = daSvc.streamAccumulation(dataStoreIdentifier, device.id.value)
    
    return ['Content-Type': 'text/csv', 'Content-Disposition':'attachment; filename=AuditEntryCSVFile.csv', 'Content': is.text]
    
    } catch (def ex) {
       xml.Response() {
           Fault {
               Code('Groovy Exception')
               Message(ex.getMessage())
               StringWriter sw = new StringWriter();
               PrintWriter pw = new PrintWriter(sw);
               ex.printStackTrace(pw);
               Detail(sw.toString())
           }
       }
    logger.info(writer.toString())
    }