2016-11-07 9 views
0

Я использую этот нижеприведенный скрипт для удаления некоторых артефактов в Artifactory на основе определенных критериев по запросу AQL. Я новичок в groovy-скрипте, но мне хотелось бы знать, возможно ли импортировать AQL-запрос из внешнего файла, поэтому нам не нужно каждый раз редактировать этот скрипт для любых изменений в запросе AQL. Этот ниже запрос работает так, как ожидалось, но любая помощь была бы оценена, если вызывать AQL из внешнего файла.Есть ли способ импортировать файл AQL импорта извне в artifactory cleanup groovy script

Заранее спасибо

import groovyx.net.http.RESTClient 
import groovyx.net.http.HttpResponseException 
import org.apache.http.conn.HttpHostConnectException 


def query = '**items.find({"repo": "xxx-repo-for-poc","created_by" : "xxx","name" :{"$match": "*.nupkg"})**' // replace this with your AQL query 
    def artifactoryURL = 'http://Servername:8081/artifactory/' // replace this with Artifactory server 
    def restClient = new RESTClient(artifactoryURL) 
    restClient.setHeaders(['Authorization': 'Basic ' + "admin:password".getBytes('iso-8859-1').encodeBase64()]) //replace the 'admin:password' with your own credentials 
    def dryRun = true //set the value to false if you want the script to actually delete the artifacts 

    def itemsToDelete = this.&getAqlQueryResult(restClient, query) 
    if (itemsToDelete != null && itemsToDelete.size() > 0) { 
     this.&delete(restClient, itemsToDelete, dryRun) 
    } else { 
     println('NOTHING TO DELETE') 
    } 

    /** 
    * Send the AQL to Artifactory and collect the response. 
    */ 
    public List getAqlQueryResult(RESTClient restClient, String query) { 
     def response 
     try { 
      response = restClient.post(path: 'api/search/aql', 
        body: query, 
        requestContentType: 'text/plain' 
      ) 
     } catch (Exception e) { 
      println(e.message) 
     } 
     if (response != null && response.getData()) { 
      def results = []; 
      response.getData().results.each { 
       results.add(constructPath(it)) 
      } 
      return results; 
     } else return null 
    } 

    /** 
    * Construct the full path form the returned items. 
    * If the path is '.' (file is on the root) we ignores it and construct the full path from the repo and the file name only 
    */ 
    public constructPath(groovy.json.internal.LazyMap item) { 
     if (item.path.toString().equals(".")) { 
      return item.repo + "/" + item.name 
     } 
     return item.repo + "/" + item.path + "/" + item.name 
    } 

    /** 
    * Send DELETE request to Artifactory for each one of the returned items 
    */ 
    public delete(RESTClient restClient, List itemsToDelete, def dryRun) { 
     dryMessage = (dryRun) ? "*** This is a dry run ***" : ""; 
     itemsToDelete.each { 
      println("Trying to delete artifact: '$it'. $dryMessage") 
      try { 
       if (!dryRun) { 
        restClient.delete(path: it) 
       } 
       println("Artifact '$it' has been successfully deleted. $dryMessage") 
      } catch (HttpResponseException e) { 
       println("Cannot delete artifact '$it': $e.message" + 
         ", $e.statusCode") 
      } catch (HttpHostConnectException e) { 
       println("Cannot delete artifact '$it': $e.message") 
      } 
     } 
    } 

ответ

0

searches апи выставляет aql метод, который позволяет выполнять запросы AQL и действовать по результатам, как вы считаете нужным.

Вы также должны проверить пользовательские плагины documentation, он содержит полезную информацию и примеры использования.

 Смежные вопросы

  • Нет связанных вопросов^_^