Axeda Connected Configuration Items Create/Read/Update

    The following script is a component of the Axeda Connected Configuration (CMDB) feature.  It is used to provide configuration data for controlling package deployments via Connected Content (SCM).

    ConfigItem_CRU.groovy

    *Takes a POST request, not parameters


    import static com.axeda.sdk.v2.dsl.Bridges.*
    import com.axeda.drm.sdk.scripto.Request
    import com.axeda.services.v2.ConfigurationItem
    import com.axeda.services.v2.ConfigurationItemCriteria
    import com.axeda.services.v2.AssetConfiguration
    import com.axeda.services.v2.Asset
    import com.axeda.services.v2.ExecutionResult
    import groovy.json.JsonSlurper
    import net.sf.json.JSONObject
    import groovy.xml.MarkupBuilder
    
    /**
    * ConfigItem_CRU.groovy
    * -----------------------
    *
    * Reads in json from an http post request and reads, adds, deletes or updates Configuration Items.
    *
    *
    * @note this parses a post and does not take any additional parameters.
    *
     * @author sara streeter <sstreeter@axeda.com>
    */
    
    def contentType = "application/json"
    final def serviceName = "ConfigItem_CRU"
    
    def response = [:]
    def writer = new StringWriter()
    def xml = new MarkupBuilder(writer)
    
    try {
        // BUSINESS LOGIC BEGIN
        def assetId
        def validationOnly
        def validationResponse = ""
        List<ConfigurationItem> configItemList
        if (Request?.body != null && Request?.body !="") {
    
            def slurper = new JsonSlurper()
            def request = slurper.parseText(Request?.body)
    
            assetId = request.result.assetId
            validationOnly = request.result.validationOnly?.toBoolean()
    
            if (request.result.items != null && request.result.items.size() > 0){
                configItemList = request.result.items.inject([]) { target, item ->
                  if (item && item.path != "" && item.key != "" && item.path != null && item.key != null){
                        ConfigurationItem configItem = new ConfigurationItem()
                        configItem.path = item.path + item.key
                        configItem.value = item.value
                        target << configItem
                    }
                    target
                }
            }
        }
    
          if (assetId != null) {
                  def asset = assetBridge.find([assetId])[0]
                AssetConfiguration config = assetConfigurationBridge.getAssetConfiguration(assetId, "")
                  def itemToDelete
            
                    if (config == null) {
                        createConfigXML(xml)
                        AssetConfiguration configToCreate = assetConfigurationBridge.fromXml(writer.toString(), asset.id)
                        ExecutionResult result = assetConfigurationBridge.create(configToCreate)
                        AssetConfiguration config2 = assetConfigurationBridge.getAssetConfiguration(asset.id, "")
                        config = config2
                        itemToDelete = "/Item"
                    }
                    if (configItemList != null && configItemList?.size() > 0){
                    List<ConfigurationItem> compareList = config.items
    
                    def intersectingCompareItems = compareList.inject(["save": [], "delete": []]) { map, item ->
    
                        // find whether to delete
                        def foundItem = configItemList.findAll{ compare -> item?.path == compare?.path && item?.value == compare?.value  }
                        map[foundItem.size() > 0 ? "save" : "delete"] << item
                        map
                    }
    
                  intersectingCompareItems.delete = intersectingCompareItems.delete.collect{it.path}
                  if (itemToDelete){
                    intersectingCompareItems.delete.add(itemToDelete)
                  }
    
                    def intersectingConfigItems = configItemList.inject(["old": [], "new": []]) { map, item ->
                        // find whether it's old
                        def foundItem = compareList.findAll{ compare -> item?.path == compare?.path && item?.value == compare?.value }
    
                        map[foundItem.size() > 0 ? "old" : "new"] << item
                        map
                    }
    
                    assetConfigurationBridge.deleteConfigurationItems(config, intersectingCompareItems.delete)
    
                    assetConfigurationBridge.appendConfigurationItems(config, intersectingConfigItems.new)
    
                  def exResult = assetConfigurationBridge.validate(config)
    
                  if (exResult.successful){
                        validationResponse = "success"
                        if (!validationOnly){
                            assetConfigurationBridge.update(config)
                        }
                  }
                    else {
                        validationResponse = exResult.failures[0]?.details
                    }
    
                }
    
                response = [
    
                    assetId: assetId,
                    items: config?.items?.collect { item ->
                    def origpath = item.path
    
                    def lastSlash = origpath.lastIndexOf("/")
    
                    def key = origpath.substring(lastSlash + 1, origpath.length())
            
                    def path = origpath.replace("/" + key, "")
                    path += "/"
                        [
                            path: path,
                            key: key,
                            value: item.value
                        ]
                    },
                    validationResponse: validationResponse
                ]
    
          }
    
            else {
                throw new Exception("Error: Asset Id must be provided.")
            }
    
    }
    catch (Exception ex) {
          logger.error ex
      response = [
              error:  [
                      type: "Backend Application Error"
                      , msg: ex.getLocalizedMessage()
              ]
      ]
    }
    
    return ['Content-Type': 'application/json', 'Content': JSONObject.fromObject(response).toString(2)]
    
    /**
    * Create the Success response.
    *
    * @param xml : The xml response.<br>
    * @param info : If this is set to "1" the info element will be included in the response.<br>
    * @param infos : Collection of information to include within the info element of the response.<br>
    */
    private void createConfigXML(xml) {
        xml.Item()
    
    }