Added code for BAEL-1355 (#11908)

* Added code for BAEL-1355

* Formatted the code

* Added jakarta-ee to parent pom

Co-authored-by: Bhaskara Navuluri <bhaskara.navuluri@hpe.com>
This commit is contained in:
Bhaskara 2022-03-10 03:31:39 +05:30 committed by GitHub
parent 410ccd500b
commit f0f014b99c
11 changed files with 637 additions and 42 deletions

111
jakarta-ee/pom.xml Normal file
View File

@ -0,0 +1,111 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>mvc-2.0</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>mvc-2.0</name>
<properties>
<jakartaee-api.version>9.0.0</jakartaee-api.version>
<krazo.version>2.0.0</krazo.version>
<jakarta.mvc-api.version>2.0.0</jakarta.mvc-api.version>
<junit.jupiter.version>5.8.2</junit.jupiter.version>
<local.glassfish.home>C:/glassfish6</local.glassfish.home>
<local.glassfish.user>admin</local.glassfish.user>
<local.glassfish.domain>mvn-domain</local.glassfish.domain>
<mockito.version>1.10.19</mockito.version>
<local.glassfish.passfile>
${local.glassfish.home}\\domains\\${local.glassfish.domain}\\config\\domain-passwords
</local.glassfish.passfile>
</properties>
<dependencies>
<dependency>
<groupId>jakarta.platform</groupId>
<artifactId>jakarta.jakartaee-web-api</artifactId>
<version>${jakartaee-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jakarta.mvc</groupId>
<artifactId>jakarta.mvc-api</artifactId>
<version>${jakarta.mvc-api.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.krazo</groupId>
<artifactId>krazo-jersey</artifactId>
<version>${krazo.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>mvc-2.0</finalName>
<plugins>
<plugin>
<groupId>org.glassfish.maven.plugin</groupId>
<artifactId>maven-glassfish-plugin</artifactId>
<version>2.1</version>
<configuration>
<glassfishDirectory>${local.glassfish.home}</glassfishDirectory>
<user>admin</user>
<!-- <passwordFile>${local.glassfish.passfile}</passwordFile>-->
<adminPassword>password</adminPassword>
<domain>
<name>${local.glassfish.domain}</name>
<httpPort>8080</httpPort>
<adminPort>4848</adminPort>
</domain>
<components>
<component>
<name>${project.artifactId}</name>
<artifact>target/${project.build.finalName}.war</artifact>
</component>
</components>
<debug>true</debug>
<terse>false</terse>
<echo>true</echo>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,84 @@
package com.baeldung.eclipse.krazo;
import jakarta.enterprise.context.RequestScoped;
import jakarta.inject.Named;
import jakarta.mvc.RedirectScoped;
import jakarta.mvc.binding.MvcBinding;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Null;
import jakarta.validation.constraints.Size;
import jakarta.ws.rs.FormParam;
import java.io.Serializable;
@Named("user")
@RedirectScoped
public class User implements Serializable {
@MvcBinding
@Null
private String id;
@MvcBinding
@NotNull
@Size(min = 1, message = "Name cannot be blank")
@FormParam("name")
private String name;
@MvcBinding
@Min(value = 18, message = "The minimum age of the user should be 18 years")
@FormParam("age")
private int age;
@MvcBinding
@Email(message = "The email cannot be blank and should be in a valid format")
@Size(min=3, message = "Email cannot be empty")
@FormParam("email")
private String email;
@MvcBinding
@Null
@FormParam("phone")
private String phone;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.eclipse.krazo;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
/**
* Default JAX-RS application listening on /app
*/
@ApplicationPath("/app")
public class UserApplication extends Application {
}

View File

@ -0,0 +1,85 @@
package com.baeldung.eclipse.krazo;
import jakarta.inject.Inject;
import jakarta.mvc.Controller;
import jakarta.mvc.Models;
import jakarta.mvc.binding.BindingResult;
import jakarta.mvc.security.CsrfProtected;
import jakarta.validation.Valid;
import jakarta.ws.rs.BeanParam;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* The class contains two controllers and a REST API
*/
@Path("users")
public class UserController {
@Inject
private BindingResult bindingResult;
private static final List<User> users = new ArrayList<>();
@Inject
private Models models;
/**
* This is a controller. It displays a initial form to the user.
* @return The view name
*/
@GET
@Controller
public String showForm() {
return "user.jsp";
}
/**
* The method handles the form submits
* Handles HTTP POST and is CSRF protected. The client invoking this controller should provide a CSRF token.
* @param user The user details that has to be stored
* @return Returns a view name
*/
@POST
@Controller
@CsrfProtected
public String saveUser(@Valid @BeanParam User user) {
if (bindingResult.isFailed()) {
models.put("errors", bindingResult.getAllErrors());
return "user.jsp";
}
String id = UUID.randomUUID().toString();
user.setId(id);
users.add(user);
return "redirect:users/success";
}
/**
* Handles a redirect view
* @return The view name
*/
@GET
@Controller
@Path("success")
public String saveUserSuccess() {
return "success.jsp";
}
/**
* The REST API that returns all the user details in the JSON format
* @return The list of users that are saved. The List<User> is converted into Json Array.
* If no user is present a empty array is returned
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<User> getUsers() {
return users;
}
}

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/beans_3_0.xsd"
bean-discovery-mode="all" version="3.0">
</beans>

View File

@ -0,0 +1,47 @@
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MVC 2.0</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Raleway:wght@100;200;300;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="${pageContext.request.contextPath}/styles.css">
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<div class="container-fluid">
<span class="navbar-brand" href="#"><span style="font-size: 24px;">Baeldung - Eclipse Krazo</span></span>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse"
aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
</div>
</nav>
<div class="container">
<div class="row align-items-center">
<div class="col-sm-7 mx-auto">
<div class="card">
<div class="card-body">
<h3 class="card-title text-success">User created successfully!</h3>
</div>
</div>
</div>
</div>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</html>

View File

@ -0,0 +1,89 @@
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MVC 2.0</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Raleway:wght@100;200;300;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="${pageContext.request.contextPath}/styles.css">
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<div class="container-fluid">
<span class="navbar-brand" href="#"><span style="font-size: 24px;">Baeldung - Eclipse Krazo</span></span>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse"
aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
</div>
</nav>
<div class="container">
<div class="row align-items-center">
<div class="col-sm-7 mx-auto">
<h3>
<strong>User Details</strong>
</h3>
<hr class="hr-dark"/>
<c:if test="${errors.size() > 0}">
<div class="alert alert-danger" role="alert">
<dl class="row">
<c:forEach var="error" items="${errors}">
<dt class="col-sm-2">${error.paramName}</dt>
<dd class="col-sm-10">${error.message}</dd>
</c:forEach>
</dl>
</div>
</c:if>
<form action="${mvc.basePath}/users" method="post">
<div class="form-group row mt-3">
<label for="name" class="col-sm-3 col-form-label">Name</label>
<div class="col-sm-9">
<input name="name" type="text" class="form-control" id="name">
</div>
</div>
<div class="form-group row mt-3">
<label for="age" class="col-sm-3 col-form-label">Age</label>
<div class="col-sm-9">
<input name="age" type="text" class="form-control" id="age">
</div>
</div>
<div class="form-group row mt-3">
<label for="email" class="col-sm-3 col-form-label">Email</label>
<div class="col-sm-9">
<input name="email" type="email" class="form-control" id="email">
</div>
</div>
<div class="form-group row mt-3">
<label for="phone" class="col-sm-3 col-form-label">Phone</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="phone">
</div>
</div>
<hr class="hr-dark"/>
<div class="form-group row mt-3">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary"><strong>Create</strong></button>
</div>
</div>
<input type="hidden" name="${mvc.csrf.name}" value="${mvc.csrf.token}"/>
</form>
</div>
</div>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</html>

View File

@ -0,0 +1,28 @@
body, html {
font-family: Raleway, serif;
font-weight: 300;
}
.bg-dark {
background-color: #63b175 !important;
font-weight: 600 !important;
}
body {
padding-top: 80px;
}
@media (max-width: 979px) {
body {
padding-top: 0;
}
}
label {
font-weight: bold;
}
.hr-dark {
border-top: 2px solid #000;
margin-bottom: 20px;
}

View File

@ -0,0 +1,16 @@
package com.baeldung.eclipse.krazo;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Dummy Test
*/
public class AppTest {
@Test
public void test() {
assertTrue(true);
}
}

View File

@ -0,0 +1,116 @@
package com.baeldung.eclipse.krazo;
import com.baeldung.eclipse.krazo.User;
import com.baeldung.eclipse.krazo.UserController;
import jakarta.mvc.Models;
import jakarta.mvc.binding.BindingResult;
import org.eclipse.krazo.core.ModelsImpl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;
/**
* The class contains unit tests. We do only unit tests. Most of the classes are mocked
*/
@DisplayName("Eclipse Krazo MVC 2.0 Test Suite")
class UserControllerUnitTest {
@InjectMocks
UserController userController = new UserController();
@Mock
Models models;
@Mock
BindingResult bindingResult;
@BeforeEach
public void setUpClass() {
MockitoAnnotations.initMocks(this);
}
@Test
@DisplayName("Test Show Form")
void whenShowForm_thenReturnViewName() {
assertNotNull(userController.showForm());
assertEquals("user.jsp", userController.showForm());
}
@Test
@DisplayName("Test Save User Success")
void whenSaveUser_thenReturnSuccess() {
when(bindingResult.isFailed()).thenReturn(false);
User user = new User();
assertNotNull(userController.saveUser(user));
assertDoesNotThrow(() -> userController.saveUser(user));
assertEquals("redirect:users/success", userController.saveUser(user));
}
@Test
@DisplayName("Test Save User Binding Errors")
void whenSaveUser_thenReturnError() {
when(bindingResult.isFailed()).thenReturn(true);
Models testModels = new ModelsImpl();
when(models.put(anyString(), any())).thenReturn(testModels);
User user = getUser();
assertNotNull(userController.saveUser(user));
assertDoesNotThrow(() -> userController.saveUser(user));
assertEquals("user.jsp", userController.saveUser(user));
}
@Test
@DisplayName("Test Save User Success View")
void whenSaveUserSuccess_thenRedirectSuccess() {
assertNotNull(userController.saveUserSuccess());
assertDoesNotThrow(() -> userController.saveUserSuccess());
assertEquals("success.jsp", userController.saveUserSuccess());
}
@Test
@DisplayName("Test Get Users API")
void whenGetUser_thenReturnUsers() {
when(bindingResult.isFailed()).thenReturn(false);
User user= getUser();
assertNotNull(user);
assertEquals(30, user.getAge());
assertEquals("john doe", user.getName());
assertEquals("anymail", user.getEmail());
assertEquals("99887766554433", user.getPhone());
assertEquals("1", user.getId());
userController.saveUser(user);
userController.saveUser(user);
userController.saveUser(user);
assertNotNull(userController.getUsers());
assertDoesNotThrow(() -> userController.getUsers());
assertEquals(3, userController.getUsers().size());
}
private User getUser() {
User user = new User();
user.setId("1");
user.setName("john doe");
user.setAge(30);
user.setEmail("anymail");
user.setPhone("99887766554433");
return user;
}
}

View File

@ -462,6 +462,7 @@
<module>jaxb</module> <module>jaxb</module>
<module>jee-7</module> <module>jee-7</module>
<module>jee-7-security</module> <module>jee-7-security</module>
<module>jakarta-ee</module>
<module>jersey</module> <module>jersey</module>
<module>jgit</module> <module>jgit</module>
<module>jgroups</module> <module>jgroups</module>
@ -945,6 +946,7 @@
<module>jaxb</module> <module>jaxb</module>
<module>jee-7</module> <module>jee-7</module>
<module>jee-7-security</module> <module>jee-7-security</module>
<module>jakarta-ee</module>
<module>jersey</module> <module>jersey</module>
<module>jgit</module> <module>jgit</module>
<module>jgroups</module> <module>jgroups</module>