0% found this document useful (0 votes)
6 views91 pages

OOP Java Programming II

The document outlines the course IT 313: OOP Java Programming II, focusing on automation concepts and techniques in Java. It covers the definition, benefits, and types of automation, as well as specific Java automation methods such as using the Robot class, Reflection, and code injection into the JVM. Additionally, it introduces keyboard and mouse automation, providing practical examples and programming tasks for students.

Uploaded by

Roxeverlyne
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views91 pages

OOP Java Programming II

The document outlines the course IT 313: OOP Java Programming II, focusing on automation concepts and techniques in Java. It covers the definition, benefits, and types of automation, as well as specific Java automation methods such as using the Robot class, Reflection, and code injection into the JVM. Additionally, it introduces keyboard and mouse automation, providing practical examples and programming tasks for students.

Uploaded by

Roxeverlyne
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

IT 313

OOP Java Programming II


TABLE OF CONTENTS
Lecture Notes
Cover .......................................................................................................................I
Table of Contents....................................................................................................II
Lecture Note ..........................................................................................................III
Chapter 1: Introduction to Automation
Chapter 2: Keyboard and Mouse Automation
Chapter 3: Automation with Selenium
Chapter 4: Automation Framework
Chapter 5: Building Reports using Jasper
Lecture Notes
Chapter I

Chapter 1: Introduction to Automation


Contents

1. What is Automation?

2. Benefits and Types of the Automation

3. Automation in Java

Objectives

Basic concept of automation is presented in this chapter. First we start with the definition and its process
of the automation, then we move to the advantages of using the automation techniques and its various
types. Finally, we jump into the automation implemented in Java programming, especially the approaches
used in this semester.

1. What is Automation?

Automation technologies have cut costs for businesses, help scale company operations, and greatly
boosted efficiency.

Automation is a technology that enables processes to occur without human intervention. Essentially,
“automating” tasks mean creating a situation where the system (or part of a system) will run by itself. This
includes enterprise applications such as business process automation (BPA), IT automation, network
automation, automating integration between systems, industrial automation such as robotics, and
consumer applications such as home automation and more.

For the advancement of this technology, the use of computers and computer-related technologies has
become more and more crucial. As a result, automated systems have grown more complicated and
intelligent. In many aspects, the capabilities and performance of advanced systems are superior to those
of humans to carry out the same tasks.

Code: IT 313, Subject: OOP Java Programming II 1|Page


Chapter I
2. Benefits and Types of the Automation

Early on, automation mostly referred to physical machinery that helps carry out laborious tasks such as
printing text or manufacturing cars. This has drastically shifted in the modern age. Now, enterprises and
individuals can adopt software solutions from third-party companies to automate tasks.

These tasks could be as simple as automated emails being sent at specific times, or as complex as
preventing global cyberattacks from occurring. Automation is a key driver of digital transformation. Most
of the solutions that businesses adopt to upgrade and modernize their operations are automation
solutions.

Automating workflows and processes can bring about a number of benefits for businesses, including:

• Scalability

• Cost-cutting

• Greater efficiency

• Employee upskilling

• Reduced errors

• Streamlined functions

• Greater accountability

• Improved communication

Examples of Automation

Seeing automation in action can help businesses better understand the actionable benefits it can bring to
operations. These include:

• Customer Service: The first and most common example of automation comes in the customer
service industry. Businesses can leverage automation to automate responses to customers, then

Code: IT 313, Subject: OOP Java Programming II 2|Page


Chapter I
leverage user data to provide more tailored responses. This helps businesses not only respond
immediately to customers, but also in a highly tailored manner.

• Payroll: HR departments have greatly benefited from automation with HR software solutions
automating payroll processing. Advanced solutions help verify employee data, validate
timesheets, and confirm earnings, reimbursements, and deductions. Even benefits administration
can be automated. This helps take massive amounts of stress off the HR department when
onboarding or offboarding employees.

• Cybersecurity: Perhaps most important, automation can help businesses with strengthening their
cybersecurity. Security is where AI and automation truly show their full potential when working
together. Advanced solutions can train themselves and learn from human behavior, as well as
previous attacks, to prevent any further breaches.

• Greater Human Capital: Menial tasks have historically gotten in the way of employees reaching
their true potential. When clerical tasks clog up hours of work, business efficiency takes a hit.
Industries are aware of this as well. Work Market reported that 53% of employees feel they can
save up to two work hours a day through automation. Offering even more potential, 78% of
business leaders stated automation could free up to three work hours a day.

Types of Automation

• Basic Automation

Basic or task automation takes simple, repetitive tasks and automates them. This level of automation is
about digitizing work by using automation to streamline and centralize routine tasks, such as using a
shared messaging system instead of having information in disconnected silos. This helps eliminate errors,
accelerate the pace of transactional work, and free up people’s time to do higher value, more meaningful
work. Robotic process automation (RPA) is an example of basic automation.

• Process Automation

Process automation takes more complex and repeatable, multi-step processes by integrating with
multiple systems and automates them. This level of automation manages business and IT processes for
uniformity and transparency. Using process automation can increase productivity and efficiency within
your business. It can also deliver new insights into business and IT challenges and suggest solutions using
rules-based deaccessioning. Process mining and workflow automation and Business process management
(BPM) are examples of process automation.

• Intelligent Automation

The most advanced level of automation is intelligent automation. It combines automation with artificial
intelligence (AI) and machine learning (ML) capabilities. This means that machines that automations can
continuously “learn” and make enable better decision making and actions based on data from past
situations they have encountered and analyzed. For example, in customer service, virtual assistants
powered by AI/ML can reduce costs while empowering both customers and human agents, creating an
optimal customer service experience. AIOps and digital workers are examples of intelligent automation.

Code: IT 313, Subject: OOP Java Programming II 3|Page


Chapter I
3. Automation in Java

Java Automation technique deals with code that can be used to control the execution of the program. In
here, we only focus on two scenarios; namely process automation and testing automation.

Approaches for Automating

The following approaches are available for automating a Java Application:

1. Using robot class to automate

2. Using reflection to launch the application

3. Injecting code into another application

RPA vs Automation Testing

RPA focuses on automating business processes such as mimicking the tasks and actions while keeping in
mind various scenarios through artificial intelligence. Test automation on the other hand requires strict
rules and focuses on different scenarios related to the testing of software.

A. Using Robot Class (Imperfect Approach)

Robot is one the class provided by Java to simulate mouse click / keyboard events. We can use this class
to automate not only Java but any application.

However, with Robot, issue arises while providing the location coordinates. Robot basically simulates a
mouse click at the current position of the mouse. Hence hard coding the mouse location is not a good
idea as the location depends on whether the application is opened to full screen. If not full screen, then
what is the x, y position of the top-left end of the application? Moving the application, a little on the screen
changes all the x, y positions of all components. Also if screen resolution is changed then also x, y positions
of each component will be changed. Another disadvantage is that users will have to keep the application
on top and wait until the automation finishes. This blocks valuable user time.

Here are some pros/cons of this approach in brief:

Automation Possible Scenarios

Automating applications will be possible by using this approach if we consider the following scenario.

Code: IT 313, Subject: OOP Java Programming II 4|Page


Chapter I
• Screen resolution is same across all desktops

• Each application opens with fixed width and height or application opens in maximized state.

• If application is not opening in maximized state then (x,y) co-ordinate for the specific application
remains the same for each run.

• User should not perform any other operation while automation is running.

Assuming the above conditions are met, we can automate not only java, but any technology application.
This technique is solely dependent upon where the application is on the screen. So any application in any
technology is possible to automate.

Advantages

• Perform Mouse click at specified location.

• Dispatch keyboard events (it is assumed that focus is already present at required field.)

Disadvantages

• When the application is moved in the screen then this method cannot be used

• User needs to wait till the operation is completed

• If something pops up while automation is running, then automation will fail

• If screen resolution is changed then this approach will fail

• Background processing of the automation is not possible

• Retrieving values from any field is not possible

So simulating clicks on the UI is not a good approach and we will have to go inside Java to get more
accessibility and access actual objects to perform the required operation.

B. Using Reflection (Imperfect Approach)

The second approach manipulates how Java applications get launched using the JVM.

This approach uses the Reflection API. In this approach, instead of JVM launching the application, it is
routed through the custom launcher. Custom launcher reads the main jar file and also loads all
dependency jar files. Then it loads the entry class (class with main method) and executes main method
from the class.

As custom launcher has launched the application using Reflection, it has control over the JVM on which
the application is running and so it can access any of the UI component objects from the application. Once
the object from the UI is accessible, it is easy to perform any required operation on the object. These
operations can include setting text, getting text, dispatching events, etc.

Though at this stage Java Reflection looks like a favorable approach, further investigation reveals issues
while automating applet applications. Specifically, in scenarios where an applet takes dynamic parameters
from the web page or where the applet is launched using complex logic on a web page, it is not feasible

Code: IT 313, Subject: OOP Java Programming II 5|Page


Chapter I
to use this approach. Also the Java applications, which are wrapped as exe, are also not possible to load.
For thick client applications where launching java applications has complex steps, this approach cannot
be used or it may require more complex coding to be done.

Automation Possible Scenarios

Thick client applications, which can be run using a simple command java –jar UIApplication.jar, can be
automated easily. If the command has more properties set in order to run the application with –D options
then it will be difficult to automate, or it will need more effort to make it work.

Applet applications with simple tag <Applet class=”my.applet.example.ClassName” width=”500”


height==”300” /> can be automated. If the applet tag is generated using JSP or if it is retrieved from the
application server after few steps, then it becomes difficult. This approach goes to discarding state when
a user wants to automate an applet, which takes input as parameter like token from an HTML or JSP page.

The same is true in the case of JNLP. Applications with a simple static JNLP file can be automated, but
difficulties start when JNLP files are generated dynamically.

Advantages

• Perform Mouse click for specified object


• Dispatch keyboard events for specified objects
• Retrieving value from specified objects
• Does not depend on screen resolution/position of application on screen
• Background processing is possible
• As this runs in background, user can simultaneously work on other things
Disadvantages

• All Applets cannot be automated using this approach


• Dynamically generated JNLP files cannot be automated
• Thick client apps with complex launching logic will be difficult to automate
• Thick client apps, which use batch file to launch and having complex launch logic cannot be
automated
• Jar files wrapped as exe cannot be automated
• It is required to give extra permission for socket connection and listening to AWT events and
depending on the app may require giving all permission as well
C. Injecting Code into Running JVM (Best Suited Approach)

Java provides 2 approaches to inject code into running JVM. These are the concepts of Java
instrumentation and attaching Instrumentation Agent.

We will discuss these concepts in brief here.

Java provides a class called java.lang.instrument.Instrumentation, which can be used to inject code in
running JVM. Code can be injected in 2 ways.

Using Agentmain Method

For more detail about using this method, refer to Java Instrumentation from the Oracle docs. This type of
injection injects the code into running JVM. Here the assumption is that the third party application is

Code: IT 313, Subject: OOP Java Programming II 6|Page


Chapter I
already up and running. Code can be injected into the running application by creating a Java agent jar file
with the agentmain method. Once the code is injected, the agentmain method gets called. Automation
related code can be executed considering the agentmain method as the entry point. Now the code written
in agentmain and the third party application both reside in the same JVM. So automation code can directly
access objects from the running third party application. More detail about accessing objects from a third
party application and performing operations on it are explained in later sections.

Still there are some restrictions to using this method e.g., not all JVMs support this type of code injection.
Also we require the JDK to be installed in order to use this type of code injection.

Using Premain Method

For more detail about using this method, read Java Instrumentation from the Oracle docs. This type of
injection injects the code while starting JVM. Here, the Java agent runs even before third party
application. As the method suggests, the premain method gets called even before the main method of
the third party application. Here, the same as agentmain, Automation related code is executed from the
premain method. These two run in the same JVM so Automation code can get ahold of UI objects
easily. More detail about accessing objects from third party applications and performing operations on it
are explained in later sections.

Advantages/Automation Possible Scenarios

All kinds of Java applications are possible to automate using this approach. The only pre-requisite is that
before launching the app, environment variable JAVA_TOOL_OPTIONS is required to set with value as –
javaagent:” <PATH TO JAVAAGENT>”. The variable can be set as process level, user level, or system level
depending upon the requirement.

Advantages

• Perform Mouse click for specified object


• Dispatch keyboard events for specified objects
• Retrieving value from specified objects
• Does not depend on screen resolution/position of application on screen
• Background processing is possible
• As this runs in background, user can simultaneously work on other things
• All kind of desktop Swing/AWT applications can be automated
• All JNLP applications can be automated
• All applet applications can be automated
• Java applications wrapped as exe can be automated
• Dynamically generating JNLP applications can be automated
• Two or more applets embedded in one html can be automated
Disadvantages

• It is required to give extra permission for socket connection and listening to AWT events and
depending on the app may require giving all permission as well.

Code: IT 313, Subject: OOP Java Programming II 7|Page


Chapter I
Homework

1. What is Automation? Why is it important?

2. Describe the different types of automation.

3. What is the Automation in Java? And what types of the automation we are going to focus?

Code: IT 313, Subject: OOP Java Programming II 8|Page


Chapter II

Chapter 2:
Keyboard and Mouse Automation
Contents
1. Automating Mouse Operation

2. Automating Keyboard Operation

3. Mouse Move for Keeping System Awake

4. Generating jar, bat and exe File

Objective
The basic mouse and keyboard automation operation is introduced in this chapter. First we automate on
opening some applications, moving mouse and using several keypress of the keyboard. Then we make the
program to automate the typing and saving files. Finally, we generate the program file into jar, bat and
exe file.
1. Automating Mouse Operation

A. Opening a Program

Common programs you can launch from Command Prompt include:

• File Explorer: explorer


• Calculator: calc
• Notepad: notepad
• Character Map: charmap
• Paint: mspaint
• Command Prompt (new window): cmd
• Task Manager: taskmgr
• Command Prompt: cmd
• Windows Media Player: wmplayer
• MS Word: winword
......

Code: IT 313, Subject: OOP Java Programming II 9|Page


Chapter II

• Run Program using Java automation:

import java.awt.*;

import java.io.IOException;

public class RobotMouse{

public static void main(String[] args)

throws AWTException, IOException{

Runtime.getRuntime().exec("cmd /c start control");

robot.delay(2000);

• Basic Key Operation:

package org.example;

import java.awt.*;

import java.awt.event.*;

import java.io.IOException;

public class RobotMouse{

public static void main(String[] args)

throws AWTException, IOException{

Robot robot = new Robot();

Runtime.getRuntime().exec("cmd /c start control");

robot.delay(2000);

// Press Key

robot.keyPress(KeyEvent.VK_ALT);

robot.keyPress(KeyEvent.VK_SPACE);

// Release Key

robot.keyRelease(KeyEvent.VK_ALT);

robot.keyRelease(KeyEvent.VK_SPACE);

robot.delay(3000);

// Maximize thr tab

Code: IT 313, Subject: OOP Java Programming II 10 | P a g e


Chapter II
robot.keyPress(KeyEvent.VK_X);

robot.keyRelease(KeyEvent.VK_X);

robot.delay(2000);

// move mouse to the coordination og 2000 and 0

robot.mouseMove(2000,0); // Screen 1920 * 1080

• Press and release left mouse

....

robot.delay(3000);

robot.mousePress(InputEvent.BUTTON1_MASK);

robot.delay(3000);

//release the left mouse

robot.mouseRelease(InputEvent.BUTTON1_MASK);

• Type google.com then enter

..........

robot.delay(3000);

Runtime.getRuntime().exec("cmd /c start firefox.exe");

robot.delay(3000);

robot.keyPress(KeyEvent.VK_G);

robot.keyRelease(KeyEvent.VK_G);

robot.keyPress(KeyEvent.VK_O);

robot.keyRelease(KeyEvent.VK_O);

robot.keyPress(KeyEvent.VK_O);

robot.keyRelease(KeyEvent.VK_O);

robot.keyPress(KeyEvent.VK_G);

robot.keyRelease(KeyEvent.VK_G);

robot.keyPress(KeyEvent.VK_L);

Code: IT 313, Subject: OOP Java Programming II 11 | P a g e


Chapter II
robot.keyRelease(KeyEvent.VK_L);

robot.keyPress(KeyEvent.VK_E);

robot.keyRelease(KeyEvent.VK_E);

// Dot

robot.keyPress(KeyEvent.VK_PERIOD);

robot.keyRelease(KeyEvent.VK_PERIOD);

robot.keyPress(KeyEvent.VK_C);

robot.keyRelease(KeyEvent.VK_C);

robot.keyPress(KeyEvent.VK_O);

robot.keyRelease(KeyEvent.VK_O);

robot.keyPress(KeyEvent.VK_M);

robot.keyRelease(KeyEvent.VK_M);

robot.keyPress(KeyEvent.VK_ENTER);

robot.keyRelease(KeyEvent.VK_ENTER);

• Type Weather today then enter

......

robot.delay(3000);

robot.keyPress(KeyEvent.VK_W);

robot.keyRelease(KeyEvent.VK_W);

robot.keyPress(KeyEvent.VK_E);

robot.keyRelease(KeyEvent.VK_E);

robot.keyPress(KeyEvent.VK_A);

robot.keyRelease(KeyEvent.VK_A);

robot.keyPress(KeyEvent.VK_T);

robot.keyRelease(KeyEvent.VK_T);

robot.keyPress(KeyEvent.VK_H);

robot.keyRelease(KeyEvent.VK_H);

robot.keyPress(KeyEvent.VK_E);

Code: IT 313, Subject: OOP Java Programming II 12 | P a g e


Chapter II
robot.keyRelease(KeyEvent.VK_E);

robot.keyPress(KeyEvent.VK_R);

robot.keyRelease(KeyEvent.VK_R);

robot.keyPress(KeyEvent.VK_SPACE);

robot.keyRelease(KeyEvent.VK_SPACE);

robot.keyPress(KeyEvent.VK_T);

robot.keyRelease(KeyEvent.VK_T);

robot.keyPress(KeyEvent.VK_O);

robot.keyRelease(KeyEvent.VK_O);

robot.keyPress(KeyEvent.VK_D);

robot.keyRelease(KeyEvent.VK_D);

robot.keyPress(KeyEvent.VK_A);

robot.keyRelease(KeyEvent.VK_A);

robot.keyPress(KeyEvent.VK_Y);

robot.keyRelease(KeyEvent.VK_Y);

robot.keyPress(KeyEvent.VK_ENTER);

robot.keyRelease(KeyEvent.VK_ENTER);

2. Automating Keyboard Operation

In here, we do the basic automation by automating the keyboard to type some characters by itself.

Open Notepad and type "Welcome"

Code: IT 313, Subject: OOP Java Programming II 13 | P a g e


Chapter II
import java.awt.*;

import java.awt.event.*;

import java.io.IOException;

public class Robot_Keyboard{

public static void main(String[] args)

throws AWTException,IOException{

int keyInput[] = {

KeyEvent.VK_W,

KeyEvent.VK_E,

KeyEvent.VK_L,

KeyEvent.VK_C,

KeyEvent.VK_O,

KeyEvent.VK_M,

KeyEvent.VK_E

};

Runtime.getRuntime().exec("notepad");

Robot robot = new Robot();

// Make the first character upper case and the remaining characters lower case.

robot.keyPress(KeyEvent.VK_SHIFT);

for (int cnt2 = 0;cnt2 < keyInput.length; cnt2++){

if(cnt2 > 0){

robot.keyRelease(KeyEvent.VK_SHIFT);

}//end if

robot.keyPress(keyInput[cnt2]);

robot.delay(500);

Code: IT 313, Subject: OOP Java Programming II 14 | P a g e


Chapter II
• Save the file and name it "sa"

....

robot.keyPress(KeyEvent.VK_CONTROL);

robot.keyPress(KeyEvent.VK_S);

robot.keyRelease(KeyEvent.VK_CONTROL);

robot.keyRelease(KeyEvent.VK_S);

robot.delay(1500);

robot.keyPress(KeyEvent.VK_S);

robot.keyRelease(KeyEvent.VK_S);

robot.keyPress(KeyEvent.VK_A);

robot.keyRelease(KeyEvent.VK_A);

robot.delay(1500);

robot.keyPress(KeyEvent.VK_ENTER);

robot.keyRelease(KeyEvent.VK_ENTER);

3. Mouse Move for Keeping System Awake

We make the computer awake forever by making the move move every 5 seconds in different
coordination.

import java.awt.*;

import java.util.*;

public class Robot_MouseAwake{

public static void main(String[] args) throws Exception{

Code: IT 313, Subject: OOP Java Programming II 15 | P a g e


Chapter II
Robot hal = new Robot();

//hal.mou

hal.mouseMove(1366,0);

hal.delay(5000);

Random random = new Random();

while(true){

hal.delay(5000);

int x= random.ints(0, 1366).findFirst().getAsInt();

int y= random.ints(0, 768).findFirst().getAsInt();

hal.mouseMove(x,y);

System.out.println(x+"*"+y);

4. Generating jar, bat and exe File

A JAR file is a package file format typically used to aggregate many Java class files and associated metadata
and resources into one file for distribution. JAR files are archive files that include a Java-specific manifest
file. They are built on the ZIP format and typically have a .jar file extension.

To create a jar file, please follow the steps below.

Code: IT 313, Subject: OOP Java Programming II 16 | P a g e


Chapter II
1. Go to File -> Project Structure -> Artifacts -> Add -> from modules with dependencies -> Select
java file -> Ok -> Ok

2. Go to File -> Setting -> Build, Execution, Deployment -> Compiler -> Java Compiler -> Target
bytecode version => (17) -> Ok

3. Go to Build -> Build Artifacts -> Build

4. The jar file built successfully and stored at the out folder

To run the jar file, we use two techniques; namely running as bat file and wrapping as exe file.

• bat file

go to the jar filepath -> cmd -> write the following command

java -jar filepath

or

create a notepad name Run.bat by passing the above command

• exe file

1. Go to https://launch4j.sourceforge.net/ to download and install Java executable wrapper software

2. On "Output file": select the destination for the exe output

3. On "Jar" browse to the jar file

4. On "Icon" browse to the ico file extension

5. Select JRE menu, on the "JRE paths", put the path of the java jdk

6. Click on "Setting" then put any name for the file test

7. Done

Code: IT 313, Subject: OOP Java Programming II 17 | P a g e


Chapter II

Code: IT 313, Subject: OOP Java Programming II 18 | P a g e


Chapter II

Homework

1. What is automation? Why is it important?

2. Write a program to make a mouse operation to automate the process of downloading any
software from the website.

3. Write a program to make a Keyboard operation to automate the process of typing a sentence in
MS word and save it.

Code: IT 313, Subject: OOP Java Programming II 19 | P a g e


Chapter III

Chapter 3: Automation with Selenium


Contents

1. Introduction to Selenium

2. Selenium Web Driver

Objective

This chapter mainly focuses on the usage of selenium driver for web automation. First we start with the
overview of the selenium, its advantages and how to install and setup the software to the computer. Then
we move to create various basic automation with maven project such as getting text from the web page,
clicking on button, sending texts to the web, working with tables and alerting in JavaScript.

1. Introduction to Selenium

Selenium is a powerful open-source framework that enables automated testing of web applications across
multiple browsers and platforms. It provides a single interface that lets you write test scripts in
programming languages like Ruby, Java, NodeJS, PHP, Perl, Python, and C#, among others.

The interface used to send commands to the different browsers is called Selenium WebDriver.
Implementations of this interface are available for every major browser, including Mozilla Firefox, Google
Chrome and Internet Explorer.

The main component of the selenium suite is:

• Selenium Integrated Development Environment(IDE)

• Selenium Remote Control(RC)

• Webdriver

• Selenium Grid

Code: IT 313, Subject: OOP Java Programming II 20 | P a g e


Chapter III
With the help of selenium Webdriver, it is possible to request clicking of the browser back and front
buttons, this feature is not available in many automation-testing tools, which is the biggest advantage of
using selenium as an automation testing tool.

Using selenium as a testing tool, we can make quick changes in code, reduce duplication in code, minimize
complication in code and improve code readability. Selenium is more flexible as compared with other
testing tools.

Setting up the Selenium Web Driver

Normally, to setup the Selenium Webdriver, there 4 steps to follow:

1. Create a Maven project

a. Open your IntelliJ IDEA

b. Click on File -> New -> Project - -> Put suitable Name and Location -> Choose Java and
Maven -> Create

c. Right click on java directory (under the src) to create a new java class.

d. Inside the created class, type "psvm" then press "ctrt + space", and then enter

2. Add Selenium-server to the IDE

a. Go to https://www.selenium.dev/downloads

b. Click on "Latest stable version 4.10.0" (updated frequently)

c. On Intellij IDea, click on File -> Project Structure -> Module - > Dependencies -> Add ->
Jar or Directories.

d. Browse to the path of the selenium-server that you have downloaded

3. Download a web driver (chrome driver)

a. Go to https://chromedriver.chromium.org/downloads

Code: IT 313, Subject: OOP Java Programming II 21 | P a g e


Chapter III
b. Choose a suitable version

c. Move to the path of your project

4. Write some code to test the automation

WebDriver driver = new ChromeDriver();

System.setProperty("webdriver.chrome.driver", "chromedriver.exe");

driver.manage().window().maximize();

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

driver.get("https://www.wikipedia.org/");

//driver.close();

Now you can run the java class and you will see that Chrome browser is automatically opened and
maximized. Then, it go to the url "https://www.wikipedia.org/".

1 - Create a maven project

Code: IT 313, Subject: OOP Java Programming II 22 | P a g e


Chapter III

2 - Create a java class

3 - Download selenium

Code: IT 313, Subject: OOP Java Programming II 23 | P a g e


Chapter III

4 - Add selenium dependencies to the IntelliJ IDEA

5 - chromedriver at the project folder

Code: IT 313, Subject: OOP Java Programming II 24 | P a g e


Chapter III
2. Selenium Web Driver

Locator

Locator is the location in the DOM (Document Object Model) that leads to certain elements which we can
capture and use to perform certain actions against to those elements such as button clicks or sending
texts to an email. Locators are coordinated to identify web elements in a web page.

There are many types of locators.

• ID: It identifies the alignment based on id (id="info_home") -> the fastest locator

• XPath: It identifies the query language (//*[@id="content"]/div[2]) -> the slowest locator

• CssLocator: It describes the web element through css properties (#content > div.mw-
indicators.mw-body-content)

• Class name: It identifies an element by the name of its class (class = head-bg-sticky)

• Tag name: It identifies the element by its tag name (div)

• LinkText: It identifies the element by the text of its link

Reliability:

• ID: unique, all browsers support it

• CSS: unique, not all browsers support it

• Name: not unique, all browsers support it

• Xpath: unique, all browsers support it

//locators

//id

......

Code: IT 313, Subject: OOP Java Programming II 25 | P a g e


Chapter III
Long start = System.currentTimeMillis();

driver.findElement(By.id("js-link-box-en"));

Long end = System.currentTimeMillis();

System.out.println("The time needed to get a locator by ID is: " + (end - start));

//xpath

start = System.currentTimeMillis();

driver.findElement(By.xpath("//*[@id=\"www-wikipedia-org\"]/div[2]/div[2]"));

end = System.currentTimeMillis();

System.out.println("The time needed to get a locator by Xpath is: " + (end - start));

//cssSelector

start = System.currentTimeMillis();

driver.findElement(By.cssSelector("#www-wikipedia-org > div.central-featured > div.central-


featured-lang.lang2"));

end = System.currentTimeMillis();

System.out.println("The time needed to get a locator by CSSSelector is: " + (end - start));

driver.close();

Get the text from the web

...

WebElement titleOfWebPage = driver.findElement(By.cssSelector("#www-wikipedia-org >


div.central-textlogo > h1 > span"));

Code: IT 313, Subject: OOP Java Programming II 26 | P a g e


Chapter III
String titleText = titleOfWebPage.getText();

String expectedText = "Wikipedia";

if(titleText.equals(expectedText)){

System.out.println("Test has passed!");

else{

System.out.println("Test did not pass!");

driver.close();

throw new Exception();

driver.close();

Clicking on a WebPage

......

WebElement englishButton = driver.findElement(By.id("js-link-box-en"));

englishButton.click();

String expectedTitle = "Welcome to Wikipedia,";

WebElement titleOfEnglishPage = driver.findElement(By.id("mp-welcome"));

if(titleOfEnglishPage.getText().equals(expectedTitle)){

System.out.println("Test has passed! Page is the English one");

Code: IT 313, Subject: OOP Java Programming II 27 | P a g e


Chapter III
}

else{

System.out.println("Test has failed! Click() was not successful.");

driver.close();

Sending texts to the webpage

...

WebElement searchBox = driver.findElement(By.id("searchInput"));

String searchStr = "Cambodia";

searchBox.sendKeys(searchStr);

WebElement searchButton = driver.findElement(By.cssSelector("#search-form > fieldset > button"));

searchButton.click();

//driver.close();

Code: IT 313, Subject: OOP Java Programming II 28 | P a g e


Chapter III

Working with table

tablepage.html

<table border=1>

<tbody>

<th>

First Column

</th>

<th>

Second Column

</th>

<th>

Third Column

</th>

<tr>

<td>

</td>

Code: IT 313, Subject: OOP Java Programming II 29 | P a g e


Chapter III
<td>

</td>

<td>

</td>

</tr>

<tbody>

</table>

App.java

...

driver.get("file:///D:/tablePage.html");

//System.out.println(driver.findElement(By.xpath("/html/body/table/tbody[1]/tr[2]/td[1]")).getText());

//System.out.println(driver.findElement(By.xpath("/html/body/table/tbody[1]/tr[1]/th[2]")).getText());

List<WebElement> listOfWebElements =
driver.findElements(By.xpath("/html/body/table/tbody[1]/tr"));

for(WebElement element : listOfWebElements){

System.out.println(element.getText());

driver.close();

Code: IT 313, Subject: OOP Java Programming II 30 | P a g e


Chapter III

Using the JavascriptExecutor

...

driver.get("https://www.udemy.com/course/core-java-programming-language-tutorial/");

WebElement signUpButton = driver.findElement(By.cssSelector("#udemy > div.main-content-


wrapper > div.ud-app-loader.ud-component--header-v6--header.udlite-header.ud-app-loaded >
div.udlite-text-sm.header--header--3sK1h.header--flex-middle--2Xqjv > div:nth-child(9) > a > span"));

//Clicking with JavascriptExecutor

((JavascriptExecutor) driver).executeScript("arguments[0].click();", signUpButton);

//Setting up timeouts

((JavascriptExecutor) driver).executeAsyncScript("window.setTimeout(arguments[arguments.length-
1], 1000);");

//Changing the webpage

((JavascriptExecutor) driver).executeScript("window.location = 'https://wikipedia.com'");

//Scroll the webpage

((JavascriptExecutor) driver).executeScript("window.scrollBy(0,1000)");

driver.close();

Code: IT 313, Subject: OOP Java Programming II 31 | P a g e


Chapter III

Alerts in Selenium

alerts.java

<body>

<p>Click the button to display a basic alert.</p>

<button onclick="myFunction()">Display Alert</button>

<script>

function myFunction() {

alert("Hello! I am an alert box!");

</script>

<p>Click the button to display a confirmation alert.</p>

<button onclick="confirmationAlert()">Confirmation Alert</button>

<script>

function confirmationAlert() {

confirm("Press a button!");

</script>

<p>Click the button to demonstrate a prompt alert.</p>

<button onclick="promptAlert()">Prompt Alert</button>

<p id="demo"></p>

Code: IT 313, Subject: OOP Java Programming II 32 | P a g e


Chapter III
<script>

function promptAlert() {

var person = prompt("Please enter your name", "John Doe");

if (person != null) {

document.getElementById("demo").innerHTML =

"Hello " + person + "! How are you today?";

</script>

</body>

App.java

...

driver.get("file:///D:/Projects/Video/youtube/bitheap/DesignPatterns/seleniumDemo/alerts.html");

WebElement basicAlertButton = driver.findElement(By.cssSelector("body > button:nth-child(2)"));

WebElement confirmationAlertButton = driver.findElement(By.cssSelector("body > button:nth-


child(5)"));

WebElement promptAlertButton = driver.findElement(By.cssSelector("body > button:nth-child(8)"));

//Basic Alert Demo

basicAlertButton.click();

WebDriverWait wait = new WebDriverWait(driver, 15);

wait.until(ExpectedConditions.alertIsPresent());

Alert basicAlert = driver.switchTo().alert();

basicAlert.accept();

//Confirmation Alert Demo

confirmationAlertButton.click();

wait.until(ExpectedConditions.alertIsPresent());

Alert confirmationAlert = driver.switchTo().alert();

Code: IT 313, Subject: OOP Java Programming II 33 | P a g e


Chapter III
confirmationAlert.dismiss();

//Prompt Alert Demo

promptAlertButton.click();

wait.until(ExpectedConditions.alertIsPresent());

Alert promptAlert = driver.switchTo().alert();

System.out.println(promptAlert.getText());

promptAlert.sendKeys("Laurentiu");

promptAlert.accept();

//driver.close();

Working with iFrames

driver.get("https://www.w3schools.com/html/html_iframe.asp");

String title = driver.switchTo().frame(0).findElement(By.cssSelector("#main > h1")).getText();

System.out.println(title);

WebElement iframe = driver.findElement(By.cssSelector("#main > div:nth-child(7) > iframe"));

driver.switchTo().frame(iframe).findElement(By.cssSelector("#topnav > div > div.w3-bar.w3-left >


a:nth-child(5)")).click();

driver.close();

Code: IT 313, Subject: OOP Java Programming II 34 | P a g e


Chapter III

....

driver.get("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select");

driver.switchTo().frame(driver.findElement(By.id("iframeResult")));

WebElement selectable = driver.findElement(By.id("cars"));

Select select = new Select(selectable);

select.selectByIndex(1);

driver.close();

Droppable

Code: IT 313, Subject: OOP Java Programming II 35 | P a g e


Chapter III
.....

driver.get("https://jqueryui.com/droppable/");

driver.switchTo().frame(driver.findElement(By.cssSelector("#content > iframe")));

WebElement draggable = driver.findElement(By.id("draggable"));

WebElement droppable = driver.findElement(By.id("droppable"));

Actions dragAndDrop = new Actions(driver);

dragAndDrop.dragAndDrop(draggable, droppable).build().perform();

Actions contextClick = new Actions(driver);

contextClick.contextClick().build().perform();

Actions actionObj = new Actions(driver);

actionObj.keyDown(Keys.F1);

driver.close();

Homework

1. What is Selenium? And what is Selenium web driver? Why do we need it?

2. Use selenium driver to make an automation process of the AIB website.

Code: IT 313, Subject: OOP Java Programming II 36 | P a g e


Chapter IV

Chapter 4: Automation Framework


Contents

1. Page Object Model

2. Managing the Framework's Driver

Objective
Within this chapter, we're going to discuss about several topics, and the first one is the page object model.
A design pattern will help us design our framework more efficiently and more logically. The next part will
be about framework design and it will split into several parts, and the first part focuses on how to create
the framework class, how to efficiently create a drama class that can be extended to be used with other
drivers, with several types of drivers. And the other parts will show how to implement the concept of a
model in your framework. The next part is going to be about test cases and unit tests, libraries. Then we're
going to add logging capability and reporting as well. We are going to implement Java Library to report on
our test results. We are also going to create pipelines for running our disguises automatically through
pipelines, through different triggers, such as a scheduler.

1. Page Object Model

Page Object Model, also known as POM, is a design pattern in Selenium that creates an object repository
for storing all web elements. It helps reduce code duplication and improves test case maintenance. In
Page Object Model, consider each web page of an application as a class file.

Code: IT 313, Subject: OOP Java Programming II 37 | P a g e


Chapter IV

2. Managing the Framework's Driver

1. application.properties

browser=Chrome

2. DriverStrategy.java

public interface DriverStrategy {

WebDriver setStrategy();

Code: IT 313, Subject: OOP Java Programming II 38 | P a g e


Chapter IV

1 - 3. POM - Selenium -Java

4. Chrome.java

public class Chrome implements DriverStrategy {

public WebDriver setStrategy() {

System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");

ChromeOptions options = new ChromeOptions();

options.setExperimentalOption("useAutomationExtension", false);

options.addArguments("--no-sandbox");

return new ChromeDriver(options);

5. PhantomJs.java

public class PhantomJs implements DriverStrategy {

public WebDriver setStrategy() {

System.setProperty("phantomjs.binary.path", "src/main/resources/phantomjs.exe");

DesiredCapabilities desiredCapabilities = new DesiredCapabilities();

desiredCapabilities.setJavascriptEnabled(true);

WebDriver driver = new PhantomJSDriver(desiredCapabilities);

return driver;

Code: IT 313, Subject: OOP Java Programming II 39 | P a g e


Chapter IV
}

6. Firefox.java

public class Firefox implements DriverStrategy {

public WebDriver setStrategy() {

System.setProperty("webdriver.gecko.driver", "src/main/resources/geckodriver.exe");

WebDriver driver = new FirefoxDriver();

return driver;

7. DriverStrategyImplementer.java

public class DriverStrategyImplementer {

public static DriverStrategy chooseStrategy(String strategy){

switch(strategy){

case "Chrome":

return new Chrome();

case "PhantomJs":

return new PhantomJs();

case "Firefox":

return new Firefox();

default:

return null;

8. DriverSigleton.java

public class DriverSingleton {

private static DriverSingleton instance = null;

private static WebDriver driver;

private DriverSingleton(String driver){

Code: IT 313, Subject: OOP Java Programming II 40 | P a g e


Chapter IV
instantiate(driver);

public WebDriver instantiate(String strategy){

DriverStrategy driverStrategy = DriverStrategyImplementer.chooseStrategy(strategy);

driver = driverStrategy.setStrategy();

driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

driver.manage().window().maximize();

return driver;

public static DriverSingleton getInstance(String driver){

if(instance == null){

instance = new DriverSingleton(driver);

return instance;

public static void closeObjectInstance() {

instance = null;

driver.quit();

public static WebDriver getDriver() {

return driver;

9. Main.java

public class Main {

public static void main(String[] args) {

FrameworkProperties frameworkProperties = new FrameworkProperties();

DriverSingleton.getInstance(frameworkProperties.getProperty("browser"));

WebDriver driver = DriverSingleton.getDriver();

Code: IT 313, Subject: OOP Java Programming II 41 | P a g e


Chapter IV
driver.get("http://automationpractice.com");

10. FrameworkProperties.java

public class FrameworkProperties {

private String result = "";

private InputStream inputStream;

public String getProperty(String key) {

try {

Properties properties = new Properties();

String propFileName = "framework.properties";

inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);

if ( inputStream != null )

properties.load(inputStream);

else

throw new FileNotFoundException("The Property file has not been found");

String propertyValue = properties.getProperty(key);

this.result = propertyValue;

} catch (IOException e) {

e.printStackTrace();

} return result;

3. JUnit
JUnit is a unit testing framework for the Java programming language. JUnit has been important in the
development of test-driven development, and is one of a family of unit testing frameworks which is
collectively known as xUnit that originated with SUnit. JUnit is linked as a JAR at compile-time.

Code: IT 313, Subject: OOP Java Programming II 42 | P a g e


Chapter IV

Homework

1. Form a group then create an automation framework to test on any website you prefer.

Code: IT 313, Subject: OOP Java Programming II 43 | P a g e


Chapter V

Chapter 5: Building Reports using Jasper


Contents

1. What is Jasper Report?

2. Getting Started with Jasper Report

3. Working with Charts

4. Jasper Reports with Spring Boot

Objective
This chapter focuses mainly on building reports using Jasper Report with Maven and Springboot. We start
with the definition and the benefit of the software, then move to setting up the first program and getting
started with JasperReport. We work with various basic elements such as textbox, static box, table, etc.
along with field, variable and parameters. In here, we use Java by choosing maven to create the project.
And then we to create charts and subreport. Finally, we create the Jasper report with springboot.

1. What is Jasper Report?

Basically, reports are used to represent the data. It can be in any format like tabular data or text data, or
maybe you are putting some images. For example, you are a sale manager or maybe you are involved in
the marketing team and you are going for a meeting, so obviously you will prepare the summary of the
data. Reports can have charts like bar chart and pie charts. There are many tools for making the reports,
but this course we use jasper along with java and spring boot.

Jasper is an open source tool to generate reports. It offers different formats for the reports like pdf, excel,
html, etc. The Jaspersoft reporting platform provides a single environment for managing users, reports,
dashboards, security, scheduling, and more, allowing administrators to orchestrate and manage
deployments of any level of complexity. It allows role-based access control to all reports in the repository
and also enable using of single report data from multiple data sources.

Code: IT 313, Subject: OOP Java Programming II 44 | P a g e


Chapter V
In this course we are going to use Jasper studio community addition because the community Edition is for
free.

Setting up the Program:

1. Go to https://community.jaspersoft.com/download and choose "download now" on Community


Edition

2. Click download on Jaspersoft® Studio CE

3. Install the software

4. Add dependency to the pom.xml on the maven project

<dependencies>

<dependency>

<groupId>net.sf.jasperreports</groupId>

<artifactId>jasperreports</artifactId>

<version>6.20.1</version>

</dependency>

</dependencies>

2. Getting Started with Jasper Report


2.1 Create First Report with Jasper Studio

1 - 1. Go to File -> New -> Jasper Report

Code: IT 313, Subject: OOP Java Programming II 45 | P a g e


Chapter V

2 - 2. Choose Simple Blue -> Next

3 - 3. Put name -> Next

Code: IT 313, Subject: OOP Java Programming II 46 | P a g e


Chapter V
4 - 4. Select Table -> write "select * from address"

5 - 5. Select all fields -> choose ">"

6 - 6. Click Next

Code: IT 313, Subject: OOP Java Programming II 47 | P a g e


Chapter V
7 - 7. Click Finish

8 - 8. Click Preview

2.2 Basic Elements in Jasper Report


1. Edit Title & remove the description text box

a. Double click on the title then rename it

b. Right click on the description text box then choose delete

2. Add new textbox and customize

a. Drag and drop the text box

b. Right click on the textbox and click "Show Properties"

c. Change color, choose font and font size

Code: IT 313, Subject: OOP Java Programming II 48 | P a g e


Chapter V

9 - Drag and drop the text box

10 - Right click on the textbox and click "Show Properties"

Code: IT 313, Subject: OOP Java Programming II 49 | P a g e


Chapter V
11 - Change color, choose font and font size

3. Knowing the Parameter, Field, and Variable

For the report, it is very important to understand what is parameter, field and variable in jasper reports.

• Parameters are the object references; those are passed during report-filling operations to the
report engine. it is represented by $P.

• A field is identified by a unique name, a type, and an optional description. It is represented by $F

• Variables can be used to store partial results and do complex calculations with the data extracted
from data source. It is represented by $V

4. Creating a Parameter

a. Right click on Parameter and choose "Create Parameter"

b. Name the parameter then chooses the class type

c. Right click on textbox "Text Field"

d. Click on Expression icon, then choose Parameter, and then double click on "studentName
Parameter string"

12 - Right click on Parameter and choose "Create Parameter"

Code: IT 313, Subject: OOP Java Programming II 50 | P a g e


Chapter V

13 - Name the parameter then choose the class type

14 - Right click on textbox "Text Field"

Code: IT 313, Subject: OOP Java Programming II 51 | P a g e


Chapter V

5. Copy the FirstReport.jrxml to the Maven project

a. On Jaspersoft Studio, right click on the FirstReport.jrxml file and choose copy

b. On IntelliJ IDEA, go to the maven project then paste the FirstReport.jrxml on the resources
directory

c. Write code as below:

public static void main (String [] args) {

try {

String filePath = "D:\\JasperReport\\src\\main\\resources\\FirstReport.jrxml";

Map<String, Object> parameters = new HashMap<String, Object> ();

parameters.put("studentName", "John");

} catch (Exception e) {

System.out.println("Exception while creating report");

Code: IT 313, Subject: OOP Java Programming II 52 | P a g e


Chapter V

Code: IT 313, Subject: OOP Java Programming II 53 | P a g e


Chapter V

6. Generating FirstReport.pdf

a. Create Student entity in the maven project

private long id;

private String firstName;

private String lastName;

private String street;

private String city;

public Student(long id, String firstName, String lastName, String street, String city) {

this.id = id;

this.firstName = firstName;

this.lastName = lastName;

this.street = street;

this.city = city;

public long getId() {

return id;

public void setId(long id) {

this.id = id;

Code: IT 313, Subject: OOP Java Programming II 54 | P a g e


Chapter V
}

public String getFirstName() {

return firstName;

public void setFirstName(String firstName) {

this.firstName = firstName;

public String getLastName() {

return lastName;

public void setLastName(String lastName) {

this.lastName = lastName;

public String getStreet() {

return street;

public void setStreet(String street) {

this.street = street;

public String getCity() {

return city;

public void setCity(String city) {

this.city = city;

b. Change the field name in Jaspersoft Studio accordingly

c. Create some object of the student then add them to the list, and then create a dataSource
connection (FirstReport.java)

Code: IT 313, Subject: OOP Java Programming II 55 | P a g e


Chapter V
......

Student student1 = new Student(1L, "Vichet", "Vuth", "Monivong", "Phnom penh");

Student student2 = new Student(1L, "Dara", "Khun", "Norodom", "Phnom penh");

List<Student> list = new ArrayList<Student>();

list.add(student1);

list.add(student2);

JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(list);

d. Filling the report and generating as pdf

JasperReport report = JasperCompileManager.compileReport(filePath);

JasperPrint print = JasperFillManager.fillReport(report, parameters, dataSource);

JasperExportManager.exportReportToPdfFile(print,
"D:\\JasperReport\\src\\main\\resources\\FirstReport.pdf");

System.out.println("Report Created...");

e. Alignment of the elements

f. Changing element properties from java code : put the key "name" the the textbox field then place
the following code on

FirstReport.java

......

JasperReport report = JasperCompileManager.compileReport(filePath);

JRBaseTextField textField = (JRBaseTextField) report.getTitle().getElementByKey("name");

textField.setForecolor(Color.RED);

JasperPrint print = JasperFillManager.fillReport(report, parameters, dataSource);

.......

Code: IT 313, Subject: OOP Java Programming II 56 | P a g e


Chapter V

Code: IT 313, Subject: OOP Java Programming II 57 | P a g e


Chapter V
15 - Change the field name in Jaspersoft Studio accordingly

16 - Filling the report and generating as pdf

Code: IT 313, Subject: OOP Java Programming II 58 | P a g e


Chapter V

17 - Alignment of the elements

18 - Put the key for changing element properties from java code

2.3 Building a Custom Report


1. Creating the bank report

a. Go to file -> New -> Jasper Report -> Choose Blank Report

b. Name the report then clicks Next

19 - Go to file -> New -> Jasper Report -> Choose Blank Report

Code: IT 313, Subject: OOP Java Programming II 59 | P a g e


Chapter V

20 - Name the report then click Next

2. Inserting the title

a. Click on Image Element then choose the image for the element

b. Add text box to the title

c. Select the 3 fields, then right click and choose "Enclose into Frame"

d. Put the color for the frame

e. Make the frame fit to the title

21 - Click on Image Element then choose the image for the element

Code: IT 313, Subject: OOP Java Programming II 60 | P a g e


Chapter V

22 - Add text box to the title

23 - Select the 3 fields, then right click and choose "Enclose into Frame"

Code: IT 313, Subject: OOP Java Programming II 61 | P a g e


Chapter V
24 - Put the color for the frame

25 - Make the frame fit to the title

3. Put the dashed line for the Page header

a. Drag and drop the Line element into the Page Header

b. Apply Size container to "Fit Width"

c. Put Size on the Appearance "h = 1 px"

d. On Borders, choose Line Style as "Dashed"

26 - Drag and drop the Line element into the Page Header

Code: IT 313, Subject: OOP Java Programming II 62 | P a g e


Chapter V

27 - On Borders, choose Line Style as "Dashed"

4. Making the Footer Page

a. Add two text boxes to the Footer Page

b. Write "Page" + $V{PAGE_NUMBER} on the Expression Editor for the first text box, with
the Evaluation Time as Now, and the Text Alignment as Right Alignment

c. Write " of " + $V{PAGE_NUMBER} on the Expression Editor for the second text box, with
the Evaluation Time as Report

28 - Write "Page" + $V{PAGE_NUMBER} on the Expression Editor for the first text box, with the Evaluation Time as Now, and the
Text Alignment as Right Alignment

Code: IT 313, Subject: OOP Java Programming II 63 | P a g e


Chapter V

29 - Write " of " + $V{PAGE_NUMBER} on the Expression Editor for the second text box, with the Evaluation Time as Report

5. Working with table

a. Create blank table

b. Design Title, Footer

c. Add parameter and field

d. Design Table

e. Add field to the table

Code: IT 313, Subject: OOP Java Programming II 64 | P a g e


Chapter V

Code: IT 313, Subject: OOP Java Programming II 65 | P a g e


Chapter V

Code: IT 313, Subject: OOP Java Programming II 66 | P a g e


Chapter V

Code: IT 313, Subject: OOP Java Programming II 67 | P a g e


Chapter V

Code: IT 313, Subject: OOP Java Programming II 68 | P a g e


Chapter V

Code: IT 313, Subject: OOP Java Programming II 69 | P a g e


Chapter V

6. Coding on the Maven project

Subject.java

private String subjectName;

private long markObtained;

public Subject(String subjectName, long markObtained) {

this.subjectName = subjectName; this.markObtained = markObtained;

public String getSubjectName() {

return subjectName;

public void setSubjectName(String subjectName) {

Code: IT 313, Subject: OOP Java Programming II 70 | P a g e


Chapter V
this.subjectName = subjectName;

public long getMarkObtained() {

return markObtained;

public void setMarkObtained(long markObtained) {

this.markObtained = markObtained;

CustomReport.java

public static void main(String[] args) {

try {

String filePath = "D:\\JasperReport\\src\\main\\resources\\Student.jrxml";

Subject subject1 = new Subject("Java", 80);

Subject subject2 = new Subject("MySQL", 70);

Subject subject3 = new Subject("PHP", 50);

Subject subject4 = new Subject("MongoDB", 40);

Subject subject5 = new Subject("C++", 60);

List<Subject> list = new ArrayList<Subject>();

list.add(subject1);

list.add(subject2);

list.add(subject3);

list.add(subject4);

list.add(subject5);

JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(list);

Map<String, Object> parameters = new HashMap<String, Object>();

Code: IT 313, Subject: OOP Java Programming II 71 | P a g e


Chapter V
parameters.put("studentName", "John");

parameters.put("tableData", dataSource);

JasperReport report = JasperCompileManager.compileReport(filePath);

JasperPrint print = JasperFillManager.fillReport(report, parameters, new


JREmptyDataSource());

JasperExportManager.exportReportToPdfFile(print,
"D:\\JasperReport\\src\\main\\resources\\student.pdf");

System.out.println("Report Created...");

} catch(Exception e) {

System.out.println("Exception while creating report");

7. Filling and customizing the table

Code: IT 313, Subject: OOP Java Programming II 72 | P a g e


Chapter V

8. Calculating the table

Code: IT 313, Subject: OOP Java Programming II 73 | P a g e


Chapter V

Code: IT 313, Subject: OOP Java Programming II 74 | P a g e


Chapter V

3. Working with Charts


We will work with Jasperreport to make Bar chart and Pie chart.

First of all, we add the field in the main report: studentName and markObtained

Code: IT 313, Subject: OOP Java Programming II 75 | P a g e


Chapter V

Then we create the chartDataSourcce as below

........

JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(list);

JRBeanCollectionDataSource chartDataSource = new JRBeanCollectionDataSource(list);

Map<String, Object> parameters = new HashMap<String, Object>();

parameters.put("studentName", "John");

parameters.put("tableData", dataSource);

JasperReport report = JasperCompileManager.compileReport(filePath);

JasperPrint print = JasperFillManager.fillReport(report, parameters, chartDataSource);

........

Working with Pie Chart

Code: IT 313, Subject: OOP Java Programming II 76 | P a g e


Chapter V

Code: IT 313, Subject: OOP Java Programming II 77 | P a g e


Chapter V

Working with bar chart

Code: IT 313, Subject: OOP Java Programming II 78 | P a g e


Chapter V

To HTML file

JasperExportManager.exportReportToHtmlFile(print,
"D:\\JasperReport\\src\\main\\resources\\student.html");

Code: IT 313, Subject: OOP Java Programming II 79 | P a g e


Chapter V
To HTML

JRXlsxExporter exporter = new JRXlsxExporter();

exporter.setExporterInput(new SimpleExporterInput(print));

exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(new FileOutputStream( new


File("D:\\M\\U\\Teaching\\Jasper-Reports\\Data\\Exported-Reports\\student.xlsx"))));

exporter.exportReport();

Creating Sub Report

Code: IT 313, Subject: OOP Java Programming II 80 | P a g e


Chapter V

Code: IT 313, Subject: OOP Java Programming II 81 | P a g e


Chapter V

public class CustomReport {

.........

parameters.put("tableData", dataSource);

parameters.put("subReport", getSubReport());

parameters.put("subDataSource", getSubDataSource());

......

public static JasperReport getSubReport () {

String filePath = "D:\\JasperReport\\src\\main\\resources\\FirstReport.jrxml";

JasperReport report;

try {

report = JasperCompileManager.compileReport(filePath);

return report;

} catch (JRException e) {

e.printStackTrace();

return null;

public static JRBeanCollectionDataSource getSubDataSource () {

Student student1 = new Student(1L, "Raj", "Joshi", "Happy Street",

"Delhi");

Code: IT 313, Subject: OOP Java Programming II 82 | P a g e


Chapter V
Student student2 = new Student(2L, "Peter", "Smith", "Any Street",

"Mumbai");

List<Student> list = new ArrayList<Student>();

list.add(student1);

list.add(student2);

JRBeanCollectionDataSource dataSource =

new JRBeanCollectionDataSource(list);

return dataSource;

Code: IT 313, Subject: OOP Java Programming II 83 | P a g e


Chapter V

CustomReport.java

....

parameters.put("subParameters", getSubParameters());

......

public static Map<String, Object> getSubParameters () {

Map<String, Object> parameters = new HashMap<String, Object>();

parameters.put("studentName", "Dara");

return parameters;

4. Jasper Reports with Spring Boot


Here we need to create a springboot application and then add the jrxml file to the resource folder, then
add the Student.java and Subject.java to the java folder.

Now we need to the following code to the demo java file

@SpringBootApplication

@ComponentScan("com.example.*")

public class DemoApplication {

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);

Code: IT 313, Subject: OOP Java Programming II 84 | P a g e


Chapter V
}

Create a file StudentController.java

@RestController

@RequestMapping("/api/student")

public class StudentController {

@GetMapping("/report")

public ResponseEntity<byte[]> getReport() {

try {

String filePath = ResourceUtils.getFile("classpath:Student.jrxml")

.getAbsolutePath();

Subject subject1 = new Subject("Java", 80);

Subject subject2 = new Subject("MySQL", 70);

Subject subject3 = new Subject("PHP", 50);

Subject subject4 = new Subject("MongoDB", 40);

Subject subject5 = new Subject("C++", 60);

List<Subject> list = new ArrayList<Subject>();

list.add(subject1);

list.add(subject2);

list.add(subject3);

list.add(subject4);

list.add(subject5);

JRBeanCollectionDataSource dataSource =

new JRBeanCollectionDataSource(list);

JRBeanCollectionDataSource chartDataSource =

new JRBeanCollectionDataSource(list);

Map<String, Object> parameters = new HashMap<String, Object>();

parameters.put("studentName", "John");

parameters.put("tableData", dataSource);

Code: IT 313, Subject: OOP Java Programming II 85 | P a g e


Chapter V
parameters.put("subReport", getSubReport());

parameters.put("subDataSource", getSubDataSource());

parameters.put("subParameters", getSubParameters());

JasperReport report = JasperCompileManager.compileReport(filePath);

JasperPrint print =

JasperFillManager.fillReport(report, parameters, chartDataSource);

byte[] byteArray = JasperExportManager.exportReportToPdf(print);

HttpHeaders headers = new HttpHeaders();

headers.setContentType(MediaType.APPLICATION_PDF);

headers.setContentDispositionFormData("filename", "student.pdf");

return new ResponseEntity<byte[]>(byteArray, headers, HttpStatus.OK);

} catch(Exception e) {

System.out.println("Exception while creating report");

return new ResponseEntity<byte[]>(HttpStatus.INTERNAL_SERVER_ERROR);

public static JasperReport getSubReport () {

JasperReport report;

try {

String filePath = ResourceUtils.getFile("classpath:FirstReport.jrxml").getAbsolutePath();

report = JasperCompileManager.compileReport(filePath);

return report;

} catch (Exception e) {

e.printStackTrace();

return null;

public static JRBeanCollectionDataSource getSubDataSource () {

Student student1 = new Student(1L, "Raj", "Joshi", "Happy Street",

Code: IT 313, Subject: OOP Java Programming II 86 | P a g e


Chapter V
"Delhi");

Student student2 = new Student(2L, "Peter", "Smith", "Any Street",

"Mumbai");

List<Student> list = new ArrayList<Student>();

list.add(student1);

list.add(student2);

JRBeanCollectionDataSource dataSource =

new JRBeanCollectionDataSource(list);

return dataSource;

public static Map<String, Object> getSubParameters () {

Map<String, Object> parameters = new HashMap<String, Object>();

parameters.put("studentName", "Raj");

return parameters;

Code: IT 313, Subject: OOP Java Programming II 87 | P a g e


Chapter V
Homework

Form a group and build a report for one of the topic below:

a. Inventory management system

b. Teacher management system

c. Mart management system

d. Other proposed system

The report should include table, calculation, charts, etc.

Code: IT 313, Subject: OOP Java Programming II 88 | P a g e

You might also like