jenkins中jelly文件的使用

jelly文件爲jenkins插件提供圖形界面,後臺的處理函數由對應的java代碼進行處理。例如要在系統設置中爲自己的插件添加參數設置等選項,就需要在~/jenkins-plugin/src/main/java/目錄錄下添加自己的java類來處理這個事情,例如我添加的類爲Tools,則我在對應的~/jenkins-plugin/src/main/resources/Tools/下添加對應的jelly文件,名爲global.jelly。這個jelly放在什麼名字的文件夾下就會去找什麼名字對應的類中的處理函數。

在pom.xml文件中,下面的代碼定義了插件構建所依賴的jenkins版本。

 <parent>
    <groupId>org.jenkins-ci.plugins</groupId>
    <artifactId>plugin</artifactId>
    <version>2.11</version>
    <relativePath/>
  </parent>

在對應的java文件中,我們可以通過拓展一個jenkins本身的拓展點來完成插件的設計。每個可以被拓展的類都實現了hudson.ExtensionPoint。可以通過類似@Extension@DataBoundConstructor這樣的內嵌標籤來告訴jenkins做一些操作。描述符(Descriptor)定義了jenkins是如何創建這個插件的實例和傳遞一些配置參數的。JavaDoc中對其的定義如下。

hudson.model.Descriptor
Metadata about a configurable instance. 

Descriptor is an object that has metadata about a Describable object, and also serves as a factory (in a way this relationship is similar to Object/Class relationship. A Descriptor/Describable combination is used throughout in Hudson to implement a configuration/extensibility mechanism. 

Take the list view support as an example, which is implemented in ListView class. Whenever a new view is created, a new ListView instance is created with the configuration information. This instance gets serialized to XML, and this instance will be called to render the view page. This is the job of Describable — each instance represents a specific configuration of a view (what projects are in it, regular expression, etc.) 

For Hudson to create such configured ListView instance, Hudson needs another object that captures the metadata of ListView, and that is what a Descriptor is for. ListView class has a singleton descriptor, and this descriptor helps render the configuration form, remember system-wide configuration, and works as a factory. 

Descriptor also usually have its associated views. 

在描述符中,調用load()裝載持久化保存在本地的配置數據,在configure函數中調用save()來持久化保存配置參數到本地。由於jenkins的機制問題,所以描述符只能內嵌聲明在主要的插件類中。

jenkins插件中使用了一種機制,只要我們給描述符中的方法命名爲一個特殊的的符合約定的名字,jenkins就會自動去調用它。如,load()調用過程中會把本地持久化的數據再存儲到描述符的字段中,然後使用調用getXxx方法,這樣就把字段中的值存儲到xxx中了。

在系統設置界面,只要用戶點擊保存或者應用,就會調用描述符中定義的configure方法。我們可以在這個函數中讀取用戶輸入的配置信息,進行處理,最後調用save方法保存這些參數。

我覺得學習jelly的編寫和其與java的交互代碼,更快的是閱讀Github上的各種開源項目,可以尋找一個和你實現功能類似的,然後修改並測試測試其中的源碼,總結各種變化的規律。也可以參考我最近寫的一個jenkins插件hyper common plugin,這個插件實現了hyper credentials的存儲,hypercli的下載和與其賬戶的連通性測試。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章