Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Jakarta EE Cookbook
  • Table Of Contents Toc
Jakarta EE Cookbook

Jakarta EE Cookbook - Second Edition

By : Moraes
5 (2)
close
close
Jakarta EE Cookbook

Jakarta EE Cookbook

5 (2)
By: Moraes

Overview of this book

Jakarta EE is widely used around the world for developing enterprise applications for a variety of domains. With this book, Java professionals will be able to enhance their skills to deliver powerful enterprise solutions using practical recipes. This second edition of the Jakarta EE Cookbook takes you through the improvements introduced in its latest version and helps you get hands-on with its significant APIs and features used for server-side development. You'll use Jakarta EE for creating RESTful web services and web applications with the JAX-RS, JSON-P, and JSON-B APIs and learn how you can improve the security of your enterprise solutions. Not only will you learn how to use the most important servers on the market, but you'll also learn to make the best of what they have to offer for your project. From an architectural point of view, this Jakarta book covers microservices, cloud computing, and containers. It allows you to explore all the tools for building reactive applications using Jakarta EE and core Java features such as lambdas. Finally, you'll discover how professionals can improve their projects by engaging with and contributing to the community. By the end of this book, you'll have become proficient in developing and deploying enterprise applications using Jakarta EE.
Table of Contents (14 chapters)
close
close

Using Jakarta Batch processing

Running background tasks is a useful and important skill in an enterprise context.

You could use it to process data in bulk or just to separate it from the UI processes. This recipe will show you how to do this.

Getting ready

Let's add our dependencies:

<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.10.Final</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>8.0</version>
<scope>provided</scope>
</dependency>
</dependencies>

How to do it...

Perform the following steps to complete this recipe:

  1. First, we need to define our persistence unit:
  <persistence-unit name="ch02-batch-pu" >
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>java:app/userDb</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-
generation.database.action"
value="create"/>
<property name="hibernate.transaction.jta.platform"
value="org.hibernate.service.jta.platform
.internal.SunOneJtaPlatform"/>
</properties>
</persistence-unit>

  1. Then, we need to declare a User entity:
@Entity
@Table(name = "UserTab")
public class User implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@NotNull
private Integer id;

private String name;

private String email;

public User() {
}

//DO NOT FORGET TO IMPLEMENT THE GETTERS AND SETTERS
}
  1. Here, we're creating a job reader:
@Named
@Dependent
public class UserReader extends AbstractItemReader {

private BufferedReader br;

@Override
public void open(Serializable checkpoint) throws Exception {
br = new BufferedReader(
new InputStreamReader(
Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream
("META-INF/user.txt")));
}

@Override
public String readItem() {
String line = null;

try {
line = br.readLine();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}

return line;
}
}
  1. Then, we need to create a job processor:
@Named
@Dependent
public class UserProcessor implements ItemProcessor {

@Override
public User processItem(Object line) {
User user = new User();

StringTokenizer tokens = new StringTokenizer((String)
line, ",");
user.setId(Integer.parseInt(tokens.nextToken()));
user.setName(tokens.nextToken());
user.setEmail(tokens.nextToken());

return user;
}
}
  1. Here, we're creating a job writer:
@Named
@Dependent
public class UserWriter extends AbstractItemWriter {

@PersistenceContext
EntityManager entityManager;

@Override
@Transactional
public void writeItems(List list) {
for (User user : (List<User>) list) {
entityManager.persist(user);
}
}
}
  1. The processor, reader, and writer are referenced by the acess-user.xml file, which is located at META-INF.batch-jobs:
<?xml version="1.0" encoding="windows-1252"?>
<job id="userAccess"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
version="1.0">
<step id="loadData">
<chunk item-count="3">
<reader ref="userReader"/>
<processor ref="userProcessor"/>
<writer ref="userWriter"/>
</chunk>
</step>
</job>
  1. And finally, we create a bean to interact with the batch engine:
@Named
@RequestScoped
public class UserBean {

@PersistenceContext
EntityManager entityManager;

public void run() {
try {
JobOperator job = BatchRuntime.getJobOperator();
long jobId = job.start("acess-user", new Properties());
System.out.println("Job started: " + jobId);
} catch (JobStartException ex) {
System.out.println(ex.getMessage());
}
}

public List<User> get() {
return entityManager
.createQuery("SELECT u FROM User as u", User.class)
.getResultList();
}
}
  1. For the purpose of this example, we are going to use a JSF page to run the job and load the data:
 <h:body>
<h:form>
<h:outputLabel value="#{userBean.get()}" />
<br />
<h:commandButton value="Run" action="index" actionListener="#{userBean.run()}"/>
<h:commandButton value="Reload" action="index"/>
</h:form>
</h:body>

Run it on a Jakarta EE server to load the web page. Click on the Run button and then the Reload button.

How it works...

UserReader extends the AbstractItemReader class, which has two key methods open() and readItem(). In our case, the first one opens the META-INF/user.txt file, while the second one reads each line of the file.

After that, the UserProcessor class extends the ItemProcessor class, which has a processItem() method. It gets the item read by readItem() (from UserReader) to generate the User object that we want.

Once all the items have been processed and are available in a list (in memory), we use the UserWriter class. This extends the AbstractItemWriter class and contains the writeItems method. In our case, we use it to persist the data that we read from the user.txt file.

Now, we just need to use UserBean to run the job:

public void run() {
try {
JobOperator job = BatchRuntime.getJobOperator();
long jobId = job.start("acess-user", new Properties());
System.out.println("Job started: " + jobId);
} catch (JobStartException ex) {
System.out.println(ex.getMessage());
}
}

The job.start() method is referencing the acess-user.xml file, thereby enabling our reader, processor, and writer to work together.

See also

CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Jakarta EE Cookbook
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon