Jenkins in Jelly Foundation, hyperlinks, internationalization

Source: Internet
Author: User

Jelly Foundation

Reference: Https://wiki.jenkins-ci.org/display/JENKINS/Basic+guide+to+Jelly+usage+in+Jenkins

UI Samples Plugin

This plugin is used to show how to use the Jenkins UI controls based on stapler, Jelly, groovy and other technologies. Installing this plugin is useful for learning about Jenkins plugin development.

Create a *.jelly file

A basic Jenkins plug-in structure consists of the following sections:

    • Pom.xml
    • Src/main/java
    • Src/main/resources
    • Src/main/webapp

If you have already written a class Src/main/java/org/myorganization/myaction.java, define a jelly file for this class.

    1. Create a directory in the resources directory that corresponds to class name one by one: src/main/resources/org/myorganization/myaction
    2. Add a. jelly file to this directory (different filenames will have different effects), such as index.jelly.
    3. And then it's editing the file.

Pre-defined objects

All jelly files in a directory are directly associated with a class corresponding to that directory one by one. The corresponding class object is bound to a variable named it in the jelly file, and the method in the jelly file can be called through the IT variable , and the calling code is wrapped in a pair of curly braces with the front parenthesis plus $. The form is:${insert code here}.

For example, the following method is defined in Myaction.java

 Public String getmystring () {    return "Hello jenkins!" ;}

Example of calling this method in a jelly file

 <  j:jelly  xmlns:j  = "Jelly:core"   Xmlns:st  = "Jelly:stapler"   Xmlns:d  = "Jelly:define"   Xmlns:l  = "/lib/layout"   Xmlns:t  = "/lib/hudson"   Xmlns:f  = "/lib/form"  >   ${it.mystring}  </ j:jelly  >  

The get at the beginning of the method name is automatically removed and the rest of the first letter becomes lowercase. It is recommended that the naming of Java conventions (such as the CamelCase form of the Getter method) be used to ensure that jelly can find the correct method.

The pre-defined objects in Jenkins are mainly

It

class instances directly associated with the jelly file

Instance

The object that is currently being configured (within a region of the configuration page), such as BuildStep. This variable is null if you have just added a new instance instead of reconfiguring it.

App

Jenkins (or Hudson) instances

Descriptor

Descriptor Object corresponding to the class that the instance object belongs to

H

Hudson. An instance of the functions object provides a number of very useful methods.

Predefined URL variables

Rooturl

The URL of the Jenkins instance

Resurl

JavaScript, HTML and other static WebApp resources (cf. Jenkins.resource_path)

Imagesurl

icon and other image resource path, is actually resurl/images

You should use Resurl instead of rooturl as much as possible, because Resurl allows the browser to cache, which can improve response speed and relieve server pressure.

As long as within the l:layout or L:ajax block, these URLs are already defined, which means they can be used on any Jenkins page (if the page is loaded via Ajax, you need to add a l:ajax tag).

Note that until 1.505 Rooturl would be empty in the typical case of Jenkins running in development mode with no CO ntext path (http://localhost:8080/); It is used for creating server-absolute paths such as /some/path for direct links. As of 1.505 it would be /jenkins in test mode, the to-help remind the use it! In the "rare case," need to pass a complete URL of external service for some reason, use app.rooturl ins Tead (which takes into account "Jenkins URLs" from the system /configure screens). Hyperlinks in HTML have a fuller treatment of this topic.

in most cases, the jelly file is modified without restarting the Jenkins service to see the effect. Modify the file and then re-request the page, the modified jelly file will be loaded.

Objects with descriptors (such as publisher)
    1. Defines an immutable class that takes all configuration options as arguments to the constructor. Then add the @databoundconstructor annotation to the constructor, and Jenkins will know how to instantiate the object of the class with this annotation.
    2. Add a getter method for the configuration options field, or change the configuration option fieldto public final. These field values can be read in the Jelly script to the configuration page.
    3. Write jelly fragment files (typically called config.jelly, you can see the Javadoc document of the base class to see which jelly file names you can use), and show all the configuration options in the Jelly file. The most basic form is as follows (the field property of the jelly element is the name of the property, and also the name of the constructor parameter, in this case the class that corresponds to the jelly file needs to provide the Getport method or the Public port field).
<j:jellyxmlns:j= "Jelly:core"xmlns:f= "/lib/form">  <F:entrytitle= "${%port}"Field= "Port">    <F:textbox/>  </F:entry>  <F:entrytitle= "${%host}"Field= "Host">    <F:textbox/>  </F:entry></j:jelly>

${%...} For internationalization tagging (https://wiki.jenkins-ci.org/display/JENKINS/Internationalization).

Help file

Plug-ins can use help-field.html or help-field.jelly files in the Src/main/resources/path/to/plugin/pluginname directory. Jenkins will add a question mark icon after the corresponding filed element, and clicking on the icon will render the help file inline in the configuration page. help.html or help.jelly will act as the top-level help file for the plugin.

Form validation

The Docheckfield method that is added in the Descriptor class is used for form validation logic. Examples are as follows:

 Public formvalidation docheckport (@QueryParameter String value) {  if(Looksok (value))  return  Formvalidation.ok ();   Else                return Formvalidation.error ("There ' s a problem here");}

This method can have more than one @queryparameter ("FIELD") annotation parameter that specifies the specific filed, while obtaining multiple parameter values. You can validate the interdependence between form field. More detailed information can be queried for stapler's documentation.

Default value

You can set a default value for a form field by using the page elements ' default property. That is, you can calculate the default values in literal form or programmatically (using jelly predefined variables, methods for invoking these objects). Examples are as follows:

<j:jellyxmlns:j= "Jelly:core"xmlns:f= "/lib/form">  <F:entrytitle= "${%port}"Field= "Port">    <F:textboxdefault= "a" />  </F:entry>  <F:entrytitle= "${%host}"Field= "Host">    <F:textboxdefault= "${descriptor.defaulthost ()}/> </f:entry></j:jelly>

objects without descriptor (e.g. Computerlistener)

Reference plugin: Https://github.com/jenkinsci/sidebar-link-plugin

If the plug-in uses an descriptor object, such as Computerlistener. You can add a text box that can be read by a plug-in class (subclass plugin) in the configuration page by following the steps below.

  1. Override the Configure (Staplerrequest req, Jsonobject FormData) method of the plugin class. This method will be called when the user clicks the Save button on the configuration page.
  2. In the Configure method, call Formdata's fetch data method to get the configuration value, such as Optint ("Port", 3141), and save the obtained data in the member field of the plugin class.
  3. In the Configure method, the Save () method is called to persist the serializable field of the plugin class to the store.
  4. In the Start method of the plugin class, the load () is called, and the persisted stored data is reloaded when the plug-in starts.
  5. Create the config.jelly file in the location (src/main/resources/path/to/plugin/classname/config.jelly) corresponding to the plugin class and write the Configuration page view. In the config.jelly of the plug-in class,replacing variable instance with variable it, It.port can refer to the port parameter value that is currently in use. The Help property uses the Artifactid reference plug-in resource that is specified in Pom.xml when the plug-in is created.
    <j:jellyxmlns:j= "Jelly:core"xmlns:st= "Jelly:stapler"xmlns:d= "Jelly:define"xmlns:l= "/lib/layout"Xmlns:t= "/lib/hudson"xmlns:f= "/lib/form">  <f:sectiontitle= "My Plugin">    <F:entrytitle= "${%port}" Help= "/plugin/artifact_id_goes_here/help-projectconfig.html">      <F:textboxname= "Port"value= "${it.port}"/>    </F:entry>  </f:section></j:jelly>
  6. Create the Help file help-projectconfig.html in Src/main/webapp.
  7. Start Jenkins (MVN hpi:run) normally to see the effect.

hyperlinks in HTML

Https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML

Rule 1: Do not use absolute URLs for hyperlinks

Hyperlinks in HTML should use relative URLssuch as: /foo/bar, build/5/changes) or apply a relative URL(with/start, such as/JOB/FOO/5,/manage). However, do not use absolute paths (such as HTTP://JENKINS/FOO/1) in front. Let the browser make the relative path absolute.

The reason for this rule is that after a process such as a reverse proxy, the Web app cannot know the URL that the client uses to access the server. However, the reverse proxy will ensure that the path portion of the URL (context Path+path info) is intact, and that using relative paths within the app will have no effect.

In Java EE, the path portion of the URL can be divided into two segments, first the context path, followed by Path Info. For example, Http://server.example.com/jenkins/job/foo/5,/jenkins is the context path,/job/foo/5 for path info. Jenkins developers can control the latter.

    • The GETURL () method returns the path info portion of the domain object in the entire Jenkins, such as Buiild.geturl (), which returns job/foo/32/(no/At the beginning, not the same as the end/different version).
    • Getabsoluteurl () returns the absolute path of the domain object throughout Jenkins. Do not render the hyperlinks in this way.
    • In Groovy/jelly/javascript, the Rooturl variable represents the context path. The generated relative hyperlink format is:<a href= "${rooturl}/${it.url}" >...</a> (in Jelly) or A (href: "${rooturl}/${ My.url} ", ...) (for Groovy)
Rule 2: Use static resource prefix URLs to access static resources

Static resources such as pictures, JavaScript scripts, stylesheets, and so on, do not change in the Jenkins run and should be accessed using the static resource prefix URL (/static/xxxxx), such as/static/907dbcb0/plugin/foobar/ Abc.png. The xxxxx section is a random string that Jenkins generates for the duration of a running Jenkins session. The requested route is the same as without a prefix, but prefixed with a prefix will set a long expiration time for the browser to use the cache. The random number is to prevent the browser from using the old data after the Plugins/core update.

In Java: Functions.getresourcepath () as the prefix for the URL. Use the Resurl variable in jelly.

Functions.getresourcepath () + "/plugin/git/icons/git-32x32.png"; <  src= "${resurl}/plugin/translation/flags.png"/>
Rule 3: Generate absolute paths for email,im, etc.

If you provide service data in a manner that is HTTP responsive, you need to generate an absolute path. The Jenkins.getinstance (). Getrooturl () method is available, which returns the absolute path configured by the administrator. This is the only way to accurately obtain an absolute path in a Jenkins instance.

The rule 4:consolenote must be path-info

When you embed a into hyperspace link into the console output by Hyperlinknote, a portable hyperlink is created using the/Start URL (if the URL starts with/, it is handled relative to the context path). This way, even after the console note is created, the Jenkins URL is changed, and the hyperlink is still rendered correctly.

void foo (Tasklistener listener) {  Listener.getlogger (). println (    hyperlinknote.encodeto ("/configure", "Please configure your Jenkins");}

It's easy to create hyperlinks to different objects in Jenkins, and you can consult the Modelhyperlinknote class (http://javadoc.jenkins-ci.org/?hudson/console/ModelHyperlinkNote.html).

Reverse Proxy and HTTPS

If the reverse proxy terminates, Https,jenkins cannot take advantage of httpservletrequest#issecure () to check whether the transmission is secure. Jenkins.isrooturlsecure () can check if the Jenkins URL configured by the administrator is HTTPS.

Other path-related topics

Https://wiki.jenkins-ci.org/display/JENKINS/Jenkins+says+my+reverse+proxy+setup+is+broken

Https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache

Https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Nginx

Internationalization

Https://wiki.jenkins-ci.org/display/JENKINS/Internationalization

The properties file is encoded as iso-8859-1 by default. The static resource file is encoded as UTF-8.

Messages class

Jenkins uses Localizer (https://java.net/projects/localizer/) to generate the messages class to access the message resource in a type-safe manner. Src/main/resources/**/messages.properties matches so the file will generate a corresponding Messages class. If the IDE cannot find these classes, you need to manually add the Target/generated-sources/localizer directory to the root directory of the source code. The code that returns the string used to display (such as descriptor.getdisplayname ()) can use the messages class to get localized messages. At run time, the appropriate locale is automatically selected.

A typical workflow is as follows:

    1. Identify messages that need to be localized
    2. Writes a message to the Messages.properties file. That is, you can write one for each package, or you can use only one for the entire module/plugin.
    3. Run MVN compile, generate Messages.java
    4. Update the code, using the latest generated message format method.

If the message contains single quotation marks ('), it needs to be escaped with a single quotation mark last night ('). If you want to use the English apostrophe ('), you can use the Unicode character u+2019 and write \u2019 in the properties file.

Marking messages in the jelly file

The ${%XXXX} flag indicates that stapler finds localized resources and outputs xxxx if no corresponding resource is found.

< H1 > ${%Output} </ H1 >
With parameter message

To render the result:

< P > <  href= "${obj.somemethod (a,b,c)}">here</a> </p>

The contents of the Foo.properties file are:

Click.here.link Click <a href= "{0}" >here</a>

Message reference tokens in jelly:

< P > ${%click.here.link(obj.somemethod (a,b,c))} </ P >

Because the parameter uses the parentheses () package, the normal text cannot contain parentheses.

In this case, the parentheses can be excluded from the {%} tag by splitting the text

< H1 >${%path to File} (${%.ipa or. apk})</H1>    

Multiple parameters

Between multiple parameters, separated (similar method calls). Reference {0} to the first parameter by parameter position in the properties file, {1} for the second parameter ... (by Messageformat Analysis, reference: http://docs.oracle.com/javase/6/docs/api/java/text/MessageFormat.html)

< P >${h.ifthenelse (x, "No Error", "Error")}</p>

The message is re-tagged in the parameter and no curly braces {} package is required
< P >${h.ifthenelse (x, "%no error", "%error")}</p>

Localization of help.html and help-filed.html files

The default help.html is 中文版. Then create the help_xx.html file for the xx language.

Translation

Translation tool: Command line resource file translation tools (Https://wiki.jenkins-ci.org/display/JENKINS/Translation+Tool)

Translation Assistance Plugin:adds A dialog box in Jenkins to translate and send missing keys.

Stapler plugin for IntelliJ idea: Use reflection to extract resources from Java code to the properties file (MVN compile will show an error before compiling).

NetBeans Plugin for Stapler

What to translate

    • Messages.properties
    • Jelly file. You can call MVN stapler:i18n-dlocal=fr to generate a skeleton file *_fr.properties, so the entry value is empty. If the file already exists, add a new entry that does not exist before. Entries that are left blank are rolled back to the default locale.
    • static HTML resources. Foo_xx.html

Translation Completion Report

http://www.simonwiest.de/glottr/report/

Jenkins in Jelly Foundation, hyperlinks, internationalization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.