Unit 3 - DO
Unit 3 - DO
Step 4: Now, Select the destination folder for installation and click Next button.
Paste the password in the Administrator password field on the Unblock Jenkins page
and click Continue to proceed.
Step 3: Now, enter the required information on the Create First Admin User page. Click
Save and Continue to proceed.
Step 4: On the Instance Configuration page, confirm the port number you want
Jenkins to use and click Save and Finish to finish the initial customization.
Step 3: Enter the item name on the next screen, I have given the name as welcome.
Then clicked on Freestyle project and then clicked the ok button.
Congratulations!!! we have executed our first Jenkins Job in Java using Jenkins.
Types of Jobs:
There are different types of jobs available which are intended for different purposes.
1. Freestyle Project: Jenkins freestyle projects allow users to automate simple
jobs, such as running tests, creating and packaging applications, producing
reports, or executing commands. Freestyle projects are repeatable and contain
both build steps and post-build actions.
2. Maven Project: For managing and building the Maven projects using Jenkins,
this type of Job is used.
3. Pipeline: The pipeline job is used when working on long running activities.
4. Multi-Configuration Project: For the projects that require multiple
configurations, this option is selected for creating the Jenkins job.
5. Github Organization: If your project is hosted on GitHub, this job type allows
Jenkins to automatically scan and build repositories within a GitHub
organization.
Build Triggers:
The Build trigger option can be seen in Jenkins Configuration settings.
These are the most common Jenkins build triggers:
Trigger builds remotely: If we want to trigger our project built from anywhere
anytime then we should select Trigger builds remotely option. When we
select the option “Trigger builds remotely” then we need to provide an
authorization token.
Build after other projects are built: If your project depends on another
project build then you should select Build after other projects are built option
from the build triggers. In this option, we must specify the project name in
projects to watch field section.
Build periodically: If you want to schedule your project build periodically then
you should select the Build periodically option from the build triggers. You
have to enter the schedule for periodic building using cron expression. Each
line consists of 5 fields separated by TAB or whitespace. Cron is a command-
line utility that allows the developers and system administrators to schedule
the tasks that nm in the background at regular intervals. The different fields of
cron expression are as follows -
MINUTES - Minutes in one hour (0 - 59)
HOURS - Hours in one day (0-23)
DAYMONTH- Day in a month (1-31)
MONTH - Month in a year (-12)
DAYWEEK - Day of the week (0 -7) where 0 and 7 are Sunday
The *specifies all the valid values.
M-N defines a range of values.
M-NIX or */X -defines the steps by intervals of x through the specified
range.
A,B, ... Z- enumerates multiple values.
An empty line that starts with a # symbol is treated as a comment and will
be ignored.
For example-
# every single minute
*****
# every fifteen minutes (perhaps at :07, :22, ·37,:52)
H/15 * * * *
# every ten minutes in the first half of every hour (three times, perhaps at
:04, :14, :24)
H(0-29)/10
# once every two hours at 45 minutes past the hour starting at 9:45 AM
and finishing at 3 :45 PM every weekday.
45-16/2 * * 1-5
GitHub hook trigger for GITScm polling: A webhook is an HTTP callback, an
HTTP POST that occurs when something happens through a simple event-
notification via HTTP POST. GitHub webhooks in Jenkins are used to trigger
the build whenever a developer commits something to the branch, on GitHub.
Poll SCM :Poll SCM periodically polls the SCM to check whether changes were
made(i.e. new commits in GitHub repository) and builds the project if new
commits were pushed since the last build. We must schedule the polling
duration in the scheduler field. Using the cron expressions we can specify the
schedule.
INTRODUCTION TO PLUGINS:
For enhancing the functionality of Jenkins, we use plugins.
There are thousands of different plugins which can be installed on Jenkins
controller or can be integrated with some build tools, cloud providers and so on.
A plugin is written in Java.
Plugins use their own set of Java Annotations and design patterns that define how
the plugin is instantiated, extension points, the function of the plugin and the UI
representation in the Jenkins Web UI.
Benefits of using Plugins:
Following are some benefits that are observed when the Jenkins plugins are used
1. Extended Functionality: Plugins can be used to add new features to Jenkins. Many
plugins are open-source and maintained by the Jenkins community. This means you
can benefit from the contributions and improvements made by a large user base.
2. Task Automation: Plugins can be used to automate various tasks related-to
software development such as building, testing, deployment of library files to
executable environment.
3. Scalability: We can add or remove the plugins as per the requirements of our project
and thereby Jenkins meets the requirements of organization.
4. Security: Jenkins plugins are useful to make the job secure by integrating with
security tools, vulnerability scanners.
5. Continuous Improvement: Jenkins is an automated tool. Developers continuously
create new plugins or improve the existing ones. Thus continuous improvement is
made with latest technologies.
6. Increased Flexibility: Plugins can be used to increase. the flexibility of Jenkins. For
example, Amazon EC2 plugin allows to deploy the application from cloud platform or
Gitplugin allows you to deploy the application from GitHub repository. There are
various ways by which the desired activity can be carried out in Jenkins.
Adding Plugins to Jenkins:
The simplest and most common way of installing plugins is through the Manage
Jenkins > Plugins view, available to administrators of a Jenkins environment.
Locate the desired plugin from the list or else, you can search for the plugin by
typing plugin’s names. Suppose we wish to install HTML Publisher plugin then we
can either locate it in the list or we can simply type the name of that plugin in the
search window.
Then click Install button which is present at the top right corner. The plugin gets
installed.
Once the Jenkins Git Plugin is installed and configured, our Jenkins build jobs can
poll any local or remote repositories for new commits. The cron expression is used
for job scheduling periodically.
Example Demo:
Step 1: Create a simple Java program. I have created a folder named MyJavaPrograms
and inside it created a simple Java program as follows
test.java
public class test
{
public static void main(String args [])
{
for (int i=1; i<=5; i++)
System.out.println (“Welcome Anuradha”);
}
}
Step 2: Open the command prompt, switch to that folder and execute the above Java
program. It is illustrated by following screenshot.
Step 3: Now we will create a Git repository and push this repository on GitHub.
First of all we will initialize the Git repository my using git init command.
Now we will create a repository on GitHub and then push the above committed Git
repository on the GitHub.
Open a web browser, and login to www.GitHub.com. Create a repository by the name
MyJavaPrograms.
then copy the URL of this repository.
HTTPS SSH https://github.com/AnurdhaP/yJavaPrograms.git
Now open the command prompt window and go to the MyJavaPrograms directory and
issue the following command.
git remote add origin https://github.com/AnurdhaP/MyJavaPrograms.git
then push the Git to GitHub repository using the command
push -u origin master
It is illustrated as follows
Now it we refresh the repository on GitHub then we can see our test.java and test.class
programs are present in that repository.
Step 4: Now create a job in Jenkins that makes use of GitHub plugin in order to access
the GitHub repository.
And configure the Jenkins job as follows -
Save this configuration.
Step 5: Now if we build this job the output that we see is as follows on Console Output.
Step 6: Now go to GitHub repository and make some changes to your test.java file and
commit these changes.
Step7: Now, if you check on the Jenkins page, it automatically executes the above
updated test.java file and creates a build. It is as follows.-
Note that Jenkins builds the job automatically on every GitHub repository changes
we need not have to build it explicitly.
Parameter Plugin:
We can configure our job by adding parameters. The Jenkins can then be build with
parameters. We can add parameters to either existing job or we can create a new job
with parameters.
Example Demo:
Step 1: Click on New item and create a job. I have created a job by the name Welcome.
Step 2: Click on the existing job and configure it with parameters.
Step 3: Check the option “This project is parameterized”. Select the String
Parameter. Create some string parameter. I have created a parameter named Username
and default value to it.
Step 4: Under the Build Steps section, using echo command I tried to display the
parameter value.
Step 5: Click on Apply and then Save.
Step 6: Select Build with parameters option.
Thus we set variety of parameters to the Jenkins job. We can set the Boolean parameter,
choice parameter, credentials, file parameter, password parameter and so on.
Step 5: Now, open the pom.xml file and add the dependencies such as testing and
junit. Also add the Maven-surefire plugin and maven-compiler plugin.
Step 6: Now, open the Maven project’s src folder, inside the test folder create some
package and create a Java class file. In my case I have created a package named
myPackage and under this package I have created a java file named myTestPage.java.
myTestPage.java
package myPackage;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class
myTestPage
{
@Test
public void myFun ()
{
System.setProperty (“webdriver.chrome.driver,”./drivers/chromedniver.exe”);
WebDriver driver = new ChromeDriver ();
driver.get (“https://google.com”);
String title = driver.g etTitle ();
System out.println (“Hey Anuradha, the tile of this page is: ”+title);
driver.quit ();
}
}
Program Explanation: In above program, we have written one test case by the function
myFun. In this function, using the Chromedriver which we have installed, we open the
web page google.com Then we try to get the tile of this page and display it on the console
using System.out statement. Finally, we quit the driver.
Step 7: Right click on the Project name in Project Explorer window, Run As-> Maven
Test.
Step 8: Now, locate the Java file myTestPage.java and right click Run As->TestNG
Test. It is as follows -
Step 9: We will get the output as follows -.
Step 10: Now, we will open the Jenkin’s page and create the HTML Publisher report for
the above SeleniumDemo project. The prerequisite to this activity is that the
HTMLPublisher report plugin must be installed in Jenkins.
Click on New Item, Enter the Item Name and select as Freestyle project, I have
given the name HTMLReportDemo.
Then click on configure. Write the suitable description in General section.
Then in Build Steps and Add Build steps as Invoke top-level Maven targets
provide the Maven version, and under goals write clean test.
Under Post Build Actions, click on Add Post Build Action and select Publish
HTML Report. Now give the path of index.html file which is created by Selenium
testing framework in Maven. It is the path of test-output folder, Also give some
suitable HTML report title.
Step 11: Click on Apply and then Save. Now build this project.
Step 12: On successful build, it creates the HTML Report as follows
Thus using HTML Publish Report Plugin we can successfully generate HTML report
of some testing framework application.
Troubleshooting: Sometimes, the raw file is displayed as HTML report. To get the
HTML formatted report we must click on Manage Jenkins section, scroll down and
locate Script Console section. Click on it.
Step 7: Now we have to copy test.class file from the workspace of Appl to another job.
For that purpose we will create another Job named App2 by clicking New Item. Select
the Freestyle Project.
Step 8: Then configure the Build Steps by selecting the option Copy artifacts from
another project as follows -
First of all give the name of the project from which you want to copy the files. In
mycase it is Appl.
Then select the option “copy from WORKSPACE of latest completed build”.
Give the regular expression **/*.* Here’s a breakdown of what **/*.* means:
**: The double asterisk (**) is a wildcard that matches zero or more directories
and subdirectories. It's often used to recursively search through all directories
and subdirectories.
/: The forward slash (/) is used as a directory separator, typically on Unix-like
systems.
*.*: This part of the regular expression is used to match files with an extension.
In regular expressions, the symbol represents “zero or more” of the preceding
character or pattern, and the . character is used to match any character. So, *.*
essentially matches any file with any extension.
So, when you use the regular expression **/*.* in a Jenkins build configuration,
you are instructing Jenkins to include all files with any extension (*.*) located in
any directory and subdirectory (**) within the workspace or specified location.
Add one more Build Step and select Execute Windows batch Command. Give the
command dir so that the name of files and directories that are copied from App1 to
App2 will be displayed on the Console.
Click Apply and Save.
Step 9: Now Build this project (App2). The output will be as follows
Note that the git repository and the files from that repository are copied from the
workspace of App1 to App2. Also note that test.class and test.java files are copied to
the workspace of App2.
Extended Choice Parameters:
The extended choice parameters allows you to create more advanced and dynamic
choice parameters in your Jenkins build jobs.
Features:
Parameter types: The extended choice parameter plugin extends the basic
parameter types in Jenkins by offering various advanced parameter types. These
include:
1. Single Select: Allows users to choose a single option from a list.
2. Multi-Select: Allows users to select multiple options from a list.
3. Checkboxes: Presents options as checkboxes for multiple selections.
4. Radio Buttons: Presents options as radio buttons for single selection.
5. PTT (Progressive Trace Text): Provides a text box with autocomplete
suggestions based on the user’s input.
Dynamic generation of choices: One of the most powerful features of this plugin is
the ability to generate choices dynamically. You can define scripts using Groovy,
JavaScript, or other scripting languages to compute the list of choices based on
certain conditions, external data sources or calculations.
Integration with other plugins: The extended choice parameter plugin can be
integrated with other Jenkins plugins, enabling more complex and customized
workflows.
How to install extended choice parameter plugin?
Start the Jenkins tool by entering login and password. Click on Manage Jenkins. Click
on Plugins. Search for extended choice. The plugin name will be displayed.
Click install, Once it gets installed the Success message will be shown.
Example Demo:
Step 1: Create a new Job or select the existing Jenkins Job.
Step 2: Select the option This project is parameterized and select the option Extended
Choice Parameter.
Step 3: Click Apply and Save.
Step 4: Click Build with Parameters, and you will get
Just click Next button without selecting any archetype over here. Another window will
appear as given below - Select the maven-archetype-webapp.
Then click the Next button. Provide the Group Id and Artifact Id as per your choice.
Click on libraries path and click on JRE System Libraries and Edit it by giving the path
of JDK. (Note that Java must be installed prior to this Maven web application building)
Just open the index.jsp file and edit it. I have edited it as follows -
index.jsp
<IDOCTYPE html>
<html>
<body>
<h2> Welcome Anuradhal! </h2>
</body>
</html>
Step 4: Now edit pom.xml by adding some dependencies.
Add Jakarta Servlet dependency in pom.xml file. The dependency code can be
obtained from mvrepository.com. The code for the dependency is as follows -
<!-- https://mvrepository .com/artifact/jakarta.servlet/jakarta.serv let-api -->
<dependency>
<groupld> jakarta .servlet </groupld>
<artifactld> jakarta.serv let-api </artifactld>
<version> 6.0.0 </version>
<scope> provided </scope>
</dependency>
Step 5: Now right click on Project name in the project explorer and click Run As
Select Maven install. This will build your web application.
The Build Success message will be displayed on the Console window.
Step 6: Right click on project name and select Run As-> Run on Server. This will lead
to configuration of Tomcat folder which is installed on your local machine.
Once the Tomcat server gets started, following output can be viewed in the web browser.
Stage 2: Pushing the Maven Web Application on Git
The prerequisite here is to have a account on Github.
Now we will use following steps to push the above Maven Web app on GitHub. This
is how we try to link our web application to Github.
Step 1: Sign in the Github.com by entering your username and password.
Give the repository name. Note that this name must be the same name as of your Maven
project (we have created in Stage1).
Click on-New and then type the name of the Repository
Step 2: Now click on Settings ->Developer Settings, click on Personal access tokens.
Click on Generate New Token in order to create a token. This token is generated so that
any third party application can access to this repository without re-entering the login
name and password.
I have given the token name as mytoken and no-expiration to this token. Selected the
repo checkbox.
Then click on Generate Token button. A token will get generated.
Step 3: Now in the Eclipse IDE, from the menu bar, click on Window->Show view-
>other. Select the Git Repositories.
Step 4: On the GitHub.com, just copy the URL link of your repository.
Step 5: Now, inside the Eclipse, click on Clone a Git repository.
Click on Finish button. Now from menu bar of Eclipse, select Window->show
view->other. Select the Git Staging. Now drag the index.jsp and pom.xml file from
Unstaged Changes area to Staged Changes.
Now type some commit message and click on Commit and Push.
Then a pop up window will appear on which as a user-name we have to enter the
Github’s user email id. And as a password it has to copy the Personal access token
from Github.
Thus the copied token is pasted as a password in Eclipse. Check the checkbox Store in
Secure Store. Then click Log in button.
Then Push the app.
Step 6: Now, in the Web browser just refresh the GitHub.com. We can now see our Web
Application on Git Hub.
Step 3: In the Description box, write the description of your project. Then select option
GitHub project and enter the URL of your repository which you have created in Stage 2.
This URL can be copied from the GitHub.com by opening your repository.
There are no credentials as your repository is public. If the repository is private then we
have to provide the credentials of user name and password of our GitHub account.
Step 5: If the branch of your GitHub repository is a master branch then keep it as it is.
Step 6: In the Build Trigger section select the option Poll SCM and give five stars with a
space in between. The meaning of this is that when ever you make changes in your
GitHub repository then the Build will be triggered in Jenkins. And after each one minute
Jenkins will make a Build. It will get your code from Git Repository, will make a War file
with the help of Maven command. The five stars indicate a one minute time frame.
Then give the Tomcat URL. All the above activities are illustrated in following screenshot.
Finally Click Apply and Save.
Step 9: Start your local Tomcat server. Then on Jenkins page, click the Build Now for
building the automation.
On Successful Build we get following output on Console.
Step 10: Open the web browser arid enter the URL of your Web Application.
Step 11: If you make any changes in your repository file on GitHub then accordingly
Build will be generated by Jenkins automatically and if you refresh the Web application
URL, those changes will be reflected automatically.
Thus when developers edit the code, those changes will be automatically reflected as an
output, if we use Jenkins as an automated tool. Thus it facilitates us with Continuous
Integration and Continuous Development!!!
CREATING A JENKINS BUILD AND JENKINS WORKSPACE:
In Jenkins Build is a process of compiling the source code, running tests, creating
deployable artifact such as binary executable, a library or web application.
Following activities occur during the Jenkins Build process.
1. Source Code Retrieval: In this step the source code is retrieved by the version
control system such as Git or Subversion. Sometimes, the source code can also
be retrieved from the local storage disk.
2. Workspace Creation: Jenkins creates a working directory which is known as
workspace where it stores all the files necessary for the build process.
3. Build Environment Configuration: Jenkins allows to specify the files, libraries
and dependencies required for the build, which is called configuration process.
4. Build process: Following activities are carried out during the actual build
process -
a. Compilation: Source code is compiled into executable binaries or libraries.
b. Testing: Running test cases to check the correctness of the source code.
c. Artifact Generation: The artifacts such as jar or war files are generated.
5. Reporting: Jenkins collect and generate reports during the build process. For
instance the HTML report can be published by Jenkins.
6. Artifact Archiving: Jenkins collect the artifact that are ready for deployment.
7. Deployment: The artifacts that are deployed in the executable environment. For
example if the war file is generated during the Jenkins Build can be deployed on
the Tomcat container for execution.
8. Logging: Jenkins maintains detailed logs of each build, including console
output and build artifact.
Steps to Create Jenkins Build:
Step 1: Open the web browser and access the web interface of Jenkins by providing the
username and password.
Step 2: Click on “New Item” on the Jenkins dashboard to create a new job or select the
already created job. Once job is ready, click on Build Now.
Step 3: If there exists some errors, then Jenkins will display the errors on Console
output otherwise the actual output can be seen on the console.
The workspace for the Jenkins job gets created automatically. Sample workspace is
represented by following screenshot.