Sample web application project using Plain JavaSE – Maven Embedded

Hi, in this post i’ll be publishing a sample web application with an endpoint that runs a maven command and prints logged output to response.
The motivation for this is to expose maven command ‘mvn dependency:tree’ output on an endpoint. This command prints a tree of project dependencies.

This web app is deployed on embedded Tomcat server and uses maven embedded.
Logging framework is slf4-simple with properties set on simplelogger.properties file.

The proposed flow on the web application  is:

  1.  Visit – ‘localhost:8080/mvn/mvn’ , where a servlet is contacted to run a  maven command ‘mvn dependency:tree’.
    Logged output is printed to http response.
    (screenshot)

Relevant code snippets:

MavenServlet
https://gist.github.com/arthurportas/96e77e7187ff7e8c59e428431d45b954

simplelogger.properties
https://gist.github.com/arthurportas/d2b311bb840ae38af2e66838d88273bf

‘mavenembedded’  – is a  maven project, so it should be fairly simple to import and build it. Run main class ‘Main.java’ on your IDE providing VM options
‘-Dmaven.multiModuleProjectDirectory=$M2_HOME'(see bellow image).
Hope it’s helpful for someone!

IntelliJ run config with VM options screenshot

Sample project using Plain JavaSE – Episode 4

Hi, this is the fourth post of a series where i’ll be publishing some samples showing how to develop web applications with Java technology.
This post sample consists on a project ‘staffgest-mvc-freemarker‘ that serves as presentation layer using Freemarker.

This web app is deployed on a embedded Glassfish server .
You can read more about Glassfish Embedded in here.
You can read more about Freemarker in here.
For more context please refer to the previous post.

The proposed flow on the web application  is:

  1.  Visit – ‘localhost:8080/staffgest-mvc-freemarker/new-employee.html’ , where a form to create an employee is showed
    – submit form and “new-employee.ftl” is rendered
  2. Visit – ‘localhost:8080/staffgest-mvc-freemarker/search-employee.html’ , where a form to search an employee is showed
    – submit form and “search-employee.ftl” is rendered

Relevant code snippets:

Web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee&quot;
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd&quot;
version="3.1">
<welcome-file-list>
<welcome-file>new-employee.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>freemarker</servlet-name>
<servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class>
<!--
Init-param documentation:
http://freemarker.org/docs/api/freemarker/ext/servlet/FreemarkerServlet.html
-->
<!-- FreemarkerServlet settings: -->
<init-param>
<param-name>TemplatePath</param-name>
<param-value>/</param-value>
</init-param>
<init-param>
<param-name>NoCache</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>ExceptionOnMissingTemplate</param-name>
<!-- true => HTTP 500 on missing template, instead of HTTP 404. -->
<param-value>true</param-value>
</init-param>
<!-- FreeMarker engine settings: -->
<init-param>
<param-name>incompatible_improvements</param-name>
<param-value>2.3.23</param-value>
<!--
Recommended to set to a high value.
See: http://freemarker.org/docs/pgui_config_incompatible_improvements.html
-->
</init-param>
<init-param>
<param-name>template_exception_handler</param-name>
<!-- Use "html_debug" during development! -->
<param-value>rethrow</param-value>
</init-param>
<init-param>
<param-name>template_update_delay</param-name>
<!-- Use 0 during development! Consider what value you need otherwise. -->
<param-value>0 s</param-value>
</init-param>
<init-param>
<param-name>default_encoding</param-name>
<!-- The encoding of the template files: -->
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>output_encoding</param-name>
<!-- The encoding of the template output; Note that you must set
"ResponseCharacterEncodring" to "fromTemplate" for this to work! -->
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>locale</param-name>
<!-- Influences number and date/time formatting, etc. -->
<param-value>pt_PT</param-value>
</init-param>
<init-param>
<param-name>number_format</param-name>
<param-value>0.##</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>freemarker</servlet-name>
<url-pattern>*.ftl</url-pattern>
</servlet-mapping>
<!--
Prevent the visiting of MVC Views from outside the servlet container.
RequestDispatcher.forward/include should, and will still work.
Removing this may open security holes!
-->
<security-constraint>
<web-resource-collection>
<web-resource-name>FreeMarker MVC Views</web-resource-name>
<url-pattern>*.ftl</url-pattern>
</web-resource-collection>
<auth-constraint>
<!-- Nobody is allowed to visit these directly. -->
</auth-constraint>
</security-constraint>
</web-app>
view raw web.xml hosted with ❤ by GitHub

Controller

package com.arthurportas.presentation.servlets;
import com.arthurportas.entities.Employee;
import com.arthurportas.services.EmployeeService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by arthurportas on 22/04/2017.
*/
@WebServlet(urlPatterns = "/employee")
public class EmployeeController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String value = req.getParameter("value");
Employee employee = getEmployeeService().findbyName(value);
req.setAttribute("emp", employee);
req.getRequestDispatcher("search-employee.ftl").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String firstName = req.getParameter("firstName");
String lastName = req.getParameter("lastName");
Employee employee = new Employee();
employee.setFirstName(firstName);
employee.setLastName(lastName);
employee = getEmployeeService().create(employee);
req.setAttribute("emp", employee);
resp.setContentType("text/html;charset=UTF-8");
req.getRequestDispatcher("new-employee.ftl").forward(req, resp);
}
private EmployeeService getEmployeeService() {
return new EmployeeService();
}
}

Views
“new-employee.html”

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>::StaffGest:: - new-employee</title>
<meta name="description" content="StaffGest:: - search-employee">
<meta name="author" content="Arthur Portas">
</head>
<body>
<form action="/staffgest-mvc-freemarker/employee" method="post">
First name:<br>
<input type="text" name="firstName" value="Arthur">
<br>
Last name:<br>
<input type="text" name="lastName" value="Portas">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

“new-employee.ftl”

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>New Employee</title>
</head>
<body>
Employee created with success!
${emp}
</body>
</html>

“search-employee.html”

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>::StaffGest:: - search-employee</title>
<meta name="description" content="StaffGest:: - search-employee">
<meta name="author" content="Arthur Portas">
</head>
<body>
<form action="/staffgest-mvc-freemarker/employee" method="get">
Enter search criteria:<br>
<input type="text" name="value" value="Arthur">
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>

“search-employee.ftl”

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Search Employee</title>
</head>
<body>
Search results: ${emp}
</body>
</html>

‘staffgest-mdw‘ , ‘staffgest-mvc-freemarker‘ – are all maven projects, so it should be fairly simple to import and build it. First build “staffgest-mdw” and the run “staffgest-mvc-freemarker” through a main class ‘App.java’.
Hope it’s helpful for someone!

Sample project using Plain JavaSE – Episode 3

Hi, this is the third post of a series where i’ll be publishing some samples showing how to develop web applications with Java technology.
This post sample consists on a project ‘staffgest-persistence-hibernate-jpa‘ that serves as persistence layer using JPA.
I’ll use Hibernate 5 as a JPA provider and H2 as an in-memory relational database.

On the next episode i’ll plug this project as a dependency on ‘staffgest-mdw‘.

You can read more about JPA in here.
You can read more about Hibernate in here.
You can read more about H2 in here.

For more context please refer to the previous post.

Relevant code snippets:

Persistence.xml
https://gist.github.com/arthurportas/a7fed5a33b69ae1023ea2d250cee1077

Generic DAO interface
https://gist.github.com/arthurportas/020083d56a8b840eabec350c30b7fb83

Generic DAO interface
https://gist.github.com/arthurportas/020083d56a8b840eabec350c30b7fb83

Generic DAO Impl
https://gist.github.com/arthurportas/bcf2cfa0baa221ce351fa1890f4b3f40

Employee DAO Interface
https://gist.github.com/arthurportas/76054e17b43edea4f04fbdff3e82abb7

Employee DAO Impl
https://gist.github.com/arthurportas/525e43b01aecdd780c6a234226da6f26

Employee DAO Tests
https://gist.github.com/arthurportas/fde2b404ba6c7acdcc0cff4c81b0a406

‘staffgest-persistence-hibernate-jpa‘  – is a maven project, so it should be fairly simple to import and build it.
Hope it’s helpful for someone!

Sample project using Plain JavaSE – Episode 2

Hi, this is the second post of a series where i’ll be publishing some samples showing how to develop web applications with Java technology.
This post sample consists on a project ‘staffgest-jsf‘ that serves as presentation layer using JSF.

This web app is deployed on a embedded Glassfish server .
You can read more about Glassfish Embedded in here.
You can read more about JSF in here.
For more context please refer to the previous post.

The proposed flow on the web application  is:

  1.  Visit – ‘localhost:8080/staffgest-mvc-jsp/new-employee.xhtml’ , where a form to create an employee is showed
    – submit form and “new-employee-result.xhtml” is rendered
  2. Visit – ‘localhost:8080/staffgest-mvc-jsp/search-employee.xhtml’ , where a form to search an employee is showed
    – submit form and “search-employee-result.xhtml” is rendered

Relevant code snippets:

JSF configuration on web.xml
https://gist.github.com/arthurportas/020083d56a8b840eabec350c30b7fb83

Employee Backing Bean
https://gist.github.com/arthurportas/0a2e6bfc8f834144a14cbc47f025d4dd

Views
“new-employee.xhtml”
https://gist.github.com/arthurportas/b726d951faf0c9b380601fc0bd20a12b

“new-employee-result.xhtml”
https://gist.github.com/arthurportas/1d0ad841517f6714fed8764cb318e145

“search-employee.xhtml”
https://gist.github.com/arthurportas/20393e1abb5524657bdae77632bbd3cd

“search-employee-result.xhtml”
https://gist.github.com/arthurportas/a274c18566805c4e3b1bdaab95b3b866

‘staffgest-mdw‘ ,  ‘staffgest-jsf‘  – are all maven projects, so it should be fairly simple to import and build it. First build “staffgest-mdw” and the run “staffgest-jsf” through a main class ‘App.java’.
Hope it’s helpful for someone!

 

Sample project using Plain JavaSE – Episode 1

Hi, this is the initial post of a series where i’ll be publishing some samples showing how to develop web applications with Java technology.
I’ll try to start with a very simple example and make some progress visiting several APIs/Application Servers  from the JEE stack.
This post sample consists on three projects that only uses POJOs.
The adopted subject is an application with codename ‘staffgest’ with employee management APIs.

The adopted architecture consists on a base project -”staffgest-mdw” that has the middleware service layer and the persistence layer(very simple, in memory List).
Through our journey, i’ll be decoupling the persistence layer and the presentation layer for demonstration purposes.
I’ll deliver two sample projects – “staffgest-text” and “staffgest-mvc-jsp” having the presentation layer for -”staffgest-mdw”.
“staffgest-text” is a JSE console app and”staffgest-mvc-jsp” is a web app deployed on a embedded Glassfish server .
You can read more about Glassfish Embedded in here.

The proposed flow on the web application  is:

  1.  Visit – ‘localhost:8080/staffgest-mvc-jsp/new-employee.html’ , where a form to create an employee is showed
    – submit form and “new-employee.jsp” is rendered
    Feedback welcome!
  2. Visit – ‘localhost:8080/staffgest-mvc-jsp/search-employee.html’ , where a form to search an employee is showed
    – submit form and “search-employee.jsp” is rendered

Relevant code snippets:

Controller

package com.arthurportas.presentation.servlets;
import com.arthurportas.entities.Employee;
import com.arthurportas.services.EmployeeService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by arthurportas on 22/04/2017.
*/
@WebServlet(urlPatterns = "/employee")
public class EmployeeController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String value = req.getParameter("value");
Employee employee = getEmployeeService().findbyName(value);
req.setAttribute("emp", employee);
req.getRequestDispatcher("search-employee.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String firstName = req.getParameter("firstName");
String lastName = req.getParameter("firstName");
Employee employee = new Employee();
employee.setFirstName(firstName);
employee.setLastName(lastName);
employee = getEmployeeService().create(employee);
req.setAttribute("emp", employee);
req.getRequestDispatcher("new-employee.jsp").forward(req, resp);
}
private EmployeeService getEmployeeService() {
return new EmployeeService();
}
}

Views
“new-employee.html”

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>::StaffGest:: - new-employee</title>
<meta name="description" content="StaffGest:: - search-employee">
<meta name="author" content="Arthur Portas">
</head>
<body>
<form action="/staffgest-mvc-jsp/employee" method="post">
First name:<br>
<input type="text" name="firstName" value="Arthur">
<br>
Last name:<br>
<input type="text" name="lastName" value="Portas">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

“new-employee.jsp”

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>New Employee</title>
</head>
<body>
Employee created with success!
${emp}
</body>
</html>

“search-employee.html”

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>::StaffGest:: - search-employee</title>
<meta name="description" content="StaffGest:: - search-employee">
<meta name="author" content="Arthur Portas">
</head>
<body>
<form action="/staffgest-mvc-jsp/employee" method="get">
Enter search criteria:<br>
<input type="text" name="value" value="Arthur">
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>

“search-employee.jsp”

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Search Employee</title>
</head>
<body>
Search results: ${emp}
</body>
</html>

‘staffgest-mdw‘ ,  ‘staffgest-text‘ , ‘staffgest-mvc-jsp‘ – are all maven projects, so it should be fairly simple to import and build it. First build “staffgest-mdw” and the run “staffgest-text” or “staffgest-mvc-jsp” through a main class ‘App.java’.
Hope it’s helpful for someone!

Sample project using Spring Boot, MongoDB(Fongo) with a scheduled maintenance job and test repository with NoSqlUnit

Hi, this is the another post of a series where i’ll be publishing some samples showing how to work with MongoDB documents with Java.
This post sample consists on a project that uses spring-boot with spring-data-mongo repository, Fongo(an in-memory mongodb representation) and a schedule maintenance job to delete user records.
We will also use NoSqlUnit – a helper library for tests.
For a cleaner document object, we use Lombok.

You can read more about scheduling-tasks in here.

This project uses the same structure of the one in my previous post.

User document.

package com.arthurportas.mongodb.example.domain;
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.time.ZonedDateTime;
import java.util.Date;
/**
* Created by arthurportas on 21/01/2017.
*/
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Document
public class User {
@Id
private String id;
private String firstName;
private String lastName;
private String email;
private Date lastUpdated;
}
view raw User.java hosted with ❤ by GitHub

User repository.

package com.arthurportas.mongodb.example.repository;
import com.arthurportas.mongodb.example.domain.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.List;
/**
* Created by arthurportas on 21/01/2017.
*/
@Repository
public interface UserRepository extends MongoRepository<User, String>{
List<User> findByLastUpdated(Date date);
List<User> findByLastUpdatedLessThan(Date date);
void deleteByLastUpdatedLessThan(Date date);
}

Scheduled tasks.

package com.arthurportas.mongodb.example.tasks;
import com.arthurportas.mongodb.example.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;
/**
* Created by arthurportas on 24/01/2017.
*/
@Component
public class ScheduledTasks {
private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledTasks.class);
@Autowired
private UserRepository userRepository;
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRateString = "${users.scheduled.maintenance}")//every five seconds we clean records older than current time -1 day
public void deleteUserRecords() throws ParseException {
Date currentDate = new Date();
LOGGER.info("The time now is {}, deleting {} records", dateFormat.format(currentDate),
userRepository.findByLastUpdatedLessThan(Date.from(Instant.now().minus(1, ChronoUnit.DAYS))).size());//this is an ugly count query :\
userRepository.deleteByLastUpdatedLessThan(currentDate);
}
}

Configuration.

package com.arthurportas.mongodb.example.config;
import com.github.fakemongo.Fongo;
import com.mongodb.Mongo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* Created by arthurportas on 21/01/2017.
*/
@ComponentScan(basePackages = "com.arthurportas.mongodb.example")
@EnableMongoRepositories(basePackages = "com.arthurportas.mongodb.example.repository")
@EnableScheduling
@Configuration
public class FongoConfiguration extends AbstractMongoConfiguration {
@Override
protected String getDatabaseName() {
return "demo-test";
}
@Bean
@Override
public Mongo mongo() {
// uses fongo for in-memory tests
return new Fongo("mongo-test").getMongo();
}
@Override
protected String getMappingBasePackage() {
return "com.arthurportas.mongodb.example.domain";
}
}

At this point we can run the app and what the logs to see the scheduled job in action.

captura-de-ecra%cc%83-2017-01-28-as-19-50-48

Having the app running if we run the test ‘testCountAllUsersNotUpdatedOnLast24Hours’
we can check that all users from the dataset ‘five-users.json’ are loaded and when the schedule job runs it deletes all the five records. All records have the property ‘lastUpdated’ with values that exceed more than 24 hours from now.

Sample data to load using NoSqlUnit.

{
"user": {
"data": [
{
"id": "119bbacd-9c03-4044-867f-4c26e8f715f6",
"firstName": "Arthur",
"lastName": "Portas",
"email": "arthurportas[AT]gmail.com",
"lastUpdated": {
"$date": "2017-01-24T10:09:15.210Z"
}
},
{
"id": "f0f45a6f-77af-44a6-b872-8ee139534afb",
"firstName": "John",
"lastName": "Doe",
"email": "jondoe[AT]gmail.com",
"lastUpdated": {
"$date": "2017-01-23T10:09:15.210Z"
}
},
{
"id": "a85e5ed7-1a63-4bd9-b460-0ecb0cc1327e",
"firstName": "Pamela",
"lastName": "Anderson",
"email": "pamelaanderson[AT]gmail.com",
"lastUpdated": {
"$date": "2017-01-23T10:09:15.210Z"
}
},
{
"id": "6d876643-c60b-4fd9-a7ae-be4df2b0d466",
"firstName": "Soraia",
"lastName": "Chaves",
"email": "soraiachaves[AT]gmail.com",
"lastUpdated": {
"$date": "2017-01-23T10:09:15.210Z"
}
},
{
"id": "2a734390-673f-490a-aed1-c0bb580847a6",
"firstName": "Ines",
"lastName": "Branco",
"email": "inesbranco[AT]gmail.com",
"lastUpdated": {
"$date": "2017-01-22T10:09:15.210Z"
}
}
]
}
}
view raw five-users.json hosted with ❤ by GitHub

Sample test.

package com.arthurportas.repository;
import com.arthurportas.mongodb.example.repository.UserRepository;
import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
import com.lordofthejars.nosqlunit.annotation.UsingDataSet;
import com.lordofthejars.nosqlunit.core.LoadStrategyEnum;
import com.lordofthejars.nosqlunit.mongodb.InMemoryMongoDb;
import com.lordofthejars.nosqlunit.mongodb.MongoDbRule;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;
import static com.lordofthejars.nosqlunit.mongodb.InMemoryMongoDb.InMemoryMongoRuleBuilder.newInMemoryMongoDbRule;
import static com.lordofthejars.nosqlunit.mongodb.MongoDbRule.MongoDbRuleBuilder.newMongoDbRule;
import static org.assertj.core.api.Java6Assertions.assertThat;
/**
* Created by arthurportas on 21/01/2017.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class UserRepositoryTest {
private static Logger LOGGER = LoggerFactory.getLogger(UserRepositoryTest.class);
@ClassRule
public static InMemoryMongoDb inMemoryMongoDb = newInMemoryMongoDbRule().build();
@Rule
public MongoDbRule mongoDbRule = newMongoDbRule().defaultSpringMongoDb("demo-test");
/**
* nosql-unit requirement
*/
@Autowired
private ApplicationContext applicationContext;
@Autowired
private UserRepository userRepository;
@Test
@UsingDataSet(locations = {"/five-users.json"}, loadStrategy = LoadStrategyEnum.CLEAN_INSERT)
public void testCountAllUsers() {
LOGGER.info("testCountAllUsers");
long total = this.userRepository.findAll().size();
assertThat(total).isEqualTo(5);
}
@Test
@UsingDataSet(locations = {"/five-users.json"}, loadStrategy = LoadStrategyEnum.CLEAN_INSERT)
public void testCountAllUsersByLastUpdated() throws ParseException {
LOGGER.info("testCountAllUsersByLastUpdated");
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse("2017-01-24T10:09:15.210");
long total = this.userRepository.findByLastUpdated(date).size();
assertThat(total).isEqualTo(1);
}
@Test
@UsingDataSet(locations = {"/five-users.json"}, loadStrategy = LoadStrategyEnum.CLEAN_INSERT)
public void testCountAllUsersNotUpdatedOnLast24Hours() throws ParseException, InterruptedException {
LOGGER.info("testCountAllUsersUpdatedOnLast24Hours");
Thread.sleep(10000);
assertThat(this.userRepository.count()).isEqualTo(0);
}
}

 Logs.
captura-de-ecra%cc%83-2017-01-28-as-20-05-42
 captura-de-ecra%cc%83-2017-01-28-as-20-07-32
‘fongo-scheduled-job‘ – is a maven project, so it should be fairly simple to import and build it.
Hope it’s helpful for someone!

Sample project using Spring Boot and MongoDB(Fongo) and test repository with NoSqlUnit

Hi, this is the initial post of a series where i’ll be publishing some samples showing how to work with MongoDB documents with Java.
This post sample consists on a project that uses spring-boot with spring-data-mongo repository, Fongo(an in-memory mongodb representation) and NoSqlUnit – a helper library for tests.
For a cleaner document object, we use Lombok.

You can read more about Fongo in here.
You can read more about NoSqlUnit in here.
You can read more about Spring-data-mongo in here.
You can read more about Lombok in here.

User document.

package com.arthurportas.mongodb.example.domain;
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
/**
* Created by arthurportas on 21/01/2017.
*/
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Document
public class User {
@Id
private String id;
private String firstName;
private String lastName;
private String email;
}
view raw User.java hosted with ❤ by GitHub

User repository.

package com.arthurportas.mongodb.example.repository;
import com.arthurportas.mongodb.example.domain.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
/**
* Created by arthurportas on 21/01/2017.
*/
@Repository
public interface UserRepository extends MongoRepository<User, String>{
}

Sample data to load using NoSqlUnit.

{
"user": {
"data": [
{
"id": "119bbacd-9c03-4044-867f-4c26e8f715f6",
"firstName": "Arthur",
"lastName": "Portas",
"email": "arthurportas[AT]gmail.com"
},
{
"id": "f0f45a6f-77af-44a6-b872-8ee139534afb",
"firstName": "John",
"lastName": "Doe",
"email": "jondoe[AT]gmail.com"
},
{
"id": "a85e5ed7-1a63-4bd9-b460-0ecb0cc1327e",
"firstName": "Pamela",
"lastName": "Anderson",
"email": "pamelaanderson[AT]gmail.com"
},
{
"id": "6d876643-c60b-4fd9-a7ae-be4df2b0d466",
"firstName": "Soraia",
"lastName": "Chaves",
"email": "soraiachaves[AT]gmail.com"
},
{
"id": "2a734390-673f-490a-aed1-c0bb580847a6",
"firstName": "Ines",
"lastName": "Branco",
"email": "inesbranco[AT]gmail.com"
}
]
}
}
view raw five-users.json hosted with ❤ by GitHub

Sample test.

package com.arthurportas.unit.repository;
import com.arthurportas.mongodb.example.repository.UserRepository;
import com.lordofthejars.nosqlunit.annotation.UsingDataSet;
import com.lordofthejars.nosqlunit.core.LoadStrategyEnum;
import com.lordofthejars.nosqlunit.mongodb.MongoDbRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static com.lordofthejars.nosqlunit.mongodb.MongoDbRule.MongoDbRuleBuilder.newMongoDbRule;
import static org.assertj.core.api.Java6Assertions.assertThat;
/**
* Created by arthurportas on 21/01/2017.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class UserRepositoryTest {
private static Logger LOGGER = LoggerFactory.getLogger(UserRepositoryTest.class);
@Rule
public MongoDbRule mongoDbRule = newMongoDbRule().defaultSpringMongoDb("demo-test");
/**
* nosql-unit requirement
*/
@Autowired
private ApplicationContext applicationContext;
@Autowired
private UserRepository userRepository;
@Test
@UsingDataSet(locations = {"/five-users.json"}, loadStrategy = LoadStrategyEnum.CLEAN_INSERT)
public void testCountAllUsers() {
LOGGER.info("testCountAllUsers");
long total = this.userRepository.findAll().size();
assertThat(total).isEqualTo(5);
}
}

Configuration

package com.arthurportas.config;
import com.github.fakemongo.Fongo;
import com.mongodb.Mongo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
/**
* Created by arthurportas on 21/01/2017.
*/
@ComponentScan(basePackages = "com.arthurportas.mongodb.example")
@EnableMongoRepositories(basePackages = "com.arthurportas.mongodb.example.repository")
@Configuration
public class FongoConfiguration extends AbstractMongoConfiguration {
@Override
protected String getDatabaseName() {
return "demo-test";
}
@Bean
@Override
public Mongo mongo() {
// uses fongo for in-memory tests
return new Fongo("mongo-test").getMongo();
}
@Override
protected String getMappingBasePackage() {
return "com.arthurportas.mongodb.example.domain";
}
}

‘fongo-hello-world‘ – is a maven project, so it should be fairly simple to import and build it. Run the test on class ‘UserRepositoryTest’.
Hope it’s helpful for someone!

Sample project using JasperReports to generate pdf documents

Hi, this is the initial post of a series where i’ll be publishing some samples showing how to generate pdf documents with the popular library JasperReports using the Java API.

You can read more about JasperReports in here.
Pdf document templates were designed with iReport Designer

Sample code to generate blank pdf document.

package com.arthurportas.jasperreports;
import net.sf.jasperreports.engine.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
/*
* Sample hello world pdf generation
* */
public class JasperReportsApplication {
private static final Logger logger = LoggerFactory.getLogger(JasperReportsApplication.class);
/*
* There are basically four steps to a finished product:
* <X> Design a report with Jaspersoft iReport Designer to produce a JRXML file and add it to application classpath.
* <X> Compile the report to a binary, serialized JasperReport (.jasper) file and save to disk.
* <X> Fill the compiled report with data.
* <X> Export it to pdf.
*/
public static void main(String[] args) throws Exception {
logger.debug("Starting up...");
// first, we open the XML template
logger.info("Opening the JRXML template file.");
InputStream template = JasperReportsApplication.class
.getResourceAsStream("/hello.jrxml");
// now, fill out the report
logger.info("Compiling report and filling it out.");
JasperReport report = JasperCompileManager.compileReport(template);
HashMap<String, Object> parameters = new HashMap<String, Object>();
parameters.put("hello", "hello world");
// it's important to provide an instance of JREmptyDataSource otherwise by default the report will have no pages
JasperPrint print = JasperFillManager.fillReport(report, parameters, new JREmptyDataSource());
// finally, export it to PDF
logger.info("Exporting the filled out report to a file.");
// for test purposes we should create a temp tile with File.createTempFile(),
// but in Mac Os this goes to /var/folder and it's not that accessible...
// adjust the file path according to your file system
File pdfOutputFile = new File("/Users/arthurportas/tmp/jasper.pdf");
pdfOutputFile.deleteOnExit();
JasperExportManager.exportReportToPdfStream(print, new FileOutputStream(pdfOutputFile));
// now sleep indefinitely to allow for preview but to wipe the files on JVM exit
logger.info("Done with export. Find the file at \"{}\" then end this process when done.",
pdfOutputFile.getAbsolutePath());
while (true) {
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
logger.info("Exiting now.");
}
}
}
}

Project samples:

*All running tests create a pdf document in the hard-coded path set and hang the current java process.While the process is running you can preview the pdf with your favourite tool.
When you stop this process, the document is deleted. This is the behaviour.

‘jasperreports-hello-world-pdf‘ – is the simplest sample where a blank pdf is generated. Run the main class ‘JasperReportsApplication’ and adjust the directory where the pdf file is created to fit your environment.

‘jasperreports-pdf-image‘ – this sample shows how to insert an images in several ways inside a pdf.
Run the tests declared in ‘ImageIT’ and adjust the directory where the pdf file is created to fit your environment.

jasperreports-pdf-table‘ – this sample shows how to fill a table with data inside a pdf using a ‘JRBeanCollectionDataSource’.
Run the test in ‘TableIT’ and adjust the directory where the pdf file is created to fit your environment.

Sample spring mongodb project setup with mongodb custom type converters

Hi, bellow i’ll post a sample Spring-Boot example project setup using Spring-Data MongoDb Repositories with custom converters
The goal is to use Java types like BigDecimal in MongoDb persistence layer and having these converted to correspondent Bson Type.

You can read more about mongoDb in here.
You can read more about BSON in here.
You can read more about BSON | Java types in here.

 

import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableMongoRepositories(basePackages = "com.arthurportas.repo.mongo")
@ComponentScan(basePackages = "com.arthurportas")
public class SpringMongoConfig extends AbstractMongoConfiguration {
@Value("${mongo.host}")//read from config
private String host;
@Value("${mongo.port}")//read from config
private int port;
@Value("${mongo.db}")//read from config
private String databaseName;
@Value("${mongo.username}")//read from config
private String userName;
@Value("${mongo.password}")//read from config
private String password;
private final List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>();
@Override
public String getDatabaseName() {
return databaseName;
}
@Override
@Bean
public Mongo mongo() throws Exception {
return new MongoClient(serverAddress(), Arrays.asList(mongoCredential()));
}
@Override
protected String getMappingBasePackage() {
return "com.arthurportas.domain.mongo.entities";
}
@Bean
public ServerAddress serverAddress() throws Exception {
return new ServerAddress();//TODO: read host+port from config
}
@Bean
public MongoCredential mongoCredential() {
return MongoCredential.createCredential(
this.userName,
getDatabaseName(),
this.password.toCharArray());
}
@Override
public CustomConversions customConversions() {
converters.add(new BigDecimalToDoubleConverter());
converters.add(new DoubleToBigDecimalConverterp());
return new CustomConversions(converters);
}
}
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
@Component
public class BigDecimalToDoubleConverter implements Converter<BigDecimal, Double> {
@Override
public Double convert(BigDecimal source) {
return source.doubleValue();
}
}
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.math.RoundingMode;
@Component
public class DoubleToBigDecimalConverter implements Converter<Double, BigDecimal> {
@Override
public BigDecimal convert(Double source) {
return new BigDecimal(source).setScale(2, RoundingMode.HALF_UP);
}
}

Sample spring-data mongodb project setup with querydsl

Hi, bellow i’ll post a sample Spring-Boot example project setup using Spring-Data MongoDb Repositories with QueryDSL metamodel generation.
The goal is to query MongoDb persistence layer using spring-data.
Upcoming recipes will show QueryDSL custom queries to MongoDb.

You can read more about spring-data-mongodbin here.
You can read more about query-dsl in here.
You can read more about mongoDb in here.

import org.springframework.data.mongodb.repository.MongoRepository;
import com.arthurportas.domain.mongo.entities.User;
public interface UserRepository extends MongoRepository<User, Long> {
User findBySid(UUID userSid);
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt;
<modelVersion>4.0.0</modelVersion>
<groupId>com.arthurportas</groupId>
<artifactId>com.arthurportas.data.mongo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SPRING_DATA_MONGO_QUERY_DSL</name>
<description></description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<querydsl.version>4.0.7</querydsl.version>
<querydsl.apt-maven-plugin.version>1.1.3</querydsl.apt-maven-plugin.version>
<com.mysema.querydsl.version>3.7.1</com.mysema.querydsl.version>
</properties>
<dependencies>
<!-- Querydsl -->
<dependency>
<groupId>com.mysema.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>${com.mysema.querydsl.version}</version>
</dependency>
<dependency>
<groupId>com.mysema.querydsl</groupId>
<artifactId>querydsl-mongodb</artifactId>
<version>${com.mysema.querydsl.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Generates the MongoDB static meta model -->
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>${querydsl.apt-maven-plugin.version}</version>
<executions>
<execution>
<id>process-common-model</id>
<goals>
<goal>process</goal>
</goals>
<configuration>
<!--target folder with generated metamodels Qxxxx.java-->
<outputDirectory>target/generated-sources/apt</outputDirectory>
<processors>
<processor>org.springframework.data.mongodb.repository.support.MongoAnnotationProcessor</processor>
</processors>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.mysema.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>${com.mysema.querydsl.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
view raw pom.xml hosted with ❤ by GitHub
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import java.util.Arrays;
@Configuration
@EnableMongoRepositories(basePackages = "com.arthurportas.repo.mongo")
@ComponentScan(basePackages = "com.arthurportas")
public class SpringMongoConfig extends AbstractMongoConfiguration {
@Value("${mongo.host}")//read from config
private String host;
@Value("${mongo.port}")//read from config
private int port;
@Value("${mongo.db}")//read from config
private String databaseName;
@Value("${mongo.username}")//read from config
private String userName;
@Value("${mongo.password}")//read from config
private String password;
@Override
public String getDatabaseName() {
return databaseName;
}
@Override
@Bean
public Mongo mongo() throws Exception {
return new MongoClient(serverAddress(), Arrays.asList(mongoCredential()));
}
@Override
protected String getMappingBasePackage() {
return "com.arthurportas.domain.mongo.entities";
}
@Bean
public ServerAddress serverAddress() throws Exception {
return new ServerAddress();//TODO: read host+port from config
}
@Bean
public MongoCredential mongoCredential() {
return MongoCredential.createCredential(
this.userName,
getDatabaseName(),
this.password.toCharArray());
}
}
import java.math.BigInteger;
import java.time.Instant;
import java.util.Map;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = User.USERS_COLLECTION_NAME)
public class User {
public static final String USERS_COLLECTION_NAME = "users_docs";
@Id
private BigInteger id;
@Indexed(unique = true)
UUID sid;
String name;
String email;
Map<String, String> attributes;
Instant createdAt;
Instant updatedAt;
// … getters and setters omitted
}
view raw User.java hosted with ❤ by GitHub
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.arthurportas.repo.mongo.UserRepository;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User saveUser(User user) throws Exception {
return userRepository.save(user);
}
}