BAEL-3464 - Ninja framework

This commit is contained in:
Anshul BANSAL 2019-12-14 16:34:34 +02:00
parent e6f6fd1ca7
commit e0245937f8
14 changed files with 114 additions and 115 deletions

View File

@ -4,10 +4,6 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>ninja</artifactId>
<!-- If you want to deploy to a war please -->
<!-- replace "jar" with "war" and -->
<!-- comment ninja-standalone dependency and -->
<!-- uncomment the dependency for ninja-servlet -->
<packaging>jar</packaging>
<groupId>com.baeldung</groupId>
<version>1.0.0</version>
@ -172,16 +168,6 @@
<artifactId>h2</artifactId>
<version>1.4.186</version>
</dependency>
<!-- If you want to deploy to a war please -->
<!-- comment ninja-standalone dependency and -->
<!-- uncomment the dependency for ninja-servlet -->
<!--
<dependency>
<groupId>org.ninjaframework</groupId>
<artifactId>ninja-servlet</artifactId>
<version>${ninja.version}</version>
</dependency>
-->
<dependency>
<groupId>org.ninjaframework</groupId>
<artifactId>ninja-standalone</artifactId>

View File

@ -1,33 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<!-- Database settings for development-->
<persistence-unit name="dev_unit" transaction-type="RESOURCE_LOCAL">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<!-- Database settings for development -->
<persistence-unit name="dev_unit"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.connection.driver_class" value="org.h2.Driver"/>
<property name="hibernate.connection.driver_class" value="org.h2.Driver" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.connection.autocommit" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.connection.autocommit" value="true" />
<!-- Connection Pooling settings -->
<property name="hibernate.connection.provider_class"
value="org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider" />
<property name="hibernate.connection.provider_class" value="org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider" />
<property name="hibernate.c3p0.max_size" value="100" />
<property name="hibernate.c3p0.min_size" value="0" />
<property name="hibernate.c3p0.acquire_increment" value="1" />
<property name="hibernate.c3p0.idle_test_period" value="300" />
<property name="hibernate.c3p0.max_statements" value="0" />
<property name="hibernate.c3p0.timeout" value="100" />
<property name="hibernate.c3p0.timeout" value="100" />
</properties>
</persistence-unit>
</persistence>

View File

@ -10,10 +10,15 @@ public class Routes implements ApplicationRoutes {
@Override
public void init(Router router) {
router.GET().route("/").with(ApplicationController::index);
router.GET().route("/index").with(ApplicationController::index);
router.GET().route("/home").with(ApplicationController::home);
router.GET().route("/hello").with(ApplicationController::helloWorld);
router.GET().route("/userJson").with(ApplicationController::userJson);
router.GET().route("/createUser").with(ApplicationController::createUser);
router.GET().route("/flash").with(ApplicationController::showFlashMsg);
router.GET().route("/users").with(ApplicationController::fetchUsers);
router.POST().route("/users").with(ApplicationController::insertUser);
//Assets
router.GET().route("/assets/webjars/{fileName: .*}").with(AssetsController::serveWebJars);

View File

@ -1,20 +1,9 @@
# The main properties file to configure your application
#
# Properties can be prefixed by "%".
# "%"" matches a mode you can set as system property. For instance when you
# are using maven you can do: mvn -Dmode=test jetty:run
#
# Using that the following property:
# %test.myproperty=test property
# would overwrite the property
# myproperty=my property
#
# You can define as many environments as you want. Simply set them in the mode.
application.name=baeldung ninja application
application.name=baeldung ninja dev application
%test.application.name=baeldung ninja test application
%prod.application.name=baeldung ninja application
application.cookie.prefix=NINJA
#ISO Language Code, optionally followed by a valid ISO Country Code.
application.languages=fr,en
application.session.expire_time_in_seconds=3600
@ -22,8 +11,6 @@ application.session.send_only_if_changed=true
application.session.transferred_over_https_only=false
ninja.port=8000
# enable ssl with self-signed cert in dev & test modes
ninja.ssl.port=8001
application.secret = fxSjSL9Q017BSL7gBnkyo2Prln7uXaXIT35gotXRIED8c46OSa8s4QdoIQdTsEtj

View File

@ -1,14 +1,8 @@
package controllers;
import ninja.Context;
import ninja.Result;
import ninja.Results;
import ninja.i18n.Lang;
import ninja.i18n.Messages;
import ninja.jpa.UnitOfWork;
import services.UserService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.inject.Inject;
@ -20,9 +14,19 @@ import org.apache.commons.logging.LogFactory;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.persist.Transactional;
import models.User;
import com.google.inject.persist.Transactional;
import ninja.Context;
import ninja.Result;
import ninja.Results;
import ninja.i18n.Lang;
import ninja.i18n.Messages;
import ninja.jpa.UnitOfWork;
import ninja.session.FlashScope;
import ninja.validation.JSR303Validation;
import ninja.validation.Validation;
import services.UserService;
@Singleton
public class ApplicationController {
@ -40,44 +44,59 @@ public class ApplicationController {
@Inject
UserService userService;
public Result index() {
Result result = Results.html();
lang.setLanguage("fr", result);
return result;
return Results.html();
}
public Result userJson() {
User user = userService.getUser();
logger.info(user);
return Results.json().render(user);
HashMap<String, String> userMap = userService.getUserMap();
logger.info(userMap);
return Results.json().render(userMap);
}
public Result helloWorld(Context context) {
Optional<String> language = Optional.of("en");
Optional<String> language = Optional.of("fr");
String helloMsg = msg.get("helloMsg", language).get();
return Results.text().render(helloMsg);
}
public Result showFlashMsg(FlashScope flashScope) {
flashScope.success("Success message");
flashScope.error("Error message");
return Results.redirect("/home");
}
public Result home() {
return Results.html();
}
public Result createUser() {
return Results.html();
}
@UnitOfWork
public Result fetchUsers() {
insertUser();
EntityManager entityManager = entitiyManagerProvider.get();
Query q = entityManager.createQuery("SELECT x FROM User x");
List<User> users = (List<User>) q.getResultList();
System.out.println(users);
return Results.text().render("Done");
return Results.json().render(users);
}
@Transactional
public Result insertUser() {
EntityManager entityManager = entitiyManagerProvider.get();
User user = userService.getUser();
entityManager.persist(user);
entityManager.flush();
public Result insertUser(FlashScope flashScope, @JSR303Validation User user, Validation validation) {
logger.info("Inserting User : " +user);
if (validation.getViolations().size() > 0) {
flashScope.error("Validation Error: User can't be created");
} else {
EntityManager entityManager = entitiyManagerProvider.get();
entityManager.persist(user);
entityManager.flush();
flashScope.success("User '" + user + "' is created successfully");
}
return Results.text().render("Inserted");
return Results.redirect("/home");
}
}

View File

@ -4,6 +4,7 @@ import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
@Entity
public class User {
@ -12,7 +13,9 @@ public class User {
@GeneratedValue(strategy=GenerationType.AUTO)
Long id;
@NotNull
public String firstName;
public String email;
public String toString() {

View File

@ -1,9 +1,9 @@
package services;
import models.User;
import java.util.HashMap;
public interface UserService {
User getUser();
HashMap<String, String> getUserMap();
}

View File

@ -1,15 +1,15 @@
package services;
import models.User;
import java.util.HashMap;
public class UserServiceImpl implements UserService {
@Override
public User getUser() {
User user = new User();
user.firstName = "Norman";
user.email = "norman@email.com";
return user;
public HashMap<String, String> getUserMap() {
HashMap<String, String> userMap = new HashMap<>();
userMap.put("name", "Norman Lewis");
userMap.put("email", "norman@email.com");
return userMap;
}
}

View File

@ -0,0 +1,12 @@
<#import "../layout/defaultLayout.ftl.html" as layout>
<@layout.myLayout "Create User">
<form method="post" action="users">
First Name : <input type="text" name="firstName"/>
<br/>
Email : <input type="text" name="email"/>
<br/>
<input type="submit" value="Create"/>
</@layout.myLayout>

View File

@ -0,0 +1,9 @@
<#import "../layout/defaultLayout.ftl.html" as layout>
<@layout.myLayout "Home page">
<h1>${i18n("helloMsg")}</h1>
<a href="/userJson">User Json</a>
</@layout.myLayout>

View File

@ -1,9 +1,9 @@
<#import "../layout/defaultLayout.ftl.html" as layout>
<@layout.myLayout "Home page">
<h1>${i18n("helloMsg")}</h1>
<a href="/userJson">User Json</a>
</@layout.myLayout>
<html>
<head>
<title>Ninja: Index</title>
</head>
<body>
<h1>${i18n("helloMsg")}</h1>
<a href="/userJson">User Json</a>
</body>
</html>

View File

@ -11,6 +11,8 @@
<ul class="nav navbar-nav">
<li class="active"><a href="/">${i18n("header.home")}</a></li>
<li class=""><a href="/hello">Hello</a></li>
<li class=""><a href="/users">List User</a></li>
<li class=""><a href="/createUser">Create User</a></li>
</ul>
</div>
<!--/.navbar-collapse -->

View File

@ -2,37 +2,26 @@ package controllers;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
import javax.inject.Inject;
import org.doctester.testbrowser.Request;
import org.doctester.testbrowser.Response;
import org.junit.Test;
import org.mockito.Mock;
import ninja.NinjaDocTester;
import services.UserService;
public class ApiControllerDocTesterTest extends NinjaDocTester {
String URL_INDEX = "/";
String URL_HELLO = "/hello";
String URL_USER_JSON = "/userJson";
String URL_USERS = "/users";
@Mock
UserService userService;
@Test
public void testGetIndex() {
Response response = makeRequest(Request.GET().url(testServerUrl().path(URL_INDEX)));
assertThat(response.payload, containsString("Bonjour, bienvenue dans Ninja Framework!"));
assertThat(response.payload, containsString("Hello, welcome to Ninja Framework!"));
}
@Test
public void testGetHello() {
Response response = makeRequest(Request.GET().url(testServerUrl().path(URL_HELLO)));
assertThat(response.payload, containsString("Hello, welcome to Ninja Framework!"));
assertThat(response.payload, containsString("Bonjour, bienvenue dans Ninja Framework!"));
}
}

View File

@ -1,19 +1,10 @@
package controllers;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThat;
import javax.inject.Inject;
import org.doctester.testbrowser.Request;
import org.doctester.testbrowser.Response;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import ninja.NinjaRunner;
import ninja.Result;
import services.UserService;
@ -35,7 +26,7 @@ public class ApiControllerMockTest {
public void testThatGetUserJson() {
Result result = applicationController.userJson();
System.out.println(result.getRenderable());
assertEquals(userService.getUser().toString(), result.getRenderable().toString());
assertEquals(userService.getUserMap().toString(), result.getRenderable().toString());
}
}