OOP Java Programming II
OOP Java Programming II
1. What is 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.
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
• 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.
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.
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.
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.
Automating applications will be possible by using this approach if we consider the following scenario.
• 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
• 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
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.
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
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.
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
Java provides 2 approaches to inject code into running JVM. These are the concepts of Java
instrumentation and attaching Instrumentation Agent.
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.
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
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.
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.
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
• 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.
3. What is the Automation in Java? And what types of the automation we are going to focus?
Chapter 2:
Keyboard and Mouse Automation
Contents
1. Automating Mouse Operation
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
import java.awt.*;
import java.io.IOException;
robot.delay(2000);
package org.example;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
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);
robot.keyRelease(KeyEvent.VK_X);
robot.delay(2000);
....
robot.delay(3000);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.delay(3000);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
..........
robot.delay(3000);
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);
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);
......
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);
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);
In here, we do the basic automation by automating the keyboard to type some characters by itself.
import java.awt.event.*;
import java.io.IOException;
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");
// Make the first character upper case and the remaining characters lower case.
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyRelease(KeyEvent.VK_SHIFT);
}//end if
robot.keyPress(keyInput[cnt2]);
robot.delay(500);
....
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);
We make the computer awake forever by making the move move every 5 seconds in different
coordination.
import java.awt.*;
import java.util.*;
//hal.mou
hal.mouseMove(1366,0);
hal.delay(5000);
while(true){
hal.delay(5000);
hal.mouseMove(x,y);
System.out.println(x+"*"+y);
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.
2. Go to File -> Setting -> Build, Execution, Deployment -> Compiler -> Java Compiler -> Target
bytecode version => (17) -> Ok
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
or
• exe file
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
Homework
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.
1. Introduction to Selenium
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.
• Webdriver
• Selenium Grid
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.
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
a. Go to https://www.selenium.dev/downloads
c. On Intellij IDea, click on File -> Project Structure -> Module - > Dependencies -> Add ->
Jar or Directories.
a. Go to https://chromedriver.chromium.org/downloads
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/".
3 - Download selenium
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.
• 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)
Reliability:
//locators
//id
......
driver.findElement(By.id("js-link-box-en"));
//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();
end = System.currentTimeMillis();
System.out.println("The time needed to get a locator by CSSSelector is: " + (end - start));
driver.close();
...
if(titleText.equals(expectedText)){
else{
driver.close();
driver.close();
Clicking on a WebPage
......
englishButton.click();
if(titleOfEnglishPage.getText().equals(expectedTitle)){
else{
driver.close();
...
searchBox.sendKeys(searchStr);
searchButton.click();
//driver.close();
tablepage.html
<table border=1>
<tbody>
<th>
First Column
</th>
<th>
Second Column
</th>
<th>
Third Column
</th>
<tr>
<td>
</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"));
System.out.println(element.getText());
driver.close();
...
driver.get("https://www.udemy.com/course/core-java-programming-language-tutorial/");
//Setting up timeouts
((JavascriptExecutor) driver).executeAsyncScript("window.setTimeout(arguments[arguments.length-
1], 1000);");
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,1000)");
driver.close();
Alerts in Selenium
alerts.java
<body>
<script>
function myFunction() {
</script>
<script>
function confirmationAlert() {
confirm("Press a button!");
</script>
<p id="demo"></p>
function promptAlert() {
if (person != null) {
document.getElementById("demo").innerHTML =
</script>
</body>
App.java
...
driver.get("file:///D:/Projects/Video/youtube/bitheap/DesignPatterns/seleniumDemo/alerts.html");
basicAlertButton.click();
wait.until(ExpectedConditions.alertIsPresent());
basicAlert.accept();
confirmationAlertButton.click();
wait.until(ExpectedConditions.alertIsPresent());
promptAlertButton.click();
wait.until(ExpectedConditions.alertIsPresent());
System.out.println(promptAlert.getText());
promptAlert.sendKeys("Laurentiu");
promptAlert.accept();
//driver.close();
driver.get("https://www.w3schools.com/html/html_iframe.asp");
System.out.println(title);
driver.close();
....
driver.get("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select");
driver.switchTo().frame(driver.findElement(By.id("iframeResult")));
select.selectByIndex(1);
driver.close();
Droppable
driver.get("https://jqueryui.com/droppable/");
dragAndDrop.dragAndDrop(draggable, droppable).build().perform();
contextClick.contextClick().build().perform();
actionObj.keyDown(Keys.F1);
driver.close();
Homework
1. What is Selenium? And what is Selenium web driver? Why do we need it?
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.
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.
1. application.properties
browser=Chrome
2. DriverStrategy.java
WebDriver setStrategy();
4. Chrome.java
System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");
options.setExperimentalOption("useAutomationExtension", false);
options.addArguments("--no-sandbox");
5. PhantomJs.java
System.setProperty("phantomjs.binary.path", "src/main/resources/phantomjs.exe");
desiredCapabilities.setJavascriptEnabled(true);
return driver;
6. Firefox.java
System.setProperty("webdriver.gecko.driver", "src/main/resources/geckodriver.exe");
return driver;
7. DriverStrategyImplementer.java
switch(strategy){
case "Chrome":
case "PhantomJs":
case "Firefox":
default:
return null;
8. DriverSigleton.java
driver = driverStrategy.setStrategy();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.manage().window().maximize();
return driver;
if(instance == null){
return instance;
instance = null;
driver.quit();
return driver;
9. Main.java
DriverSingleton.getInstance(frameworkProperties.getProperty("browser"));
10. FrameworkProperties.java
try {
inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if ( inputStream != null )
properties.load(inputStream);
else
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.
Homework
1. Form a group then create an automation framework to test on any website you prefer.
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.
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.
<dependencies>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.20.1</version>
</dependency>
</dependencies>
6 - 6. Click Next
8 - 8. Click Preview
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.
• 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
d. Click on Expression icon, then choose Parameter, and then double click on "studentName
Parameter string"
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
try {
parameters.put("studentName", "John");
} catch (Exception e) {
6. Generating FirstReport.pdf
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;
return id;
this.id = id;
return firstName;
this.firstName = firstName;
return lastName;
this.lastName = lastName;
return street;
this.street = street;
return city;
this.city = city;
c. Create some object of the student then add them to the list, and then create a dataSource
connection (FirstReport.java)
list.add(student1);
list.add(student2);
JasperExportManager.exportReportToPdfFile(print,
"D:\\JasperReport\\src\\main\\resources\\FirstReport.pdf");
System.out.println("Report Created...");
f. Changing element properties from java code : put the key "name" the the textbox field then place
the following code on
FirstReport.java
......
textField.setForecolor(Color.RED);
.......
18 - Put the key for changing element properties from java code
a. Go to file -> New -> Jasper Report -> Choose Blank Report
19 - Go to file -> New -> Jasper Report -> Choose Blank Report
a. Click on Image Element then choose the image for the element
c. Select the 3 fields, then right click and choose "Enclose into Frame"
21 - Click on Image Element then choose the image for the element
23 - Select the 3 fields, then right click and choose "Enclose into Frame"
a. Drag and drop the Line element into the Page Header
26 - Drag and drop the Line element into the Page Header
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
29 - Write " of " + $V{PAGE_NUMBER} on the Expression Editor for the second text box, with the Evaluation Time as Report
d. Design Table
Subject.java
return subjectName;
return markObtained;
this.markObtained = markObtained;
CustomReport.java
try {
list.add(subject1);
list.add(subject2);
list.add(subject3);
list.add(subject4);
list.add(subject5);
parameters.put("tableData", dataSource);
JasperExportManager.exportReportToPdfFile(print,
"D:\\JasperReport\\src\\main\\resources\\student.pdf");
System.out.println("Report Created...");
} catch(Exception e) {
First of all, we add the field in the main report: studentName and markObtained
........
parameters.put("studentName", "John");
parameters.put("tableData", dataSource);
........
To HTML file
JasperExportManager.exportReportToHtmlFile(print,
"D:\\JasperReport\\src\\main\\resources\\student.html");
exporter.setExporterInput(new SimpleExporterInput(print));
exporter.exportReport();
.........
parameters.put("tableData", dataSource);
parameters.put("subReport", getSubReport());
parameters.put("subDataSource", getSubDataSource());
......
JasperReport report;
try {
report = JasperCompileManager.compileReport(filePath);
return report;
} catch (JRException e) {
e.printStackTrace();
return null;
"Delhi");
"Mumbai");
list.add(student1);
list.add(student2);
JRBeanCollectionDataSource dataSource =
new JRBeanCollectionDataSource(list);
return dataSource;
CustomReport.java
....
parameters.put("subParameters", getSubParameters());
......
parameters.put("studentName", "Dara");
return parameters;
@SpringBootApplication
@ComponentScan("com.example.*")
SpringApplication.run(DemoApplication.class, args);
@RestController
@RequestMapping("/api/student")
@GetMapping("/report")
try {
.getAbsolutePath();
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);
parameters.put("studentName", "John");
parameters.put("tableData", dataSource);
parameters.put("subDataSource", getSubDataSource());
parameters.put("subParameters", getSubParameters());
JasperPrint print =
headers.setContentType(MediaType.APPLICATION_PDF);
headers.setContentDispositionFormData("filename", "student.pdf");
} catch(Exception e) {
JasperReport report;
try {
report = JasperCompileManager.compileReport(filePath);
return report;
} catch (Exception e) {
e.printStackTrace();
return null;
"Mumbai");
list.add(student1);
list.add(student2);
JRBeanCollectionDataSource dataSource =
new JRBeanCollectionDataSource(list);
return dataSource;
parameters.put("studentName", "Raj");
return parameters;
Form a group and build a report for one of the topic below: