Compare commits

...

62 Commits

Author SHA1 Message Date
Artur Kuksin
a672db346c Merge pull request #273 from ajibade3210/nodeGraphql
Node graphql
2023-03-22 16:55:46 +01:00
olaoluwa ajibade
27b63f4305 node graphql code example 2023-03-13 05:39:38 +01:00
olaoluwa ajibade
b18444293b node graphql code example 2023-03-13 05:36:45 +01:00
Artur Kuksin
5a9dd70280 Merge pull request #265 from ranjanih/ranjani-security
Getting started with Spring Security and Spring boot
2023-02-28 18:25:41 +01:00
ranjani2412
bd257c811d Updates 2023-02-21 00:17:42 +11:00
ranjani2412
8a76f45358 TestCases 2023-02-19 07:56:06 +11:00
ranjani2412
14b95378d1 Merge branch 'master' into ranjani-security 2023-02-15 03:48:23 +11:00
ranjani2412
6d8d03a64e Updates 2023-02-15 03:34:28 +11:00
ranjani2412
1f5bea6af9 Usescases 2023-02-13 10:35:53 +11:00
ranjani2412
1ed363389f Code updates 2023-02-09 23:59:57 +11:00
Abdulcelil Cercenazi
5fc64d1662 add JUnit5 code (#217)
* add JUnit5 code

* modify JUnit5 code
2023-01-31 12:46:51 +11:00
Artur Kuksin
179201f367 Merge pull request #259 from pralhad-cmd/PH-junit5-parameterized-tests
Code examples for - Parameterized tests with JUnit 5
2023-01-30 08:39:41 +01:00
Pralhad” Hadimani
41ba0f8600 Code examples for - Parameterized tests with JUnit 5 2023-01-29 00:28:50 +00:00
Pralhad” Hadimani
7758c342bc Bonus code example for - Parameterized tests with JUnit 5 2023-01-27 23:09:17 +00:00
Pralhad” Hadimani
8f2452bc69 Code examples for - Parameterized tests with JUnit 5 2023-01-25 16:07:56 +00:00
ranjani2412
df54ae491f Updates 2023-01-12 17:31:58 +11:00
ranjani2412
f2e38be788 Updates to usecases 2023-01-11 05:04:01 +11:00
ranjani2412
ec0cca1c8b Initial commit 2022-12-10 08:25:32 +11:00
Abdulcelil Cercenazi
f3f3e622e2 add code for Dependency Injection and Inversion of Control post (#237) 2022-12-08 10:56:16 +11:00
Arpendu Kumar Garai
cd69fa5842 code example for CSV Importer with Node
Co-authored-by: Arpendu Kumar Garai <Arpendu.KumarGarai@microfocus.com>
2022-12-05 09:50:13 +11:00
Arpendu Kumar Garai
3930e1cb03 Test and Automate Features behind the Flags using Cypress Tests (#206)
* nodejs cypress test launchdarkly

* Delete README.md

* refactor code

* refactor code

* code cleanup

Co-authored-by: Arpendu Kumar Garai <Arpendu.KumarGarai@microfocus.com>
2022-11-07 19:51:48 +11:00
Olaoluwa Ajibade
cd3e68cc66 Adding UrlShortener (#219) 2022-11-04 10:46:47 +11:00
ranjanih
06af47eb4b Spring CSRF (#223)
* Initial test commit

* Update UN PWD

* Updates

* Updates

* Updates

* Test updates

* Updates to tests

* Updates to code

* Update README

Co-authored-by: ranjani2412 <53815317+ranjani2412@users.noreply.github.com>
2022-10-21 10:41:40 +11:00
Arpendu Kumar Garai
f96a02270e Feature Flags in NodeJs React using LaunchDarkly (#205)
* nodejs react launchdarkly

* minor changes

* code refactor

* code refactor

Co-authored-by: Arpendu Kumar Garai <Arpendu.KumarGarai@microfocus.com>
2022-10-11 06:49:45 +11:00
Arpendu Kumar Garai
093221423e Feature Flags in Node.js Backend with LaunchDarkly (#204)
* nodejs-launchdarkly

* segregating code examples

* refactoring the code sections

* refactor directory name

* minor changes

* addressed review comments

* review comments

* review comments

Co-authored-by: Arpendu Kumar Garai <Arpendu.KumarGarai@microfocus.com>
2022-10-11 06:49:21 +11:00
ranjanih
d61382d459 Spring Boot timezones (#218)
* Files

* Updates to timezone-app

* Unit tests and config changes

* Review updates

* Updates to includes more asserts

* Remove sout

* Updates

Co-authored-by: ranjani2412 <53815317+ranjani2412@users.noreply.github.com>
2022-09-26 08:04:48 -05:00
Olaoluwa Ajibade
995a80b24b New Node-Job-Scheduler (#216) 2022-09-05 06:18:06 +10:00
ranjanih
52ce0d921f Configure cors with Spring (#209)
* Initial example

* Spring Webflux application

* Webflux filter

* Working samples

* Spring Web & Webflux initializr projects

* README updates

Co-authored-by: ranjani2412 <53815317+ranjani2412@users.noreply.github.com>
2022-09-01 06:46:01 +10:00
Olaoluwa Ajibade
126fa44d97 Adding NodeJs Logging CodeExamples (#199)
* Adding NodeJs Logging CodeExamples

* Adding NodeJs Logging CodeExamples
2022-07-25 09:51:25 +10:00
dzkaiten
b070b3376b Spring Cloud Tracing Demo Fixes (#188)
* Spring Cloud Tracing Demo Fixes

* Update docker-compose.yml
2022-07-15 06:37:56 +10:00
Anatolij Vasilev
a66b6a0aaa fixed broken link (#196)
The link in the readme was pointing to a 404 page
2022-07-15 06:36:55 +10:00
Abdulcelil Cercenazi
3d2be288e5 Code for Jackson post (#197)
* add the initial maven project

* add a few code examples

* add a few code examples

* add a few code examples

* add a few code examples

* add a few code examples

* add JsonAnyGetter example
2022-07-15 06:34:05 +10:00
Artur Kuksin
937fee0773 Merge pull request #195 from pratikdas/kotlin-coroutines
Kotlin Coroutines
2022-07-14 21:19:31 +02:00
Pratik Das
f531c21c67 code modified 2022-06-25 23:36:15 +05:30
Pratik Das
80165c55ab added code 2022-06-19 18:53:55 +05:30
Pratik Das
e4f9bece6b added code 2022-06-19 06:34:58 +05:30
Pratik Das
7f1cab6e0a added code 2022-06-19 06:13:02 +05:30
Tom Hombergs
351804a083 Update README.md 2022-06-08 17:56:24 +02:00
Arpendu Kumar Garai
657539d435 mapstruct guide (#192)
Co-authored-by: Arpendu Kumar Garai <Arpendu.KumarGarai@microfocus.com>
2022-06-08 17:55:58 +02:00
Artur Kuksin
f3064e5fa0 Merge pull request #190 from pratikdas/axios
Complete guide to Axios
2022-05-20 12:28:32 +02:00
Pratik Das
c6127955bd added ts code 2022-05-19 06:31:10 +05:30
ranjanih
2185f9c68d Introduction to retrofit (#185)
* Initial 3rd party library application

* Add basic auth to app and swagger-ui

* Modifications

* Audit application Initial commit

* Update README

* Application header changes

* Caching

* sync async requests

* Additional changes

* Unit tests

* Updates

* Mistaken refactoring

* Mistaken refactoring

* Mock updates

* Test updates

* Updates

Co-authored-by: ranjani2412 <53815317+ranjani2412@users.noreply.github.com>
2022-05-18 06:27:51 +10:00
Pratik Das
bd8c084a88 added code 2022-05-17 19:43:10 +05:30
Tom Hombergs
1d9c841d88 Update README.md 2022-05-08 06:46:22 +10:00
Artur Kuksin
ce10f21788 Merge pull request #184 from pratikdas/java-streams
Java streams
2022-05-05 11:37:53 +02:00
Artur Kuksin
8a7948a1b3 Merge branch 'master' into java-streams 2022-05-05 11:36:12 +02:00
Arpendu Kumar Garai
0372c85220 spring-reactive-architecture (#182)
Co-authored-by: Arpendu Kumar Garai <Arpendu.KumarGarai@microfocus.com>
2022-05-05 06:23:29 +10:00
Pratik Das
a5455521df added code 2022-04-29 21:11:59 +05:30
Pratik Das
89bd3b6729 added code 2022-04-29 21:08:35 +05:30
Pratik Das
a9bd712afe Merge branch 'node-errorhandling' of https://github.com/pratikdas/code-examples into node-errorhandling 2022-03-30 16:25:31 +05:30
Pratik Das
e1dae42a19 added readme for middleware article 2022-03-30 16:24:50 +05:30
Pratik Das
041442297e Merge branch 'master' into node-errorhandling 2022-03-30 11:04:29 +05:30
Pratik Das
2223be80c9 error handling code 2022-03-30 10:01:45 +05:30
Pratik Das
385c8f7e96 updated code 2022-03-16 11:36:12 +05:30
Pratik Das
a937ad3f96 Merge branch 'master' into aws-kinesis 2022-03-02 22:46:17 +05:30
Pratik Das
107586e6e5 added code 2022-03-02 22:36:19 +05:30
Pratik Das
843bfe6ad9 Merge branch 'express-get-start' of https://github.com/pratikdas/code-examples into express-get-start 2022-02-13 22:32:33 +05:30
Pratik Das
de2d608c1d added ts files 2022-02-13 22:32:02 +05:30
Pratik Das
72cca1debc Merge branch 'master' into express-get-start 2022-02-03 22:57:33 +05:30
Pratik Das
6d122d285b added code examples 2022-02-03 22:55:10 +05:30
Pratik Das
aa952c0b18 removed cdk code 2022-01-27 20:24:12 +05:30
Pratik Das
98b3c96274 added code 2022-01-26 19:32:21 +05:30
648 changed files with 113504 additions and 5 deletions

View File

@@ -87,6 +87,8 @@ if [[ "$MODULE" == "module7" ]]
then
# ADD NEW MODULES HERE
# (add new modules above the rest so you get quicker feedback if it fails)
build_gradle_module "kotlin/coroutines"
build_maven_module "core-java/streams/data-streams"
build maven_module "aws/kinesis"
build maven_module "aws/sqs"
build_maven_module "core-java/annotation-processing/introduction-to-annotations"

29
core-java/jackson/jackson/.gitignore vendored Normal file
View File

@@ -0,0 +1,29 @@
HELP.md
target/*
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

View File

@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<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.reflectoring</groupId>
<artifactId>jackson</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.13.3</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.9.0-M1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.23.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,24 @@
package com.reflectoring.pojo;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonSetter;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.util.HashMap;
import java.util.Map;
@NoArgsConstructor
@AllArgsConstructor
@Getter
public class Car {
@JsonSetter("carBrand")
private String brand;
private Map<String, String> unrecognizedFields = new HashMap<>();
@JsonAnySetter
public void allSetter(String fieldName, String fieldValue) {
unrecognizedFields.put(fieldName, fieldValue);
}
}

View File

@@ -0,0 +1,29 @@
package com.reflectoring.pojo;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonGetter;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import java.util.Map;
@NoArgsConstructor
@AllArgsConstructor
public class Cat {
private String name;
@JsonAnyGetter
Map<String, String> map = Map.of(
"name", "Jack",
"surname", "wolfskin"
);
@JsonGetter("catName")
public String getName() {
return name;
}
public Cat(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,15 @@
package com.reflectoring.pojo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Getter
public class Dog {
private String name;
@JsonIgnore
private Integer age;
}

View File

@@ -0,0 +1,16 @@
package com.reflectoring.pojo;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.util.Date;
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
private String firstName;
private String lastName;
private int age;
}

View File

@@ -0,0 +1,18 @@
package com.reflectoring.pojo;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonSetter;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
@NoArgsConstructor
@AllArgsConstructor
@Getter
public class Order {
private int id;
@JsonFormat(pattern = "dd/MM/yyyy")
private LocalDate date;
}

View File

@@ -0,0 +1,184 @@
package com.reflectoring;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.reflectoring.pojo.*;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
public class JacksonTest {
ObjectMapper objectMapper = new ObjectMapper().findAndRegisterModules();
@Test
void jsonStringToPojo() throws JsonProcessingException {
String employeeJson = "{\n" +
" \"firstName\" : \"Jalil\",\n" +
" \"lastName\" : \"Jarjanazy\",\n" +
" \"age\" : 30\n" +
"}";
Employee employee = objectMapper.readValue(employeeJson, Employee.class);
assertThat(employee.getFirstName()).isEqualTo("Jalil");
}
@Test
void pojoToJsonString() throws JsonProcessingException {
Employee employee = new Employee("Mark", "James", 20);
String json = objectMapper.writeValueAsString(employee);
assertThat(json).isEqualTo("{\"firstName\":\"Mark\",\"lastName\":\"James\",\"age\":20}");
}
@Test
void jsonFileToPojo() throws IOException {
File file = new File("src/test/resources/employee.json");
Employee employee = objectMapper.readValue(file, Employee.class);
assertThat(employee.getAge()).isEqualTo(44);
assertThat(employee.getLastName()).isEqualTo("Simpson");
assertThat(employee.getFirstName()).isEqualTo("Homer");
}
@Test
void byteArrayToPojo() throws IOException {
String employeeJson = "{\n" +
" \"firstName\" : \"Jalil\",\n" +
" \"lastName\" : \"Jarjanazy\",\n" +
" \"age\" : 30\n" +
"}";
Employee employee = objectMapper.readValue(employeeJson.getBytes(), Employee.class);
assertThat(employee.getFirstName()).isEqualTo("Jalil");
}
@Test
void fileToListOfPojos() throws IOException {
File file = new File("src/test/resources/employeeList.json");
List<Employee> employeeList = objectMapper.readValue(file, new TypeReference<>(){});
assertThat(employeeList).hasSize(2);
assertThat(employeeList.get(0).getAge()).isEqualTo(33);
assertThat(employeeList.get(0).getLastName()).isEqualTo("Simpson");
assertThat(employeeList.get(0).getFirstName()).isEqualTo("Marge");
}
@Test
void fileToMap() throws IOException {
File file = new File("src/test/resources/employee.json");
Map<String, Object> employee = objectMapper.readValue(file, new TypeReference<>(){});
assertThat(employee.keySet()).containsExactly("firstName", "lastName", "age");
assertThat(employee.get("firstName")).isEqualTo("Homer");
assertThat(employee.get("lastName")).isEqualTo("Simpson");
assertThat(employee.get("age")).isEqualTo(44);
}
@Test
void fileToPojoWithUnknownProperties() throws IOException {
File file = new File("src/test/resources/employeeWithUnknownProperties.json");
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Employee employee = objectMapper.readValue(file, Employee.class);
assertThat(employee.getFirstName()).isEqualTo("Homer");
assertThat(employee.getLastName()).isEqualTo("Simpson");
assertThat(employee.getAge()).isEqualTo(44);
}
@Test
void orderToJson() throws JsonProcessingException {
Order order = new Order(1, LocalDate.of(1900,2,1));
String json = objectMapper.writeValueAsString(order);
System.out.println(json);
}
@Test
void orderToJsonWithDate() throws JsonProcessingException {
Order order = new Order(1, LocalDate.of(2023, 1, 1));
String json = objectMapper.writeValueAsString(order);
System.out.println(json);
}
@Test
void fileToOrder() throws IOException {
File file = new File("src/test/resources/order.json");
Order order = objectMapper.readValue(file, Order.class);
assertThat(order.getDate().getYear()).isEqualTo(2000);
assertThat(order.getDate().getMonthValue()).isEqualTo(4);
assertThat(order.getDate().getDayOfMonth()).isEqualTo(30);
}
@Test
void fileToCar() throws IOException {
File file = new File("src/test/resources/car.json");
Car car = objectMapper.readValue(file, Car.class);
assertThat(car.getBrand()).isEqualTo("BMW");
}
@Test
void fileToUnrecognizedCar() throws IOException {
File file = new File("src/test/resources/carUnrecognized.json");
Car car = objectMapper.readValue(file, Car.class);
assertThat(car.getUnrecognizedFields()).containsKey("productionYear");
}
@Test
void catToJson() throws JsonProcessingException {
Cat cat = new Cat("Monica");
String json = objectMapper.writeValueAsString(cat);
System.out.println(json);
}
@Test
void catToJsonWithMap() throws JsonProcessingException {
Cat cat = new Cat("Monica");
String json = objectMapper.writeValueAsString(cat);
System.out.println(json);
}
@Test
void dogToJson() throws JsonProcessingException {
Dog dog = new Dog("Max", 3);
String json = objectMapper.writeValueAsString(dog);
System.out.println(json);
}
@Test
void fileToDog() throws IOException {
File file = new File("src/test/resources/dog.json");
Dog dog = objectMapper.readValue(file, Dog.class);
assertThat(dog.getName()).isEqualTo("bobby");
assertThat(dog.getAge()).isNull();
}
}

View File

@@ -0,0 +1,3 @@
{
"carBrand" : "BMW"
}

View File

@@ -0,0 +1,4 @@
{
"carBrand" : "BMW",
"productionYear": 1996
}

View File

@@ -0,0 +1,4 @@
{
"name" : "bobby",
"age" : 5
}

View File

@@ -0,0 +1,5 @@
{
"firstName":"Homer",
"lastName":"Simpson",
"age":44
}

View File

@@ -0,0 +1,12 @@
[
{
"firstName":"Marge",
"lastName":"Simpson",
"age":33
},
{
"firstName":"Homer",
"lastName":"Simpson",
"age":44
}
]

View File

@@ -0,0 +1,6 @@
{
"firstName":"Homer",
"lastName":"Simpson",
"age":44,
"department": "IT"
}

View File

@@ -0,0 +1,4 @@
{
"id" : 1,
"date" : "30/04/2000"
}

View File

@@ -0,0 +1,8 @@
# Maven
target/
.mvn/
# eclipse project file
.settings/
.classpath
.project

View File

@@ -0,0 +1,3 @@
# Related Blog Posts
* [Parameterized tests with JUnit 5](https://reflectoring.io/junit5-parameterized-tests/)

287
core-java/junit5-parameterized-tests/mvnw vendored Executable file
View File

@@ -0,0 +1,287 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.1.1
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /usr/local/etc/mavenrc ] ; then
. /usr/local/etc/mavenrc
fi
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
JAVA_HOME="`/usr/libexec/java_home`"; export JAVA_HOME
else
JAVA_HOME="/Library/Java/Home"; export JAVA_HOME
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`\\unset -f command; \\command -v java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
printf '%s' "$(cd "$basedir"; pwd)"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=$(find_maven_basedir "$(dirname $0)")
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar"
else
wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) wrapperUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $wrapperUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
QUIET="--quiet"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
QUIET=""
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget $QUIET "$wrapperUrl" -O "$wrapperJarPath"
else
wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath"
fi
[ $? -eq 0 ] || rm -f "$wrapperJarPath"
elif command -v curl > /dev/null; then
QUIET="--silent"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
QUIET=""
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L
else
curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L
fi
[ $? -eq 0 ] || rm -f "$wrapperJarPath"
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaSource="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaSource=`cygpath --path --windows "$javaSource"`
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaSource" ]; then
if [ ! -e "$javaClass" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaSource")
fi
if [ -e "$javaClass" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
$MAVEN_DEBUG_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

View File

@@ -0,0 +1,187 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.1.1
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %WRAPPER_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% ^
%JVM_CONFIG_MAVEN_PROPS% ^
%MAVEN_OPTS% ^
%MAVEN_DEBUG_OPTS% ^
-classpath %WRAPPER_JAR% ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%"=="on" pause
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
cmd /C exit /B %ERROR_CODE%

View File

@@ -0,0 +1,33 @@
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.refactoring</groupId>
<artifactId>junit5-parameterized-tests</artifactId>
<version>1.0.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<junit-jupiter-params.version>5.9.2</junit-jupiter-params.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
<assertj-core>3.24.1</assertj-core>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-params -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit-jupiter-params.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,43 @@
package source.argument.conversion;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.time.temporal.ChronoUnit;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.converter.ConvertWith;
import org.junit.jupiter.params.provider.ValueSource;
public class ArgumentConversionTest {
@ParameterizedTest
@ValueSource(ints = { 2, 4 })
void checkWideningArgumentConversion(long number) {
assertEquals(0, number % 2);
}
// ---------------------------------------------------------------------------
@ParameterizedTest
@ValueSource(strings = "DAYS")
void checkImplicitArgumentConversion(ChronoUnit argument) {
assertNotNull(argument.name());
}
// ---------------------------------------------------------------------------
@ParameterizedTest
@ValueSource(strings = { "Name1", "Name2" })
void checkImplicitFallbackArgumentConversion(Person person) {
assertNotNull(person.getName());
}
// ---------------------------------------------------------------------------
@ParameterizedTest
@ValueSource(ints = { 100 })
void checkExplicitArgumentConversion(@ConvertWith(StringSimpleArgumentConverter.class) String argument) {
assertEquals("100", argument);
}
}

View File

@@ -0,0 +1,18 @@
package source.argument.conversion;
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,13 @@
package source.argument.conversion;
import org.junit.jupiter.params.converter.ArgumentConversionException;
import org.junit.jupiter.params.converter.SimpleArgumentConverter;
public class StringSimpleArgumentConverter extends SimpleArgumentConverter {
@Override
protected Object convert(Object source, Class<?> targetType) throws ArgumentConversionException {
return String.valueOf(source);
}
}

View File

@@ -0,0 +1,39 @@
package source.arguments;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.ArgumentsProvider;
import org.junit.jupiter.params.provider.ArgumentsSource;
public class ArgumentsSourceTest {
@ParameterizedTest
@ArgumentsSource(ExternalArgumentsProvider.class)
void checkExternalArgumentsSource(int number, String expected) {
assertEquals(StringUtils.equals(expected, "even") ? 0 : 1, number % 2,
"Supplied number " + number + " is not an " + expected + " number");
}
// ---------------------------------------------------------------------------
@ParameterizedTest
@ArgumentsSource(NestedArgumentsProvider.class)
void checkNestedArgumentsSource(int number, String expected) {
assertEquals(StringUtils.equals(expected, "even") ? 0 : 1, number % 2,
"Supplied number " + number + " is not an " + expected + " number");
}
static class NestedArgumentsProvider implements ArgumentsProvider {
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext context) throws Exception {
return Stream.of(Arguments.of(2, "even"), Arguments.of(3, "odd"));
}
}
}

View File

@@ -0,0 +1,16 @@
package source.arguments;
import java.util.stream.Stream;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.ArgumentsProvider;
public class ExternalArgumentsProvider implements ArgumentsProvider {
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext context) throws Exception {
return Stream.of(Arguments.of(2, "even"),
Arguments.of(3, "odd"));
}
}

View File

@@ -0,0 +1,18 @@
package source.arguments.aggregator;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.aggregator.ArgumentsAccessor;
import org.junit.jupiter.params.provider.CsvSource;
public class ArgumentsAccessorTest {
@ParameterizedTest
@CsvSource({ "John, 20",
"Harry, 30" })
void checkArgumentsAccessor(ArgumentsAccessor arguments) {
Person person = new Person(arguments.getString(0), arguments.getInteger(1));
assertTrue(person.getAge() > 19, person.getName() + " is a teenager");
}
}

View File

@@ -0,0 +1,24 @@
package source.arguments.aggregator;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.aggregator.AggregateWith;
import org.junit.jupiter.params.provider.CsvSource;
public class ArgumentsAggregatorTest {
@ParameterizedTest
@CsvSource({ "John, 20", "Harry, 30" })
void checkArgumentsAggregator(@AggregateWith(PersonArgumentsAggregator.class) Person person) {
assertTrue(person.getAge() > 19, person.getName() + " is a teenager");
}
// ---------------------------------------------------------------------------
@ParameterizedTest
@CsvSource({ "John, 20", "Harry, 30" })
void checkCustomAggregatorAnnotation(@CsvToPerson Person person) {
assertTrue(person.getAge() > 19, person.getName() + " is a teenager");
}
}

View File

@@ -0,0 +1,15 @@
package source.arguments.aggregator;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.params.aggregator.AggregateWith;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@AggregateWith(PersonArgumentsAggregator.class)
public @interface CsvToPerson {
}

View File

@@ -0,0 +1,30 @@
package source.arguments.aggregator;
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
}

View File

@@ -0,0 +1,16 @@
package source.arguments.aggregator;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.params.aggregator.ArgumentsAccessor;
import org.junit.jupiter.params.aggregator.ArgumentsAggregationException;
import org.junit.jupiter.params.aggregator.ArgumentsAggregator;
public class PersonArgumentsAggregator implements ArgumentsAggregator {
@Override
public Object aggregateArguments(ArgumentsAccessor arguments, ParameterContext context)
throws ArgumentsAggregationException {
return new Person(arguments.getString(0), arguments.getInteger(1));
}
}

View File

@@ -0,0 +1,27 @@
package source.assertj;
import java.util.function.Consumer;
import java.util.stream.Stream;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class AssertJTest {
@ParameterizedTest
@MethodSource("checkNumberArgs")
void checkNumber(int number, Consumer<Integer> consumer) {
consumer.accept(number);
}
static Stream<Arguments> checkNumberArgs() {
Consumer<Integer> evenConsumer = i -> Assertions.assertThat(i % 2).isZero();
Consumer<Integer> oddConsumer = i -> Assertions.assertThat(i % 2).isEqualTo(1);
return Stream.of(Arguments.of(2, evenConsumer), Arguments.of(3, oddConsumer));
}
}

View File

@@ -0,0 +1,17 @@
package source.csv;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class CsvSourceTest {
@ParameterizedTest
@CsvSource({ "2, even",
"3, odd"})
void checkCsvSource(int number, String expected) {
assertEquals(StringUtils.equals(expected, "even") ? 0 : 1, number % 2);
}
}

View File

@@ -0,0 +1,27 @@
package source.csv.file;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvFileSource;
public class CsvFileSourceTest {
@ParameterizedTest
@CsvFileSource(files = "src/test/resources/csv-file-source.csv", numLinesToSkip = 1)
void checkCsvFileSource(int number, String expected) {
assertEquals(StringUtils.equals(expected, "even") ? 0 : 1, number % 2);
}
// ---------------------------------------------------------------------------
@ParameterizedTest
@CsvFileSource(files = "src/test/resources/csv-file-source_attributes.csv",
delimiterString = "|",
lineSeparator = "||",
numLinesToSkip = 1)
void checkCsvFileSourceAttributes(int number, String expected) {
assertEquals(StringUtils.equals(expected, "even") ? 0 : 1, number % 2);
}
}

View File

@@ -0,0 +1,25 @@
package source.enumeration;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.time.temporal.ChronoUnit;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
public class EnumSourceTest {
@ParameterizedTest
@EnumSource(ChronoUnit.class)
void checkEnumSourceValue(ChronoUnit unit) {
assertNotNull(unit);
}
// ---------------------------------------------------------------------------
@ParameterizedTest
@EnumSource(names = { "DAYS", "HOURS" })
void checkEnumSourceNames(ChronoUnit unit) {
assertNotNull(unit);
}
}

View File

@@ -0,0 +1,11 @@
package source.method;
import java.util.stream.Stream;
public class ExternalMethodSource {
static Stream<String> checkExternalMethodSourceArgs() {
return Stream.of("a1", "b2");
}
}

View File

@@ -0,0 +1,17 @@
package source.method;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class ExternalMethodSourceTest {
// Note: The test will try to load the external method
@ParameterizedTest
@MethodSource("source.method.ExternalMethodSource#checkExternalMethodSourceArgs")
void checkExternalMethodSource(String word) {
assertTrue(StringUtils.isAlphanumeric(word), "Supplied word is not alpha-numeric");
}
}

View File

@@ -0,0 +1,52 @@
package source.method;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class MethodSourceTest {
// Note: The test will try to load the supplied method
@ParameterizedTest
@MethodSource("checkExplicitMethodSourceArgs")
void checkExplicitMethodSource(String word) {
assertTrue(StringUtils.isAlphanumeric(word), "Supplied word is not alpha-numeric");
}
static Stream<String> checkExplicitMethodSourceArgs() {
return Stream.of("a1", "b2");
}
// ---------------------------------------------------------------------------
// Note: The test will search for the source method that matches the test-case
// method name
@ParameterizedTest
@MethodSource
void checkImplicitMethodSource(String word) {
assertTrue(StringUtils.isAlphanumeric(word), "Supplied word is not alpha-numeric");
}
static Stream<String> checkImplicitMethodSource() {
return Stream.of("a1", "b2");
}
// ---------------------------------------------------------------------------
// Note: The test will automatically map arguments based on the index
@ParameterizedTest
@MethodSource
void checkMultiArgumentsMethodSource(int number, String expected) {
assertEquals(StringUtils.equals(expected, "even") ? 0 : 1, number % 2);
}
static Stream<Arguments> checkMultiArgumentsMethodSource() {
return Stream.of(Arguments.of(2, "even"), Arguments.of(3, "odd"));
}
}

View File

@@ -0,0 +1,44 @@
package source.null_empty;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EmptySource;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
public class NullEmptySourceTest {
@ParameterizedTest
@NullSource
void checkNull(String value) {
assertEquals(null, value);
}
// ---------------------------------------------------------------------------
@ParameterizedTest
@EmptySource
void checkEmpty(String value) {
assertEquals("", value);
}
// ---------------------------------------------------------------------------
@ParameterizedTest
@NullAndEmptySource
void checkNullAndEmpty(String value) {
assertTrue(value == null || value.isEmpty());
}
// ---------------------------------------------------------------------------
@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = { " ", " " })
void checkNullEmptyAndBlank(String value) {
assertTrue(value == null || value.isBlank());
}
}

View File

@@ -0,0 +1,25 @@
package source.value;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
public class ValueSourceTest {
@ParameterizedTest
@ValueSource(ints = { 2, 4 })
void checkEvenNumber(int number) {
assertEquals(0, number % 2, "Supplied number is not an even number");
}
// ---------------------------------------------------------------------------
@ParameterizedTest
@ValueSource(strings = { "a1", "b2" })
void checkAlphanumeric(String word) {
assertTrue(StringUtils.isAlphanumeric(word), "Supplied word is not alpha-numeric");
}
}

View File

@@ -0,0 +1,3 @@
NUMBER, ODD_EVEN
2, even
3, odd
1 NUMBER ODD_EVEN
2 2 even
3 3 odd

View File

@@ -0,0 +1,3 @@
|| NUMBER | ODD_EVEN ||
|| 2 | even ||
|| 3 | odd ||
1 NUMBER ODD_EVEN
2 2 even
3 3 odd

View File

@@ -0,0 +1,2 @@
# Project exclude paths
/target/

View File

@@ -0,0 +1,117 @@
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

View File

@@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

View File

@@ -0,0 +1,39 @@
# A simple Spring Boot Audit application
This application manages auditing of the Library application
## Details
* This application uses the in memory HSQLDB to call the Library application maintain audit logs of the calls made.
* It uses Spring Boot to create REST endpoints
* It uses Retrofit to make calls to the Library application
* It uses Maven and Java11 to build and run.
## How to run
* Clone this project
* Use maven command: `mvn clean verify spring-boot:run`
* The application should run at `http://localhost:8081`
* Use POSTMAN to make REST calls
## Sample request JSON body
# POST Sample
````json
{
"bookName": "The Da Vinci Code",
"publisher": "Corgie Adult",
"publicationYear": "2009",
"isCopyrighted": true,
"authors": [{
"name": "Dan Brown",
"dob" : "22/06/1964"
}]
}
````
# PUT Sample
````json
{
"bookName": "The Da Vinci Code",
"publisher": "Corgie Adult - 01",
"publicationYear": "2010"
}
````

View File

@@ -0,0 +1,7 @@
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
"-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
"https://checkstyle.org/dtds/suppressions_1_2.dtd">
<suppressions>
<suppress files="[/\\]target[/\\]generated-sources[/\\]" checks=".*" />
</suppressions>

View File

@@ -0,0 +1,246 @@
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="Checker">
<property name="charset" value="UTF-8"/>
<property name="severity" value="error"/>
<property name="fileExtensions" value="java, properties, xml"/>
<module name="BeforeExecutionExclusionFileFilter">
<property name="fileNamePattern" value="module\-info\.java$"/>
</module>
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
</module>
<module name="LineLength">
<property name="max" value="120"/>
<property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://"/>
</module>
<module name="TreeWalker">
<module name="OuterTypeFilename"/>
<module name="IllegalTokenText">
<property name="tokens" value="STRING_LITERAL, CHAR_LITERAL"/>
<property name="format"
value="\\u00(09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/>
<property name="message"
value="Consider using special escape sequence instead of octal value or Unicode escaped value."/>
</module>
<module name="AvoidEscapedUnicodeCharacters">
<property name="allowEscapesForControlCharacters" value="true"/>
<property name="allowByTailComment" value="true"/>
<property name="allowNonPrintableEscapes" value="true"/>
</module>
<module name="OneTopLevelClass"/>
<module name="NoLineWrap"/>
<module name="EmptyBlock">
<property name="option" value="TEXT"/>
<property name="tokens"
value="LITERAL_TRY, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/>
</module>
<module name="LeftCurly"/>
<module name="RightCurly">
<property name="id" value="RightCurlySame"/>
<property name="tokens"
value="LITERAL_TRY, LITERAL_CATCH, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE,
LITERAL_DO"/>
</module>
<module name="RightCurly">
<property name="id" value="RightCurlyAlone"/>
<property name="option" value="alone"/>
<property name="tokens"
value="CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, STATIC_INIT,
INSTANCE_INIT"/>
</module>
<module name="WhitespaceAround">
<property name="allowEmptyConstructors" value="true"/>
<property name="allowEmptyLambdas" value="true"/>
<property name="allowEmptyMethods" value="true"/>
<property name="allowEmptyTypes" value="true"/>
<property name="allowEmptyLoops" value="true"/>
<message key="ws.notFollowed"
value="WhitespaceAround: ''{0}'' is not followed by whitespace. Empty blocks may only be represented as '{}' when not part of a multi-block statement (4.1.3)"/>
<message key="ws.notPreceded"
value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/>
</module>
<module name="OneStatementPerLine"/>
<module name="MultipleVariableDeclarations"/>
<module name="ArrayTypeStyle"/>
<module name="MissingSwitchDefault"/>
<module name="FallThrough"/>
<module name="UpperEll"/>
<module name="ModifierOrder"/>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapDot"/>
<property name="tokens" value="DOT"/>
<property name="option" value="nl"/>
</module>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapComma"/>
<property name="tokens" value="COMMA"/>
<property name="option" value="EOL"/>
</module>
<module name="SeparatorWrap">
<!-- ELLIPSIS is EOL until https://github.com/google/styleguide/issues/258 -->
<property name="id" value="SeparatorWrapEllipsis"/>
<property name="tokens" value="ELLIPSIS"/>
<property name="option" value="EOL"/>
</module>
<module name="SeparatorWrap">
<!-- ARRAY_DECLARATOR is EOL until https://github.com/google/styleguide/issues/259 -->
<property name="id" value="SeparatorWrapArrayDeclarator"/>
<property name="tokens" value="ARRAY_DECLARATOR"/>
<property name="option" value="EOL"/>
</module>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapMethodRef"/>
<property name="tokens" value="METHOD_REF"/>
<property name="option" value="nl"/>
</module>
<module name="PackageName">
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>
<message key="name.invalidPattern"
value="Package name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="TypeName">
<message key="name.invalidPattern"
value="Type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MemberName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<message key="name.invalidPattern"
value="Member name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ParameterName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ParameterNumber"/>
<module name="LambdaParameterName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Lambda parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="CatchParameterName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Catch parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="LocalVariableName">
<property name="tokens" value="VARIABLE_DEF"/>
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Local variable name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ClassTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Class type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MethodTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Method type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="InterfaceTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Interface type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="NoFinalizer"/>
<module name="GenericWhitespace">
<message key="ws.followed"
value="GenericWhitespace ''{0}'' is followed by whitespace."/>
<message key="ws.preceded"
value="GenericWhitespace ''{0}'' is preceded with whitespace."/>
<message key="ws.illegalFollow"
value="GenericWhitespace ''{0}'' should followed by whitespace."/>
<message key="ws.notPreceded"
value="GenericWhitespace ''{0}'' is not preceded with whitespace."/>
</module>
<module name="Indentation">
<property name="basicOffset" value="4"/>
<property name="braceAdjustment" value="0"/>
<property name="caseIndent" value="4"/>
<property name="throwsIndent" value="8"/>
<property name="lineWrappingIndentation" value="8"/>
<property name="arrayInitIndent" value="4"/>
</module>
<module name="AbbreviationAsWordInName">
<property name="ignoreFinal" value="false"/>
<property name="allowedAbbreviationLength" value="1"/>
</module>
<module name="OverloadMethodsDeclarationOrder"/>
<module name="VariableDeclarationUsageDistance"/>
<module name="CustomImportOrder">
<property name="customImportOrderRules"
value="THIRD_PARTY_PACKAGE###SPECIAL_IMPORTS###STANDARD_JAVA_PACKAGE###STATIC"/>
<property name="specialImportsRegExp" value="^javax\."/>
<property name="standardPackageRegExp" value="^java\."/>
<property name="sortImportsInGroupAlphabetically" value="true"/>
<property name="separateLineBetweenGroups" value="false"/>
</module>
<module name="MethodParamPad"/>
<module name="NoWhitespaceBefore">
<property name="tokens"
value="COMMA, SEMI, POST_INC, POST_DEC, DOT, ELLIPSIS, METHOD_REF"/>
<property name="allowLineBreaks" value="true"/>
</module>
<module name="ParenPad"/>
<module name="OperatorWrap">
<property name="option" value="eol"/>
<property name="tokens"
value="BAND, BOR, BSR, BXOR, DIV, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR,
LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR, METHOD_REF "/>
</module>
<module name="AnnotationLocation">
<property name="id" value="AnnotationLocationMostCases"/>
<property name="tokens"
value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF"/>
</module>
<module name="AnnotationLocation">
<property name="id" value="AnnotationLocationVariables"/>
<property name="tokens" value="VARIABLE_DEF"/>
<property name="allowSamelineMultipleAnnotations" value="true"/>
</module>
<module name="NonEmptyAtclauseDescription"/>
<module name="JavadocTagContinuationIndentation"/>
<module name="SummaryJavadoc">
<property name="forbiddenSummaryFragments"
value="^@return the *|^This method returns |^A [{]@code [a-zA-Z0-9]+[}]( is a )"/>
</module>
<module name="JavadocParagraph"/>
<module name="AtclauseOrder">
<property name="tagOrder" value="@param, @return, @throws, @deprecated"/>
<property name="target"
value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/>
</module>
<module name="JavadocMethod">
<property name="scope" value="public"/>
<property name="allowedAnnotations" value="Override, Test"/>
</module>
<module name="MethodName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9_]*$"/>
<message key="name.invalidPattern"
value="Method name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="SingleLineJavadoc">
<property name="ignoreInlineTags" value="false"/>
</module>
<module name="EmptyCatchBlock">
<property name="exceptionVariableName" value="expected"/>
</module>
<module name="CommentsIndentation"/>
<module name="AvoidNestedBlocks"/>
<module name="AbstractClassName"/>
<module name="CyclomaticComplexity"/>
<module name="EmptyStatement"/>
</module>
</module>

View File

@@ -0,0 +1,310 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

View File

@@ -0,0 +1,182 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

View File

@@ -0,0 +1,185 @@
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.reflectoring</groupId>
<artifactId>audit-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>audit-app</name>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath />
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-mapstruct-binding</artifactId>
<version>0.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.4.2.Final</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.4.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-jackson</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>logging-interceptor</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit-mock</artifactId>
<version>2.5.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-commons</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<!-- Code style checks. Will fail the build if the code is not compliant. -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.1.1</version>
<configuration>
<configLocation>checkstyle.xml</configLocation>
<suppressionsLocation>checkstyle-suppressions.xml</suppressionsLocation>
<encoding>UTF-8</encoding>
<outputEncoding>UTF-8</outputEncoding>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<linkXRef>false</linkXRef>
</configuration>
<executions>
<execution>
<id>verify</id>
<phase>verify</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<!-- Finds bugs in the code. Will fail the build if any are found. -->
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-maven-plugin</artifactId>
<version>4.5.3.0</version>
<dependencies>
<dependency>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs</artifactId>
<version>4.6.0</version>
</dependency>
</dependencies>
<configuration>
<encoding>UTF-8</encoding>
<outputEncoding>UTF-8</outputEncoding>
<includeTests>false</includeTests>
<excludeFilterFile>spotbugs-exclude.xml</excludeFilterFile>
</configuration>
<executions>
<execution>
<id>verify</id>
<phase>verify</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>11</source>
<target>11</target>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.4.2.Final</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,101 @@
<?xml version="1.0" encoding="UTF-8"?>
<FindBugsFilter>
<Match>
<!-- This is required for Immutables (or any annotation processor generated classes causing havoc) -->
<Package name="~.*\.model\.?.*"/>
<Bug pattern="NP_METHOD_PARAMETER_TIGHTENS_ANNOTATION"/>
</Match>
<Match>
<!-- Sample model class. Need not be used -->
<Package name="~.*\.model\.?.*"/>
<Bug pattern="UUF_UNUSED_FIELD"/>
</Match>
<Match>
<!-- Sample model class. Need not be used -->
<Package name="~.*\.model\.?.*"/>
<Bug pattern="EI_EXPOSE_REP"/>
</Match>
<Match>
<!-- Sample model class. Need not be used -->
<Package name="~.*\.config\.?.*"/>
<Bug pattern="EI_EXPOSE_REP"/>
</Match>
<Match>
<!-- Sample model class. Need not be used -->
<Package name="~.*\.config\.?.*"/>
<Bug pattern="EI_EXPOSE_REP2"/>
</Match>
<Match>
<!-- Sample model class. Need not be used -->
<Package name="~.*\.service\.?.*"/>
<Bug pattern="EI_EXPOSE_REP"/>
</Match>
<Match>
<!-- Sample model class. Need not be used -->
<Package name="~.*\.service\.?.*"/>
<Bug pattern="EI_EXPOSE_REP2"/>
</Match>
<Match>
<!-- Sample model class. Need not be used -->
<Package name="~.*\.model\.?.*"/>
<Bug pattern="EI_EXPOSE_REP2"/>
</Match>
<Match>
<!-- Sample model class. Need not be used -->
<Package name="~.*\.exception\.?.*"/>
<Bug pattern="EI_EXPOSE_REP2"/>
</Match>
<Match>
<!-- Sample model class. Need not be used -->
<Package name="~.*\.exception\.?.*"/>
<Bug pattern="EI_EXPOSE_REP"/>
</Match>
<Match>
<!-- Sample model class. Need not be used -->
<Package name="~.*\.web\.?.*"/>
<Bug pattern="EI_EXPOSE_REP"/>
</Match>
<Match>
<!-- Sample model class. Need not be used -->
<Package name="~.*\.web\.?.*"/>
<Bug pattern="EI_EXPOSE_REP2"/>
</Match>
<Match>
<!-- Sample model class. Need not be read -->
<Package name="~.*\.model\.?.*"/>
<Bug pattern="URF_UNREAD_FIELD"/>
</Match>
<Match>
<Package name="~.*\.model\.?.*"/>
<Bug pattern="RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT"/>
</Match>
</FindBugsFilter>

View File

@@ -0,0 +1,19 @@
package com.reflectoring.library;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
private static Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@@ -0,0 +1,30 @@
package com.reflectoring.library.client;
import com.reflectoring.library.model.LibResponse;
import com.reflectoring.library.model.mapstruct.BookDto;
import retrofit2.Call;
import retrofit2.http.*;
import java.util.List;
public interface LibraryClient {
/*@Headers({
"Accept: application/json",
"Cache-Control: max-age=640000"
})*/
@GET("/library/managed/books")
Call<List<BookDto>> getAllBooks(@Query("type") String type);
@GET("/library/managed/books/{requestId}")
Call<BookDto> getAllBooksWithHeaders(@Header("requestId") String requestId);
@POST("/library/managed/books")
Call<LibResponse> createNewBook(@Body BookDto book);
@PUT("/library/managed/books/{id}")
Call<LibResponse> updateBook(@Path("id") Long id, @Body BookDto book);
@DELETE("/library/managed/books/{id}")
Call<LibResponse> deleteBook(@Path("id") Long id);
}

View File

@@ -0,0 +1,21 @@
package com.reflectoring.library.config;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "library")
@Getter
@Setter
public class ClientConfigProperties {
private String endpoint;
private String username;
private String password;
private Integer connectionTimeout;
private Integer readWriteTimeout;
}

View File

@@ -0,0 +1,45 @@
package com.reflectoring.library.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.reflectoring.library.client.LibraryClient;
import com.reflectoring.library.interceptor.BasicAuthInterceptor;
import com.reflectoring.library.interceptor.CacheInterceptor;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
import java.io.File;
import java.util.concurrent.TimeUnit;
@Configuration
@EnableConfigurationProperties(ClientConfigProperties.class)
public class RestClientConfiguration {
@Bean
public LibraryClient libraryClient(ClientConfigProperties props) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
Cache cache = new Cache(new File("cache"), 10 * 1024 * 1024);
OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder()
.addInterceptor(new BasicAuthInterceptor(props.getUsername(), props.getPassword()))
.cache(cache)
.addNetworkInterceptor(new CacheInterceptor())
.addInterceptor(interceptor)
.connectTimeout(props.getConnectionTimeout(), TimeUnit.SECONDS)
.readTimeout(props.getReadWriteTimeout(), TimeUnit.SECONDS);
return new Retrofit.Builder().client(httpClientBuilder.build())
.baseUrl(props.getEndpoint())
.addConverterFactory(JacksonConverterFactory.create(new ObjectMapper()))
.build().create(LibraryClient.class);
}
}

View File

@@ -0,0 +1,26 @@
package com.reflectoring.library.interceptor;
import okhttp3.Credentials;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class BasicAuthInterceptor implements Interceptor {
private final String credentials;
public BasicAuthInterceptor(String user, String password) {
this.credentials = Credentials.basic(user, password);
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request authenticatedRequest = request.newBuilder()
.header("Authorization", credentials).build();
return chain.proceed(authenticatedRequest);
}
}

View File

@@ -0,0 +1,25 @@
package com.reflectoring.library.interceptor;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Response;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class CacheInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
CacheControl cacheControl = new CacheControl.Builder()
.maxAge(1, TimeUnit.MINUTES) // 1 minutes cache
.build();
return response.newBuilder()
.removeHeader("Pragma")
.removeHeader("Cache-Control")
.header("Cache-Control", cacheControl.toString())
.build();
}
}

View File

@@ -0,0 +1,99 @@
package com.reflectoring.library.mapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.reflectoring.library.model.LibResponse;
import com.reflectoring.library.model.mapstruct.AuditDto;
import com.reflectoring.library.model.mapstruct.BookDto;
import com.reflectoring.library.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
@Component
public class AuditMapper {
private static final Logger LOG = LoggerFactory.getLogger(AuditMapper.class);
public AuditDto populateAuditLogForGet(List<BookDto> books) {
AuditDto log = null;
log = new AuditDto();
log.setId(UUID.randomUUID().toString());
log.setMethodType(HttpMethod.GET);
log.setRequest(null);
log.setResponse(String.valueOf(books.size()));
log.setSuccess(Constants.SUCCESS);
log.setTimestamp(LocalDateTime.now());
return log;
}
public AuditDto populateAuditLogForGetBook(BookDto book) {
AuditDto log = null;
log = new AuditDto();
log.setId(UUID.randomUUID().toString());
log.setMethodType(HttpMethod.GET);
log.setRequest(null);
log.setResponse(book.toString());
log.setSuccess(Constants.SUCCESS);
log.setTimestamp(LocalDateTime.now());
return log;
}
public AuditDto populateAuditLogForPostAndPut(BookDto book, LibResponse response, HttpMethod method) {
AuditDto log = null;
try {
log = new AuditDto();
log.setId(UUID.randomUUID().toString());
log.setMethodType(method);
log.setRequest(new ObjectMapper().writeValueAsString(book));
log.setResponse(new ObjectMapper().writeValueAsString(response));
log.setSuccess(Constants.SUCCESS);
log.setTimestamp(LocalDateTime.now());
} catch (JsonProcessingException ex) {
LOG.error("Error processing Object to json", ex);
}
return log;
}
public AuditDto populateAuditLogForDelete(Long id, LibResponse libResponse) {
AuditDto log = null;
try {
log = new AuditDto();
log.setId(UUID.randomUUID().toString());
log.setMethodType(HttpMethod.DELETE);
log.setRequest(String.valueOf(id));
log.setResponse(new ObjectMapper().writeValueAsString(libResponse));
log.setSuccess(Constants.SUCCESS);
log.setTimestamp(LocalDateTime.now());
} catch (JsonProcessingException ex) {
LOG.error("Error processing Object to json", ex);
}
return log;
}
public AuditDto populateAuditLogForException(String request, HttpMethod type, String errorResp) {
AuditDto log = null;
try {
log = new AuditDto();
log.setId(UUID.randomUUID().toString());
log.setMethodType(type);
log.setRequest(request);
log.setResponse(new ObjectMapper().writeValueAsString(errorResp));
log.setSuccess(Constants.ERROR);
log.setTimestamp(LocalDateTime.now());
} catch (JsonProcessingException ex) {
LOG.error("Error processing Object to json", ex);
}
return log;
}
}

View File

@@ -0,0 +1,29 @@
package com.reflectoring.library.mapper;
import com.reflectoring.library.model.mapstruct.AuditDto;
import com.reflectoring.library.model.mapstruct.AuthorDto;
import com.reflectoring.library.model.mapstruct.BookDto;
import com.reflectoring.library.model.persistence.AuditLog;
import com.reflectoring.library.model.persistence.Author;
import com.reflectoring.library.model.persistence.Book;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import java.util.List;
@Mapper(componentModel = "spring")
public interface LibraryMapper {
BookDto bookToBookDto(Book book);
List<BookDto> bookToBookDto(List<Book> book);
AuthorDto authorToAuthorDto(Author author);
Book bookDtoToBook(BookDto bookDto);
Author authorDtoToAuthor(AuthorDto authorDto);
AuditLog auditDtoToAuditLog(AuditDto auditDto);
AuditDto auditLogToAuditDto(AuditLog auditLog);
}

View File

@@ -0,0 +1,16 @@
package com.reflectoring.library.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class LibResponse {
private String responseCode;
private String responseMsg;
}

View File

@@ -0,0 +1,31 @@
package com.reflectoring.library.model;
public enum Status {
SUCCESS(200) {
@Override
public String toString() {
return "Success";
}
},
ERROR(500) {
@Override
public String toString() {
return "Error";
}
};
private int code;
Status(int code) {
this.code = code;
}
public static int fetchCode(String statusCode) {
for (Status s : Status.values()) {
if (s.name().equals(statusCode.toUpperCase())) {
return s.code;
}
}
return 0;
}
}

View File

@@ -0,0 +1,39 @@
package com.reflectoring.library.model.mapstruct;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.springframework.http.HttpMethod;
import java.time.LocalDateTime;
@Getter
@Setter
@NoArgsConstructor
@ToString
public class AuditDto {
@JsonProperty("id")
private String id;
@JsonProperty("request")
private String request;
@JsonProperty("response")
private String response;
@JsonProperty("methodType")
private HttpMethod methodType;
@JsonProperty("success")
private String success;
@JsonProperty("timestamp")
private LocalDateTime timestamp;
}

View File

@@ -0,0 +1,30 @@
package com.reflectoring.library.model.mapstruct;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
public class AuthorDto {
@JsonProperty("id")
private long id;
@JsonProperty("name")
private String name;
@JsonProperty("dob")
private String dob;
@Override
public String toString() {
return "AuthorDto{" +
"id=" + id +
", name='" + name + '\'' +
", dob='" + dob + '\'' +
'}';
}
}

View File

@@ -0,0 +1,43 @@
package com.reflectoring.library.model.mapstruct;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Set;
@Getter
@Setter
@NoArgsConstructor
public class BookDto {
@JsonProperty("bookId")
private long id;
@JsonProperty("bookName")
private String name;
@JsonProperty("publisher")
private String publisher;
@JsonProperty("publicationYear")
private String publicationYear;
@JsonProperty("isCopyrighted")
private boolean copyrightIssued;
@JsonProperty("authors")
private Set<AuthorDto> authors;
@Override
public String toString() {
return "BookDto{" +
"id=" + id +
", name='" + name + '\'' +
", publisher='" + publisher + '\'' +
", publicationYear='" + publicationYear + '\'' +
", copyrightIssued=" + copyrightIssued +
", authors=" + authors +
'}';
}
}

View File

@@ -0,0 +1,34 @@
package com.reflectoring.library.model.persistence;
import lombok.Getter;
import lombok.Setter;
import org.springframework.http.HttpMethod;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "AUDIT_LOG")
@Getter
@Setter
public class AuditLog {
@Id
private String id;
private String request;
private String response;
@Enumerated(EnumType.ORDINAL)
private HttpMethod methodType;
private String success;
@Column(name = "CURR_TIMESTAMP")
private LocalDateTime timestamp;
public AuditLog() {
}
}

View File

@@ -0,0 +1,69 @@
package com.reflectoring.library.model.persistence;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Builder;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
@Entity
public class Author implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String dob;
@ManyToMany(mappedBy = "authors")
private Set<Book> books;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Book> getBooks() {
return books;
}
public void setBooks(Set<Book> books) {
this.books = books;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
@Override
public String toString() {
return "Author{" +
"id=" + id +
", name='" + name + '\'' +
", dob='" + dob + '\'' +
'}';
}
}

View File

@@ -0,0 +1,88 @@
package com.reflectoring.library.model.persistence;
import lombok.Builder;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Set;
@Entity
@Table(name = "BOOK")
public class Book implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String publisher;
private String publicationYear;
private boolean copyrightIssued;
@ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
@JoinTable(name = "author_book",
joinColumns = @JoinColumn(name = "book_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "author_id", referencedColumnName = "id"))
private Set<Author> authors;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Author> getAuthors() {
return authors;
}
public void setAuthors(Set<Author> authors) {
this.authors = authors;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getPublicationYear() {
return publicationYear;
}
public void setPublicationYear(String publicationYear) {
this.publicationYear = publicationYear;
}
public boolean isCopyrightIssued() {
return copyrightIssued;
}
public void setCopyrightIssued(boolean copyrightIssued) {
this.copyrightIssued = copyrightIssued;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", publisher='" + publisher + '\'' +
", publicationYear='" + publicationYear + '\'' +
", copyrightIssued=" + copyrightIssued +
'}';
}
}

View File

@@ -0,0 +1,9 @@
package com.reflectoring.library.repository;
import com.reflectoring.library.model.persistence.AuditLog;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface AuditRepository extends JpaRepository<AuditLog, String> {
}

View File

@@ -0,0 +1,9 @@
package com.reflectoring.library.repository;
import com.reflectoring.library.model.persistence.Author;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface AuthorRepository extends JpaRepository<Author, Long> {
}

View File

@@ -0,0 +1,9 @@
package com.reflectoring.library.repository;
import com.reflectoring.library.model.persistence.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface BookRepository extends JpaRepository<Book, Long> {
}

View File

@@ -0,0 +1,218 @@
package com.reflectoring.library.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.reflectoring.library.client.LibraryClient;
import com.reflectoring.library.mapper.AuditMapper;
import com.reflectoring.library.mapper.LibraryMapper;
import com.reflectoring.library.model.LibResponse;
import com.reflectoring.library.model.Status;
import com.reflectoring.library.model.mapstruct.AuditDto;
import com.reflectoring.library.model.mapstruct.BookDto;
import com.reflectoring.library.model.persistence.AuditLog;
import com.reflectoring.library.model.persistence.Book;
import com.reflectoring.library.repository.AuditRepository;
import com.reflectoring.library.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import java.util.*;
@Service
public class LibraryAuditService {
private static final Logger log = LoggerFactory.getLogger(LibraryAuditService.class);
private final LibraryMapper libraryMapper;
private final AuditMapper auditMapper;
private final AuditRepository auditRepository;
private final LibraryClient libraryClient;
public LibraryAuditService(LibraryMapper libraryMapper,
AuditMapper auditMapper, AuditRepository auditRepository, LibraryClient libraryClient) {
this.libraryMapper = libraryMapper;
this.auditMapper = auditMapper;
this.auditRepository = auditRepository;
this.libraryClient = libraryClient;
}
/*public void getBooksAsync(String bookRequest) {
Call<BookDto> bookDtoCall = libraryClient.getAllBooksWithHeaders(bookRequest);
bookDtoCall.enqueue(new Callback<>() {
@Override
public void onResponse(Call<BookDto> call, Response<BookDto> response) {
if (response.isSuccessful()) {
log.info("Success response : {}", response.body());
} else {
log.info("Error response : {}", response.errorBody());
}
}
@Override
public void onFailure(Call<BookDto> call, Throwable throwable) {
log.info("Network error occured : {}", throwable.getLocalizedMessage());
}
});
}*/
public BookDto getBooks(String bookRequest) {
Response<BookDto> allBooksResponse = null;
BookDto books = null;
try {
AuditDto audit = null;
allBooksResponse = libraryClient.getAllBooksWithHeaders(bookRequest).execute();
if (allBooksResponse.isSuccessful()) {
books = allBooksResponse.body();
log.info("Get All Books : {}", books);
audit = auditMapper.populateAuditLogForGetBook(books);
} else {
log.error("Error calling library client: {}", allBooksResponse.errorBody());
if (Objects.nonNull(allBooksResponse.errorBody())) {
audit = auditMapper.populateAuditLogForException(
null, HttpMethod.GET, allBooksResponse.errorBody().string());
}
}
if (Objects.nonNull(audit)) {
AuditLog savedObj = auditRepository.save(libraryMapper.auditDtoToAuditLog(audit));
log.info("Saved into audit successfully: {}", savedObj);
}
return books;
} catch (Exception ex) {
log.error("Error handling retrofit call for getAllBooks", ex);
return books;
}
}
public List<BookDto> getAllBooks() {
List<BookDto> books = Collections.emptyList();
try {
AuditDto audit = null;
Call<List<BookDto>> callBookResponse = libraryClient.getAllBooks("all");
Response<List<BookDto>> allBooksResponse = callBookResponse.execute();
if (allBooksResponse.isSuccessful()) {
books = allBooksResponse.body();
log.info("Get All Books : {}", books);
audit = auditMapper.populateAuditLogForGet(books);
} else {
log.error("Error calling library client: {}", allBooksResponse.errorBody());
if (Objects.nonNull(allBooksResponse.errorBody())) {
audit = auditMapper.populateAuditLogForException(
null, HttpMethod.GET, allBooksResponse.errorBody().string());
}
}
if (Objects.nonNull(audit)) {
AuditLog savedObj = auditRepository.save(libraryMapper.auditDtoToAuditLog(audit));
log.info("Saved into audit successfully: {}", savedObj);
}
return books;
} catch (Exception ex) {
log.error("Error handling retrofit call for getAllBooks", ex);
return books;
}
}
public LibResponse createBook(BookDto bookDto) {
log.info("Book DTO from POST request : {}", bookDto);
LibResponse resp = null;
AuditDto audit = null;
try {
Call<LibResponse> callLibResponse = libraryClient.createNewBook(bookDto);
Response<LibResponse> libResponse = callLibResponse.execute();
if (libResponse.isSuccessful()) {
resp = libResponse.body();
audit = auditMapper.populateAuditLogForPostAndPut(bookDto, resp, HttpMethod.POST);
} else {
log.error("Error calling library client: {}", libResponse.errorBody());
if (Objects.nonNull(libResponse.errorBody())) {
audit = auditMapper.populateAuditLogForException(
new ObjectMapper().writeValueAsString(bookDto),
HttpMethod.POST, libResponse.errorBody().string());
}
}
if (Objects.nonNull(audit)) {
AuditLog savedObj = auditRepository.save(libraryMapper.auditDtoToAuditLog(audit));
log.info("Saved into audit successfully: {}", savedObj);
}
return resp;
} catch (Exception ex) {
log.error("Error handling retrofit call for createNewBook", ex);
return new LibResponse(Constants.ERROR, "Failed");
}
}
public LibResponse updateBook(Long id, BookDto bookdto) {
log.info("Book DTO from PUT request : {}", bookdto);
LibResponse resp = null;
AuditDto audit = null;
try {
Call<LibResponse> callLibResponse = libraryClient.updateBook(id, bookdto);
Response<LibResponse> libResponse = callLibResponse.execute();
if (libResponse.isSuccessful()) {
resp = libResponse.body();
audit = auditMapper.populateAuditLogForPostAndPut(bookdto, resp, HttpMethod.PUT);
} else {
log.error("Error calling library client: {}", libResponse.errorBody());
if (Objects.nonNull(libResponse.errorBody())) {
audit = auditMapper.populateAuditLogForException(
new ObjectMapper().writeValueAsString(bookdto),
HttpMethod.POST, libResponse.errorBody().string());
}
}
} catch (Exception ex) {
log.error("Error handling retrofit call for updateBook", ex);
resp = new LibResponse(Constants.ERROR, "Failed");
}
if (Objects.nonNull(audit)) {
AuditLog savedObj = auditRepository.save(libraryMapper.auditDtoToAuditLog(audit));
log.info("Saved into audit successfully: {}", savedObj);
}
return resp;
}
public LibResponse deleteBook(Long id) {
LibResponse resp = null;
AuditDto audit = null;
try {
Call<LibResponse> callLibResponse = libraryClient.deleteBook(id);
Response<LibResponse> libResponse = callLibResponse.execute();
if (libResponse.isSuccessful()) {
resp = libResponse.body();
audit = auditMapper.populateAuditLogForDelete(id, resp);
} else {
log.error("Error calling library client: {}", libResponse.errorBody());
if (Objects.nonNull(libResponse.errorBody())) {
resp = new ObjectMapper().readValue(libResponse.errorBody().string(), LibResponse.class);
audit = auditMapper.populateAuditLogForException(
String.valueOf(id), HttpMethod.POST, libResponse.errorBody().string());
}
}
} catch (Exception ex) {
log.error("Error handling retrofit call for deleteBook", ex);
resp = new LibResponse(Constants.ERROR, "Failed");
}
if (Objects.nonNull(audit)) {
AuditLog savedObj = auditRepository.save(libraryMapper.auditDtoToAuditLog(audit));
log.info("Saved into audit successfully : {}", savedObj);
}
return resp;
}
}

View File

@@ -0,0 +1,8 @@
package com.reflectoring.library.util;
public class Constants {
public static final String SUCCESS = "Success";
public static final String ERROR = "Error";
}

View File

@@ -0,0 +1,22 @@
package com.reflectoring.library.util;
import org.springframework.stereotype.Component;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.sql.Timestamp;
import java.time.LocalDateTime;
@Component
@Converter(autoApply = true)
public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(LocalDateTime localDateTime) {
return localDateTime == null ? null : Timestamp.valueOf(localDateTime);
}
@Override
public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {
return timestamp == null ? null : timestamp.toLocalDateTime();
}
}

View File

@@ -0,0 +1,54 @@
package com.reflectoring.library.web;
import com.reflectoring.library.model.LibResponse;
import com.reflectoring.library.model.Status;
import com.reflectoring.library.model.mapstruct.BookDto;
import com.reflectoring.library.service.LibraryAuditService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("library/managed/books")
public class LibraryAuditController {
private static final Logger log = LoggerFactory.getLogger(LibraryAuditController.class);
private final LibraryAuditService libraryAuditService;
public LibraryAuditController(LibraryAuditService libraryAuditService) {
this.libraryAuditService = libraryAuditService;
}
@GetMapping
public ResponseEntity<List<BookDto>> getBooks() {
return ResponseEntity.ok().body(libraryAuditService.getAllBooks());
}
@GetMapping("/requestId")
public ResponseEntity<BookDto> getBooksWithHeaders(@RequestHeader String bookRequest) {
return ResponseEntity.ok().body(libraryAuditService.getBooks(bookRequest));
}
@PostMapping
public ResponseEntity<LibResponse> createBook(@RequestBody BookDto book) {
return ResponseEntity.ok().body(libraryAuditService.createBook(book));
}
@PutMapping(value = "/{id}", produces = "application/json")
public ResponseEntity<LibResponse> updateBook(@PathVariable Long id, @RequestBody BookDto book) {
return ResponseEntity.ok().body(libraryAuditService.updateBook(id, book));
}
@DeleteMapping(value = "{id}", produces = "application/json")
public ResponseEntity<LibResponse> deleteBook(@PathVariable Long id) {
LibResponse response = libraryAuditService.deleteBook(id);
log.info("Response received : {}", response);
log.info("Status from response : {}", Status.fetchCode(response.getResponseCode()));
return ResponseEntity.status(Status.fetchCode(response.getResponseCode())).body(response);
}
}

View File

@@ -0,0 +1,21 @@
spring:
datasource:
driver-class-name: org.hsqldb.jdbc.JDBCDriver
url: jdbc:hsqldb:mem:auditdb;DB_CLOSE_DELAY=-1
username: sa
password:
jpa:
defer-datasource-initialization: true
hibernate:
ddl-auto: create
server:
port: 8081
library:
endpoint: http://localhost:8090
username: libuser
password: libpass
connectionTimeout: 30
readWriteTimeout: 30

View File

@@ -0,0 +1,3 @@
CREATE SCHEMA IF NOT EXISTS auditdb;
DROP TABLE IF EXISTS AUDIT_LOG;
CREATE TABLE IF NOT EXISTS AUDIT_LOG(ID VARCHAR(30), REQUEST VARCHAR(1000), RESPONSE VARCHAR(1000), METHOD_TYPE VARCHAR(10), SUCCESS VARCHAR(10), CURR_TIMESTAMP TIMESTAMP );

View File

@@ -0,0 +1,150 @@
package com.reflectoring.library.service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.reflectoring.library.client.LibraryClient;
import com.reflectoring.library.mapper.AuditMapper;
import com.reflectoring.library.mapper.LibraryMapper;
import com.reflectoring.library.model.LibResponse;
import com.reflectoring.library.model.Status;
import com.reflectoring.library.model.mapstruct.BookDto;
import com.reflectoring.library.repository.AuditRepository;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.DisplayName;
import org.junit.runner.RunWith;
import org.mockito.Mock;
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.test.context.junit4.SpringRunner;
import retrofit2.Response;
import retrofit2.mock.Calls;
import java.io.IOException;
import java.util.List;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
@SpringBootTest
@RunWith(SpringRunner.class)
public class LibraryAuditServiceTest {
private static final Logger log = LoggerFactory.getLogger(LibraryAuditServiceTest.class);
@Autowired
private LibraryMapper libraryMapper;
@Autowired
private AuditMapper auditMapper;
@Mock
private LibraryClient libraryClient;
@Mock
private AuditRepository auditRepository;
private LibraryAuditService libraryAuditService;
@Before
public void setup() {
libraryAuditService = new LibraryAuditService(libraryMapper, auditMapper, auditRepository, libraryClient);
}
@Test
@DisplayName("Successful getAllBooks call")
public void getAllBooksTest() throws Exception {
String booksResponse = getBooksResponse("/response/getAllBooks.json");
List<BookDto> bookDtoList =
new ObjectMapper().readValue(booksResponse, new TypeReference<>() {
});
when(libraryClient.getAllBooks("all")).thenReturn(Calls.response(bookDtoList));
doReturn(null).when(auditRepository).save(any());
List<BookDto> allBooks = libraryAuditService.getAllBooks();
assertAll(
() -> assertNotNull(allBooks),
() -> assertTrue(allBooks.size()>0)
);
}
@Test
@DisplayName("Successful call to get a specific book")
public void getRequestBookTest() throws Exception {
String booksResponse = getBooksResponse("/response/getOneBook.json");
BookDto bookDto = new ObjectMapper().readValue(booksResponse, BookDto.class);
when(libraryClient.getAllBooksWithHeaders("1")).thenReturn(Calls.response(bookDto));
doReturn(null).when(auditRepository).save(any());
BookDto book = libraryAuditService.getBooks("1");
assertAll(
() -> assertNotNull(book),
() -> assertTrue(book.getId()==1)
);
}
@Test
@DisplayName("Successful call to create a book")
public void postBookRequestTest() throws Exception {
String booksResponse = getBooksResponse("/request/postBook.json");
BookDto bookDto = new ObjectMapper().readValue(booksResponse, BookDto.class);
LibResponse response = new LibResponse("Success", "Book created successfully");
when(libraryClient.createNewBook(bookDto)).thenReturn(Calls.response(response));
doReturn(null).when(auditRepository).save(any());
LibResponse libResponse = libraryAuditService.createBook(bookDto);
assertAll(
() -> assertNotNull(libResponse),
() -> assertTrue(libResponse.getResponseCode().equals("Success"))
);
}
@Test
@DisplayName("Successful call to update a book")
public void putBookRequestTest() throws Exception {
String booksResponse = getBooksResponse("/request/putBook.json");
BookDto bookDto = new ObjectMapper().readValue(booksResponse, BookDto.class);
LibResponse response = new LibResponse("Success", "Book updated successfully");
when(libraryClient.updateBook(Long.valueOf("1"), bookDto)).thenReturn(Calls.response(response));
doReturn(null).when(auditRepository).save(any());
LibResponse libResponse = libraryAuditService.updateBook(Long.valueOf("1"), bookDto);
assertAll(
() -> assertNotNull(libResponse),
() -> assertTrue(libResponse.getResponseCode().equals("Success"))
);
}
@Test
@DisplayName("Cannot delete a book")
public void deleteBookRequestTest() throws Exception {
LibResponse response = new LibResponse(Status.ERROR.toString(), "Could not delete book for id : 1000");
ResponseBody respBody = ResponseBody.create(MediaType.parse("application/json"),
new ObjectMapper().writeValueAsString(response));
Response<LibResponse> respLib = Response.error(500, respBody);
when(libraryClient.deleteBook(Long.valueOf("1000"))).thenReturn(Calls.response(respLib));
doReturn(null).when(auditRepository).save(any());
LibResponse libResponse = libraryAuditService.deleteBook(Long.valueOf("1000"));
assertAll(
() -> assertNotNull(libResponse),
() -> assertTrue(libResponse.getResponseCode().equals("Error"))
);
}
private String getBooksResponse(String path) throws IOException {
return IOUtils.toString(this.getClass().getResourceAsStream(path));
}
}

View File

@@ -0,0 +1,10 @@
{
"bookName": "The Monk who sold his Ferrari",
"publisher": "c",
"publicationYear": "2009",
"isCopyrighted": true,
"authors": [{
"name": "Robin Sharma",
"dob" : "16/06/1964"
}]
}

View File

@@ -0,0 +1,5 @@
{
"bookName": "The Monk who sold his Ferrari - 01",
"publisher": "The Monk who sold his Ferrari",
"publicationYear": "2010"
}

View File

@@ -0,0 +1,15 @@
[
{
"bookId": 1,
"bookName": "The Da Vinci Code",
"publisher": "Corgie Adult",
"publicationYear": "2009",
"isCopyrighted": true,
"authors": [{
"id": 2,
"name": "Dan Brown",
"dob" : "22/06/1964"
}]
}
]

View File

@@ -0,0 +1,14 @@
{
"bookId": 1,
"bookName": "The Da Vinci Code",
"publisher": "Corgie Adult",
"publicationYear": "2009",
"isCopyrighted": true,
"authors": [{
"id": 2,
"name": "Dan Brown",
"dob" : "22/06/1964"
}]
}

View File

@@ -0,0 +1,2 @@
# Project exclude paths
/target/

View File

@@ -0,0 +1,117 @@
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

View File

@@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

View File

@@ -0,0 +1,39 @@
# A simple Spring Boot & Springfox library application
This application manages a database of books and authors
## Details
* This application uses the default demo HSQLDB schema to maintain book and authors.
* It uses Spring Boot to create REST endpoints
* For the endpoint documentation it uses Swagger2
* It uses Maven and Java11 to build and run.
## How to run
* Clone this project
* Use maven command: `mvn clean verify spring-boot:run`
* The application should run at `http://localhost:8090`
* The swagger documentation will be available at `http://localhost:8090/swagger-ui.html#/`
* Uses Basic auth for authentication.
## Sample request JSON body
# POST Sample
````json
{
"bookName": "The Da Vinci Code",
"publisher": "Corgie Adult",
"publicationYear": "2009",
"isCopyrighted": true,
"authors": [{
"name": "Dan Brown",
"dob" : "22/06/1964"
}]
}
````
# PUT Sample
````json
{
"bookName": "The Da Vinci Code",
"publisher": "Corgie Adult - 01",
"publicationYear": "2010"
}
````

View File

@@ -0,0 +1,7 @@
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
"-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
"https://checkstyle.org/dtds/suppressions_1_2.dtd">
<suppressions>
<suppress files="[/\\]target[/\\]generated-sources[/\\]" checks=".*" />
</suppressions>

View File

@@ -0,0 +1,246 @@
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="Checker">
<property name="charset" value="UTF-8"/>
<property name="severity" value="error"/>
<property name="fileExtensions" value="java, properties, xml"/>
<module name="BeforeExecutionExclusionFileFilter">
<property name="fileNamePattern" value="module\-info\.java$"/>
</module>
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
</module>
<module name="LineLength">
<property name="max" value="120"/>
<property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://"/>
</module>
<module name="TreeWalker">
<module name="OuterTypeFilename"/>
<module name="IllegalTokenText">
<property name="tokens" value="STRING_LITERAL, CHAR_LITERAL"/>
<property name="format"
value="\\u00(09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/>
<property name="message"
value="Consider using special escape sequence instead of octal value or Unicode escaped value."/>
</module>
<module name="AvoidEscapedUnicodeCharacters">
<property name="allowEscapesForControlCharacters" value="true"/>
<property name="allowByTailComment" value="true"/>
<property name="allowNonPrintableEscapes" value="true"/>
</module>
<module name="OneTopLevelClass"/>
<module name="NoLineWrap"/>
<module name="EmptyBlock">
<property name="option" value="TEXT"/>
<property name="tokens"
value="LITERAL_TRY, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/>
</module>
<module name="LeftCurly"/>
<module name="RightCurly">
<property name="id" value="RightCurlySame"/>
<property name="tokens"
value="LITERAL_TRY, LITERAL_CATCH, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE,
LITERAL_DO"/>
</module>
<module name="RightCurly">
<property name="id" value="RightCurlyAlone"/>
<property name="option" value="alone"/>
<property name="tokens"
value="CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, STATIC_INIT,
INSTANCE_INIT"/>
</module>
<module name="WhitespaceAround">
<property name="allowEmptyConstructors" value="true"/>
<property name="allowEmptyLambdas" value="true"/>
<property name="allowEmptyMethods" value="true"/>
<property name="allowEmptyTypes" value="true"/>
<property name="allowEmptyLoops" value="true"/>
<message key="ws.notFollowed"
value="WhitespaceAround: ''{0}'' is not followed by whitespace. Empty blocks may only be represented as '{}' when not part of a multi-block statement (4.1.3)"/>
<message key="ws.notPreceded"
value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/>
</module>
<module name="OneStatementPerLine"/>
<module name="MultipleVariableDeclarations"/>
<module name="ArrayTypeStyle"/>
<module name="MissingSwitchDefault"/>
<module name="FallThrough"/>
<module name="UpperEll"/>
<module name="ModifierOrder"/>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapDot"/>
<property name="tokens" value="DOT"/>
<property name="option" value="nl"/>
</module>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapComma"/>
<property name="tokens" value="COMMA"/>
<property name="option" value="EOL"/>
</module>
<module name="SeparatorWrap">
<!-- ELLIPSIS is EOL until https://github.com/google/styleguide/issues/258 -->
<property name="id" value="SeparatorWrapEllipsis"/>
<property name="tokens" value="ELLIPSIS"/>
<property name="option" value="EOL"/>
</module>
<module name="SeparatorWrap">
<!-- ARRAY_DECLARATOR is EOL until https://github.com/google/styleguide/issues/259 -->
<property name="id" value="SeparatorWrapArrayDeclarator"/>
<property name="tokens" value="ARRAY_DECLARATOR"/>
<property name="option" value="EOL"/>
</module>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapMethodRef"/>
<property name="tokens" value="METHOD_REF"/>
<property name="option" value="nl"/>
</module>
<module name="PackageName">
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>
<message key="name.invalidPattern"
value="Package name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="TypeName">
<message key="name.invalidPattern"
value="Type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MemberName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<message key="name.invalidPattern"
value="Member name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ParameterName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ParameterNumber"/>
<module name="LambdaParameterName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Lambda parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="CatchParameterName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Catch parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="LocalVariableName">
<property name="tokens" value="VARIABLE_DEF"/>
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Local variable name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ClassTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Class type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MethodTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Method type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="InterfaceTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Interface type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="NoFinalizer"/>
<module name="GenericWhitespace">
<message key="ws.followed"
value="GenericWhitespace ''{0}'' is followed by whitespace."/>
<message key="ws.preceded"
value="GenericWhitespace ''{0}'' is preceded with whitespace."/>
<message key="ws.illegalFollow"
value="GenericWhitespace ''{0}'' should followed by whitespace."/>
<message key="ws.notPreceded"
value="GenericWhitespace ''{0}'' is not preceded with whitespace."/>
</module>
<module name="Indentation">
<property name="basicOffset" value="4"/>
<property name="braceAdjustment" value="0"/>
<property name="caseIndent" value="4"/>
<property name="throwsIndent" value="8"/>
<property name="lineWrappingIndentation" value="8"/>
<property name="arrayInitIndent" value="4"/>
</module>
<module name="AbbreviationAsWordInName">
<property name="ignoreFinal" value="false"/>
<property name="allowedAbbreviationLength" value="1"/>
</module>
<module name="OverloadMethodsDeclarationOrder"/>
<module name="VariableDeclarationUsageDistance"/>
<module name="CustomImportOrder">
<property name="customImportOrderRules"
value="THIRD_PARTY_PACKAGE###SPECIAL_IMPORTS###STANDARD_JAVA_PACKAGE###STATIC"/>
<property name="specialImportsRegExp" value="^javax\."/>
<property name="standardPackageRegExp" value="^java\."/>
<property name="sortImportsInGroupAlphabetically" value="true"/>
<property name="separateLineBetweenGroups" value="false"/>
</module>
<module name="MethodParamPad"/>
<module name="NoWhitespaceBefore">
<property name="tokens"
value="COMMA, SEMI, POST_INC, POST_DEC, DOT, ELLIPSIS, METHOD_REF"/>
<property name="allowLineBreaks" value="true"/>
</module>
<module name="ParenPad"/>
<module name="OperatorWrap">
<property name="option" value="eol"/>
<property name="tokens"
value="BAND, BOR, BSR, BXOR, DIV, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR,
LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR, METHOD_REF "/>
</module>
<module name="AnnotationLocation">
<property name="id" value="AnnotationLocationMostCases"/>
<property name="tokens"
value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF"/>
</module>
<module name="AnnotationLocation">
<property name="id" value="AnnotationLocationVariables"/>
<property name="tokens" value="VARIABLE_DEF"/>
<property name="allowSamelineMultipleAnnotations" value="true"/>
</module>
<module name="NonEmptyAtclauseDescription"/>
<module name="JavadocTagContinuationIndentation"/>
<module name="SummaryJavadoc">
<property name="forbiddenSummaryFragments"
value="^@return the *|^This method returns |^A [{]@code [a-zA-Z0-9]+[}]( is a )"/>
</module>
<module name="JavadocParagraph"/>
<module name="AtclauseOrder">
<property name="tagOrder" value="@param, @return, @throws, @deprecated"/>
<property name="target"
value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/>
</module>
<module name="JavadocMethod">
<property name="scope" value="public"/>
<property name="allowedAnnotations" value="Override, Test"/>
</module>
<module name="MethodName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9_]*$"/>
<message key="name.invalidPattern"
value="Method name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="SingleLineJavadoc">
<property name="ignoreInlineTags" value="false"/>
</module>
<module name="EmptyCatchBlock">
<property name="exceptionVariableName" value="expected"/>
</module>
<module name="CommentsIndentation"/>
<module name="AvoidNestedBlocks"/>
<module name="AbstractClassName"/>
<module name="CyclomaticComplexity"/>
<module name="EmptyStatement"/>
</module>
</module>

View File

@@ -0,0 +1,310 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

View File

@@ -0,0 +1,182 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

View File

@@ -0,0 +1,172 @@
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.reflectoring</groupId>
<artifactId>library-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>library-app</name>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath />
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-mapstruct-binding</artifactId>
<version>0.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.4.2.Final</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.4.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-commons</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<!-- Code style checks. Will fail the build if the code is not compliant. -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.1.1</version>
<configuration>
<configLocation>checkstyle.xml</configLocation>
<suppressionsLocation>checkstyle-suppressions.xml</suppressionsLocation>
<encoding>UTF-8</encoding>
<outputEncoding>UTF-8</outputEncoding>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<linkXRef>false</linkXRef>
</configuration>
<executions>
<execution>
<id>verify</id>
<phase>verify</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<!-- Finds bugs in the code. Will fail the build if any are found. -->
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-maven-plugin</artifactId>
<version>4.5.3.0</version>
<dependencies>
<dependency>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs</artifactId>
<version>4.6.0</version>
</dependency>
</dependencies>
<configuration>
<encoding>UTF-8</encoding>
<outputEncoding>UTF-8</outputEncoding>
<includeTests>false</includeTests>
<excludeFilterFile>spotbugs-exclude.xml</excludeFilterFile>
</configuration>
<executions>
<execution>
<id>verify</id>
<phase>verify</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>11</source>
<target>11</target>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.4.2.Final</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,87 @@
<?xml version="1.0" encoding="UTF-8"?>
<FindBugsFilter>
<Match>
<!-- This is required for Immutables (or any annotation processor generated classes causing havoc) -->
<Package name="~.*\.model\.?.*"/>
<Bug pattern="NP_METHOD_PARAMETER_TIGHTENS_ANNOTATION"/>
</Match>
<Match>
<!-- Sample model class. Need not be used -->
<Package name="~.*\.model\.?.*"/>
<Bug pattern="UUF_UNUSED_FIELD"/>
</Match>
<Match>
<!-- Sample model class. Need not be used -->
<Package name="~.*\.model\.?.*"/>
<Bug pattern="EI_EXPOSE_REP"/>
</Match>
<Match>
<!-- Sample model class. Need not be used -->
<Package name="~.*\.config\.?.*"/>
<Bug pattern="EI_EXPOSE_REP"/>
</Match>
<Match>
<!-- Sample model class. Need not be used -->
<Package name="~.*\.config\.?.*"/>
<Bug pattern="EI_EXPOSE_REP2"/>
</Match>
<Match>
<!-- Sample model class. Need not be used -->
<Package name="~.*\.model\.?.*"/>
<Bug pattern="EI_EXPOSE_REP2"/>
</Match>
<Match>
<!-- Sample model class. Need not be used -->
<Package name="~.*\.exception\.?.*"/>
<Bug pattern="EI_EXPOSE_REP2"/>
</Match>
<Match>
<!-- Sample model class. Need not be used -->
<Package name="~.*\.exception\.?.*"/>
<Bug pattern="EI_EXPOSE_REP"/>
</Match>
<Match>
<!-- Sample model class. Need not be used -->
<Package name="~.*\.web\.?.*"/>
<Bug pattern="EI_EXPOSE_REP"/>
</Match>
<Match>
<!-- Sample model class. Need not be used -->
<Package name="~.*\.web\.?.*"/>
<Bug pattern="EI_EXPOSE_REP2"/>
</Match>
<Match>
<!-- Sample model class. Need not be read -->
<Package name="~.*\.model\.?.*"/>
<Bug pattern="URF_UNREAD_FIELD"/>
</Match>
<Match>
<Package name="~.*\.model\.?.*"/>
<Bug pattern="RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT"/>
</Match>
</FindBugsFilter>

View File

@@ -0,0 +1,19 @@
package com.reflectoring.library;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
private static Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@@ -0,0 +1,16 @@
package com.reflectoring.library.config;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "auth")
@Getter
@Setter
public class BasicAuthConfigProperties {
private String username;
private String password;
}

View File

@@ -0,0 +1,65 @@
package com.reflectoring.library.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.reflectoring.library.exception.AuthenticationErrorHandler;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableConfigurationProperties(BasicAuthConfigProperties.class)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private static final String URI_PATTERN = "/library/managed/**";
private final BasicAuthConfigProperties basicAuth;
public SecurityConfiguration(BasicAuthConfigProperties basicAuth) {
this.basicAuth = basicAuth;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers(URI_PATTERN).permitAll()
.antMatchers("/v2/api-docs/**").permitAll()
.antMatchers("/swagger-ui/**").permitAll()
.antMatchers("/swagger-ui.html").permitAll().and()
.addFilter(new BasicAuthenticationFilter(authenticationManager(),
authenticationErrorHandler()))
.formLogin().disable()
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(authenticationErrorHandler());
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser(basicAuth.getUsername())
.password(PasswordEncoderFactories
.createDelegatingPasswordEncoder()
.encode(basicAuth.getPassword()))
.roles("USER");
}
@Bean
public AuthenticationEntryPoint authenticationErrorHandler() {
AuthenticationErrorHandler authErrorHandler =
new AuthenticationErrorHandler(new ObjectMapper());
authErrorHandler.setRealmName("Library Authentication");
return authErrorHandler;
}
}

View File

@@ -0,0 +1,47 @@
package com.reflectoring.library.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.BasicAuth;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
SecurityReference securityReference = SecurityReference.builder()
.reference("basicAuth")
.scopes(new AuthorizationScope[0])
.build();
ArrayList<SecurityReference> reference = new ArrayList<>(1);
reference.add(securityReference);
ArrayList<SecurityContext> securityContexts = new ArrayList<>(1);
securityContexts.add(SecurityContext.builder().securityReferences(reference).build());
ArrayList<SecurityScheme> auth = new ArrayList<>(1);
auth.add(new BasicAuth("basicAuth"));
return new Docket(DocumentationType.SWAGGER_2)
.securitySchemes(auth)
.securityContexts(securityContexts)
.select()
.paths(PathSelectors.ant("/library/managed/books/**"))
.apis(RequestHandlerSelectors.basePackage("com.reflectoring.library"))
.build();
}
}

View File

@@ -0,0 +1,30 @@
package com.reflectoring.library.exception;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.reflectoring.library.model.Response;
import com.reflectoring.library.model.Status;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class AuthenticationErrorHandler extends BasicAuthenticationEntryPoint {
private final ObjectMapper objectMapper;
public AuthenticationErrorHandler(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException ex) throws IOException {
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getOutputStream().println(objectMapper.writeValueAsString(
new Response(Status.ERROR.toString(), "Unauthorised")));
}
}

View File

@@ -0,0 +1,23 @@
package com.reflectoring.library.mapper;
import com.reflectoring.library.model.mapstruct.AuthorDto;
import com.reflectoring.library.model.mapstruct.BookDto;
import com.reflectoring.library.model.persistence.Author;
import com.reflectoring.library.model.persistence.Book;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import java.util.List;
@Mapper(componentModel = "spring")
public interface LibraryMapper {
BookDto bookToBookDto(Book book);
List<BookDto> bookToBookDto(List<Book> book);
AuthorDto authorToAuthorDto(Author author);
Book bookDtoToBook(BookDto bookDto);
Author authorDtoToAuthor(AuthorDto authorDto);
}

Some files were not shown because too many files have changed in this diff Show More