├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src ├── main │ ├── resources │ │ ├── config │ │ │ ├── application-hsqldb.properties │ │ │ ├── application-batch.properties │ │ │ ├── application-mysql.properties │ │ │ └── application.properties │ │ └── data │ │ │ └── changelog │ │ │ ├── db.changelog-master.xml │ │ │ └── db.changelog-1.7.0.xml │ └── java │ │ └── com │ │ └── leanstacks │ │ └── ws │ │ ├── model │ │ ├── Role.java │ │ ├── Greeting.java │ │ ├── ReferenceEntity.java │ │ ├── Account.java │ │ └── TransactionalEntity.java │ │ ├── repository │ │ ├── GreetingRepository.java │ │ └── AccountRepository.java │ │ ├── service │ │ ├── AccountService.java │ │ ├── AccountServiceBean.java │ │ ├── EmailService.java │ │ ├── GreetingService.java │ │ ├── EmailServiceBean.java │ │ └── GreetingServiceBean.java │ │ ├── Application.java │ │ ├── security │ │ ├── RestBasicAuthenticationEntryPoint.java │ │ ├── AccountUserDetailsService.java │ │ ├── AccountAuthenticationProvider.java │ │ ├── CorsProperties.java │ │ └── SecurityConfiguration.java │ │ ├── actuator │ │ └── health │ │ │ └── GreetingHealthIndicator.java │ │ ├── web │ │ ├── filter │ │ │ └── RequestContextInitializationFilter.java │ │ └── api │ │ │ ├── ExceptionDetailBuilder.java │ │ │ ├── ExceptionDetail.java │ │ │ ├── RestResponseEntityExceptionHandler.java │ │ │ └── GreetingController.java │ │ ├── util │ │ └── RequestContext.java │ │ └── batch │ │ └── GreetingBatchBean.java ├── docs │ └── asciidoc │ │ ├── _includes │ │ ├── http-response-error.adoc │ │ └── response-fields-error.adoc │ │ ├── delete-greeting.adoc │ │ ├── get-greetings.adoc │ │ ├── index.adoc │ │ ├── create-greeting.adoc │ │ ├── get-greeting.adoc │ │ ├── send-greeting.adoc │ │ └── update-greeting.adoc └── test │ └── java │ └── com │ └── leanstacks │ └── ws │ ├── BasicTransactionalTest.java │ ├── RestControllerTest.java │ ├── BasicTest.java │ ├── AbstractTest.java │ ├── web │ └── api │ │ ├── DeleteGreetingDocTest.java │ │ ├── GetGreetingsDocTest.java │ │ ├── GetGreetingDocTest.java │ │ ├── CreateGreetingDocTest.java │ │ ├── SendGreetingDocTest.java │ │ ├── UpdateGreetingDocTest.java │ │ └── GreetingControllerTest.java │ ├── util │ └── BCryptPasswordEncoderUtil.java │ ├── AbstractDocTest.java │ └── service │ └── GreetingServiceTest.java ├── .gitignore ├── Jenkinsfile ├── Dockerfile ├── gradlew.bat ├── etc ├── pmd │ └── ruleset.xml └── checkstyle │ └── rules.xml ├── pom.xml ├── mvnw.cmd ├── gradlew ├── mvnw └── LICENSE /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leanstacks/skeleton-ws-spring-boot/HEAD/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leanstacks/skeleton-ws-spring-boot/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip -------------------------------------------------------------------------------- /src/main/resources/config/application-hsqldb.properties: -------------------------------------------------------------------------------- 1 | ## 2 | # The HSQLDB Application Configuration File 3 | # 4 | # This file is included when the 'hsqldb' Spring Profile is active. 5 | ## 6 | 7 | ## 8 | # Data Source Configuration 9 | ## 10 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Eclipse Directories and Files 2 | .project 3 | .classpath 4 | /.settings 5 | 6 | # Generated Directories and Files 7 | /target 8 | /build 9 | /bin 10 | /.gradle 11 | 12 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 13 | hs_err_pid* 14 | -------------------------------------------------------------------------------- /src/main/resources/config/application-batch.properties: -------------------------------------------------------------------------------- 1 | ## 2 | # The Batch Application Configuration File 3 | # 4 | # This file is included when the 'batch' Spring Profile is active. 5 | ## 6 | 7 | ## 8 | # Greeting Batch Configuration 9 | ## 10 | batch.greeting.fixedrate=3600000 11 | batch.greeting.fixeddelay=3600000 12 | batch.greeting.initialdelay=15000 13 | batch.greeting.cron=0 0 * * * * 14 | -------------------------------------------------------------------------------- /src/docs/asciidoc/_includes/http-response-error.adoc: -------------------------------------------------------------------------------- 1 | [source,http,options="nowrap"] 2 | ---- 3 | HTTP/1.1 404 4 | Content-Length: 213 5 | Content-Type: application/json;charset=UTF-8 6 | 7 | { 8 | "timestamp": "2018-12-12T13:16:11.771539Z", 9 | "method": "GET", 10 | "path": "/api/...", 11 | "status": 404, 12 | "statusText": "Not Found", 13 | "exceptionClass": "java.util.NoSuchElementException", 14 | "exceptionMessage": "No value present" 15 | } 16 | ---- -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/model/Role.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.model; 2 | 3 | import javax.persistence.Entity; 4 | 5 | /** 6 | * The Role class is an entity model object. A Role describes a privilege level within the application. A Role is used 7 | * to authorize an Account to access a set of application resources. 8 | * 9 | * @author Matt Warman 10 | */ 11 | @Entity 12 | public class Role extends ReferenceEntity { 13 | 14 | private static final long serialVersionUID = 1L; 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/leanstacks/ws/BasicTransactionalTest.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | @Target(ElementType.TYPE) 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @BasicTest 13 | @Transactional 14 | public @interface BasicTransactionalTest { 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/leanstacks/ws/RestControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 9 | 10 | @Target(ElementType.TYPE) 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @BasicTransactionalTest 13 | @AutoConfigureMockMvc 14 | public @interface RestControllerTest { 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/leanstacks/ws/BasicTest.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | import org.springframework.test.context.ActiveProfiles; 10 | 11 | @Target(ElementType.TYPE) 12 | @Retention(RetentionPolicy.RUNTIME) 13 | @SpringBootTest 14 | @ActiveProfiles("hsqldb") 15 | public @interface BasicTest { 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/docs/asciidoc/_includes/response-fields-error.adoc: -------------------------------------------------------------------------------- 1 | |=== 2 | |Path|Type|Description 3 | 4 | |`+timestamp+` 5 | |`+String+` 6 | |The time the error occurred. 7 | 8 | |`+method+` 9 | |`+String+` 10 | |The HTTP method. 11 | 12 | |`+path+` 13 | |`+String+` 14 | |The request context path. 15 | 16 | |`+status+` 17 | |`+Number+` 18 | |The response HTTP status code. 19 | 20 | |`+statusText+` 21 | |`+String+` 22 | |The response HTTP status text. 23 | 24 | |`+exceptionClass+` 25 | |`+String+` 26 | |The exception class. 27 | 28 | |`+exceptionMessage+` 29 | |`+String+` 30 | |The exception message. 31 | 32 | |=== -------------------------------------------------------------------------------- /src/main/resources/config/application-mysql.properties: -------------------------------------------------------------------------------- 1 | ## 2 | # The MySQL Application Configuration File 3 | # 4 | # This file is included when the 'mysql' Spring Profile is active. 5 | ## 6 | 7 | ## 8 | # Data Source Configuration 9 | ## 10 | #Connection 11 | spring.datasource.url=jdbc:mysql://localhost/skeleton?useSSL=false 12 | spring.datasource.username=skeluser 13 | spring.datasource.password=skelpass 14 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver 15 | 16 | # Pool 17 | spring.datasource.hikari.connection-test-query=select 1; 18 | spring.datasource.hikari.idle-timeout=300000 19 | spring.datasource.hikari.maximum-pool-size=50 20 | 21 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/repository/GreetingRepository.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | 6 | import com.leanstacks.ws.model.Greeting; 7 | 8 | /** 9 | * The GreetingRepository interface is a Spring Data JPA data repository for 10 | * Greeting entities. The GreetingRepository provides all the data access 11 | * behaviors exposed by JpaRepository and additional custom 12 | * behaviors may be defined in this interface. 13 | * 14 | * @author Matt Warman 15 | */ 16 | @Repository 17 | public interface GreetingRepository extends JpaRepository { 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/docs/asciidoc/delete-greeting.adoc: -------------------------------------------------------------------------------- 1 | = API Endpoint - Delete Greeting 2 | LeanStacks; 3 | :doctype: book 4 | :icons: font 5 | :source-highlighter: highlightjs 6 | :includedir: _includes 7 | 8 | == Delete a greeting 9 | 10 | === DELETE /api/greetings/{id} 11 | 12 | Delete all information about a specific greeting. 13 | 14 | === Example Request 15 | 16 | Using cURL: 17 | 18 | include::{snippets}/delete-greeting/curl-request.adoc[] 19 | 20 | The HTTP request: 21 | 22 | include::{snippets}/delete-greeting/http-request.adoc[] 23 | 24 | === Example Response 25 | 26 | include::{snippets}/delete-greeting/http-response.adoc[] 27 | 28 | === Example Error Response 29 | 30 | include::{includedir}/http-response-error.adoc[] 31 | 32 | include::{includedir}/response-fields-error.adoc[] 33 | -------------------------------------------------------------------------------- /src/main/resources/data/changelog/db.changelog-master.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/docs/asciidoc/get-greetings.adoc: -------------------------------------------------------------------------------- 1 | = API Endpoint - Get Greetings 2 | LeanStacks; 3 | :doctype: book 4 | :icons: font 5 | :source-highlighter: highlightjs 6 | :includedir: _includes 7 | 8 | == Get a list of greetings 9 | 10 | === GET /api/greetings 11 | 12 | Get a list of all greetings. 13 | 14 | === Response Body Parameters 15 | 16 | include::{snippets}/get-greeting/response-fields.adoc[] 17 | 18 | === Example Request 19 | 20 | Using cURL: 21 | 22 | include::{snippets}/get-greetings/curl-request.adoc[] 23 | 24 | The HTTP request: 25 | 26 | include::{snippets}/get-greetings/http-request.adoc[] 27 | 28 | === Example Response 29 | 30 | include::{snippets}/get-greetings/http-response.adoc[] 31 | 32 | === Example Error Response 33 | 34 | include::{includedir}/http-response-error.adoc[] 35 | 36 | include::{includedir}/response-fields-error.adoc[] 37 | -------------------------------------------------------------------------------- /src/docs/asciidoc/index.adoc: -------------------------------------------------------------------------------- 1 | = Overview 2 | :doctype: book 3 | :icons: font 4 | :source-highlighter: highlightjs 5 | 6 | Review the available resources from the LeanStacks API. Click any endpoint for additional information. 7 | 8 | === Greetings 9 | 10 | [cols="2,4,4",options="header"] 11 | |=== 12 | 13 | | HTTP method | Endpoint | Function 14 | 15 | | GET | <> | Get a list of greetings 16 | 17 | | GET | <> | Get a specific greeting 18 | 19 | | POST | <> | Create a greeting 20 | 21 | | PUT | <> | Update a greeting 22 | 23 | | DELETE | <> | Delete a greeting 24 | 25 | | POST | <> | Send a greeting 26 | 27 | |=== 28 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/service/AccountService.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.service; 2 | 3 | import java.util.Optional; 4 | 5 | import com.leanstacks.ws.model.Account; 6 | 7 | /** 8 | *

9 | * The AccountService interface defines all public business behaviors for operations on the Account entity model and 10 | * some related entities such as Role. 11 | *

12 | *

13 | * This interface should be injected into AccountService clients, not the implementation bean. 14 | *

15 | * 16 | * @author Matt Warman 17 | */ 18 | public interface AccountService { 19 | 20 | /** 21 | * Find an Account by the username attribute value. 22 | * 23 | * @param username A String username to query the repository. 24 | * @return An Optional wrapped Account. 25 | */ 26 | Optional findByUsername(String username); 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/docs/asciidoc/create-greeting.adoc: -------------------------------------------------------------------------------- 1 | = API Endpoint - Create Greeting 2 | LeanStacks; 3 | :doctype: book 4 | :icons: font 5 | :source-highlighter: highlightjs 6 | :includedir: _includes 7 | 8 | == Create a new greeting 9 | 10 | === POST /api/greetings 11 | 12 | Create a new greeting. 13 | 14 | === Request Body Parameters 15 | 16 | include::{snippets}/create-greeting/request-fields.adoc[] 17 | 18 | === Response Body Parameters 19 | 20 | include::{snippets}/create-greeting/response-fields.adoc[] 21 | 22 | === Example Request 23 | 24 | Using cURL: 25 | 26 | include::{snippets}/create-greeting/curl-request.adoc[] 27 | 28 | The HTTP request: 29 | 30 | include::{snippets}/create-greeting/http-request.adoc[] 31 | 32 | === Example Response 33 | 34 | include::{snippets}/create-greeting/http-response.adoc[] 35 | 36 | === Example Error Response 37 | 38 | include::{includedir}/http-response-error.adoc[] 39 | 40 | include::{includedir}/response-fields-error.adoc[] 41 | -------------------------------------------------------------------------------- /src/docs/asciidoc/get-greeting.adoc: -------------------------------------------------------------------------------- 1 | = API Endpoint - Get Greeting 2 | LeanStacks; 3 | :doctype: book 4 | :icons: font 5 | :source-highlighter: highlightjs 6 | :includedir: _includes 7 | 8 | == Get a specific greeting 9 | 10 | === GET /api/greetings/{id} 11 | 12 | Get the information about a specific greeting. 13 | 14 | === Path Parameters 15 | 16 | include::{snippets}/get-greeting/path-parameters.adoc[] 17 | 18 | === Response Body Parameters 19 | 20 | include::{snippets}/get-greeting/response-fields.adoc[] 21 | 22 | === Example Request 23 | 24 | Using cURL: 25 | 26 | include::{snippets}/get-greeting/curl-request.adoc[] 27 | 28 | The HTTP request: 29 | 30 | include::{snippets}/get-greeting/http-request.adoc[] 31 | 32 | === Example Response 33 | 34 | include::{snippets}/get-greeting/http-response.adoc[] 35 | 36 | === Example Error Response 37 | 38 | include::{includedir}/http-response-error.adoc[] 39 | 40 | include::{includedir}/response-fields-error.adoc[] 41 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/repository/AccountRepository.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.repository; 2 | 3 | import java.util.Optional; 4 | 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import com.leanstacks.ws.model.Account; 9 | 10 | /** 11 | * The AccountRepository interface is a Spring Data JPA data repository for Account entities. The AccountRepository 12 | * provides all the data access behaviors exposed by JpaRepository and additional custom behaviors may be 13 | * defined in this interface. 14 | * 15 | * @author Matt Warman 16 | */ 17 | @Repository 18 | public interface AccountRepository extends JpaRepository { 19 | 20 | /** 21 | * Query for a single Account entity by username. 22 | * 23 | * @param username The username value to query the repository. 24 | * @return An Optional Account. 25 | */ 26 | Optional findByUsername(String username); 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Jenkinsfile: -------------------------------------------------------------------------------- 1 | node { 2 | stage('Prepare') { 3 | echo 'Preparing...' 4 | checkout scm 5 | } 6 | stage('Build') { 7 | echo 'Building...' 8 | sh './gradlew' 9 | } 10 | stage('Report') { 11 | echo 'Reporting...' 12 | junit '**/build/test-results/test/*.xml' 13 | jacoco classPattern: '**/build/classes', exclusionPattern: '**/*Test*.class', execPattern: '**/build/jacoco/**.exec' 14 | checkstyle canComputeNew: false, defaultEncoding: '', healthy: '', pattern: '**/build/reports/checkstyle/*.xml', unHealthy: '' 15 | pmd canComputeNew: false, defaultEncoding: '', healthy: '', pattern: '**/build/reports/pmd/*.xml', unHealthy: '' 16 | } 17 | stage('Docker') { 18 | echo 'Building Docker Image...' 19 | def IMAGE_NAME = 'leanstacks/skeleton-ws-spring-boot' 20 | def image = docker.build("${IMAGE_NAME}:latest") 21 | docker.withRegistry('', 'docker-hub-leanstacks') { 22 | image.push() 23 | } 24 | sh "docker image rm ${IMAGE_NAME}:latest" 25 | } 26 | } -------------------------------------------------------------------------------- /src/docs/asciidoc/send-greeting.adoc: -------------------------------------------------------------------------------- 1 | = API Endpoint - Send Greeting 2 | LeanStacks; 3 | :doctype: book 4 | :icons: font 5 | :source-highlighter: highlightjs 6 | :includedir: _includes 7 | 8 | == Send a greeting 9 | 10 | === POST /api/greetings/{id}/send 11 | 12 | Email a specific greeting synchronously or asynchronously. 13 | 14 | === Path Parameters 15 | 16 | include::{snippets}/send-greeting/path-parameters.adoc[] 17 | 18 | === Request Parameters 19 | 20 | include::{snippets}/send-greeting/request-parameters.adoc[] 21 | 22 | === Response Body Parameters 23 | 24 | include::{snippets}/send-greeting/response-fields.adoc[] 25 | 26 | === Example Request 27 | 28 | Using cURL: 29 | 30 | include::{snippets}/send-greeting/curl-request.adoc[] 31 | 32 | The HTTP request: 33 | 34 | include::{snippets}/send-greeting/http-request.adoc[] 35 | 36 | === Example Response 37 | 38 | include::{snippets}/send-greeting/http-response.adoc[] 39 | 40 | === Example Error Response 41 | 42 | include::{includedir}/http-response-error.adoc[] 43 | 44 | include::{includedir}/response-fields-error.adoc[] 45 | -------------------------------------------------------------------------------- /src/docs/asciidoc/update-greeting.adoc: -------------------------------------------------------------------------------- 1 | = API Endpoint - Update Greeting 2 | LeanStacks; 3 | :doctype: book 4 | :icons: font 5 | :source-highlighter: highlightjs 6 | :includedir: _includes 7 | 8 | == Update a greeting 9 | 10 | === PUT /api/greetings/{id} 11 | 12 | Update the information about a specific greeting. 13 | 14 | === Path Parameters 15 | 16 | include::{snippets}/update-greeting/path-parameters.adoc[] 17 | 18 | === Request Body Parameters 19 | 20 | include::{snippets}/update-greeting/request-fields.adoc[] 21 | 22 | === Response Body Parameters 23 | 24 | include::{snippets}/update-greeting/response-fields.adoc[] 25 | 26 | === Example Request 27 | 28 | Using cURL: 29 | 30 | include::{snippets}/update-greeting/curl-request.adoc[] 31 | 32 | The HTTP request: 33 | 34 | include::{snippets}/update-greeting/http-request.adoc[] 35 | 36 | === Example Response 37 | 38 | include::{snippets}/update-greeting/http-response.adoc[] 39 | 40 | === Example Error Response 41 | 42 | include::{includedir}/http-response-error.adoc[] 43 | 44 | include::{includedir}/response-fields-error.adoc[] 45 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/model/Greeting.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.model; 2 | 3 | import javax.persistence.Entity; 4 | import javax.validation.constraints.NotNull; 5 | 6 | /** 7 | * The Greeting class is an entity model object. 8 | * 9 | * @author Matt Warman 10 | */ 11 | @Entity 12 | public class Greeting extends TransactionalEntity { 13 | 14 | private static final long serialVersionUID = 1L; 15 | 16 | /** 17 | * The text value. 18 | */ 19 | @NotNull 20 | private String text; 21 | 22 | /** 23 | * Create a new Greeting object. 24 | */ 25 | public Greeting() { 26 | super(); 27 | } 28 | 29 | /** 30 | * Create a new Greeting object with the supplied text value. 31 | * 32 | * @param text A String text value. 33 | */ 34 | public Greeting(final String text) { 35 | super(); 36 | this.text = text; 37 | } 38 | 39 | public String getText() { 40 | return text; 41 | } 42 | 43 | public void setText(final String text) { 44 | this.text = text; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/Application.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cache.annotation.EnableCaching; 6 | import org.springframework.scheduling.annotation.EnableAsync; 7 | import org.springframework.scheduling.annotation.EnableScheduling; 8 | import org.springframework.transaction.annotation.EnableTransactionManagement; 9 | 10 | /** 11 | * Spring Boot main application class. 12 | * 13 | * @author Matt Warman 14 | */ 15 | @SpringBootApplication 16 | @EnableTransactionManagement 17 | @EnableCaching 18 | @EnableScheduling 19 | @EnableAsync 20 | public class Application { 21 | 22 | /** 23 | * The name of the Cache for Greeting entities. 24 | */ 25 | public static final String CACHE_GREETINGS = "greetings"; 26 | 27 | /** 28 | * Entry point for the application. 29 | * 30 | * @param args Command line arguments. 31 | */ 32 | public static void main(final String... args) { 33 | SpringApplication.run(Application.class, args); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/security/RestBasicAuthenticationEntryPoint.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.security; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.ServletException; 6 | import javax.servlet.http.HttpServletRequest; 7 | import javax.servlet.http.HttpServletResponse; 8 | 9 | import org.springframework.security.core.AuthenticationException; 10 | import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; 11 | 12 | /** 13 | * An implementation of Spring Security AuthenticationEntryPoint. Extends the default functionality of 14 | * BasicAuthenticationEntryPoint. Updates the HTTP Response with HTTP 401 status if authentication fails. 15 | * 16 | * @author Matt Warman 17 | * 18 | */ 19 | public class RestBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { 20 | 21 | @Override 22 | public void commence(final HttpServletRequest request, final HttpServletResponse response, 23 | final AuthenticationException authException) throws IOException, ServletException { 24 | 25 | response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\""); 26 | response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); 27 | 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # From the OpenJDK image 2 | FROM openjdk:11.0.1-jre-slim 3 | 4 | # Java Options 5 | ENV JAVA_OPTS="-server -Xmn384m -Xms1024m -Xmx1024m -XX:+UseParallelGC -verbose:gc" 6 | 7 | # Listens to port 8080 for HTTP connections 8 | EXPOSE 8080 9 | 10 | # Create application base directory 11 | RUN mkdir -p /var/lib/bootapp 12 | 13 | # Change working directory to the application base 14 | WORKDIR /var/lib/bootapp 15 | 16 | # Use the Gradle build artifact(s) 17 | COPY ./build/libs/*.jar application.jar 18 | 19 | # Runs the executable JAR produced by the Gradle build 20 | # Note: You may pass in environment variable key-pairs to override values 21 | # in the Spring Boot application configuration using the 22 | # "-e ENV_VARIABLE=value" option in the Docker Container Run command. 23 | # This is useful for supplying Spring Profile values or 24 | # any environment-specific overrides. 25 | # 26 | # Example: Run the application on port 8080 with default configuration: 27 | # docker container run --detach --publish 8080:8080 leanstacks/skeleton-ws-spring-boot:latest 28 | # 29 | # Example: Run the application on port 8080 with specific Spring Profiles: 30 | # docker container run --detach --publish 8080:8080 -e SPRING_PROFILES_ACTIVE=hsqldb leanstacks/skeleton-ws-spring-boot:latest 31 | # 32 | CMD java $JAVA_OPTS -jar application.jar -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/service/AccountServiceBean.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.service; 2 | 3 | import java.util.Optional; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Service; 9 | 10 | import com.leanstacks.ws.model.Account; 11 | import com.leanstacks.ws.repository.AccountRepository; 12 | 13 | /** 14 | * The AccountServiceBean encapsulates all business behaviors for operations on the Account entity model and some 15 | * related entities such as Role. 16 | * 17 | * @author Matt Warman 18 | */ 19 | @Service 20 | public class AccountServiceBean implements AccountService { 21 | 22 | /** 23 | * The Logger for this Class. 24 | */ 25 | private static final Logger logger = LoggerFactory.getLogger(AccountServiceBean.class); 26 | 27 | /** 28 | * The Spring Data repository for Account entities. 29 | */ 30 | @Autowired 31 | private transient AccountRepository accountRepository; 32 | 33 | @Override 34 | public Optional findByUsername(final String username) { 35 | logger.info("> findByUsername"); 36 | 37 | final Optional accountOptional = accountRepository.findByUsername(username); 38 | 39 | logger.info("< findByUsername"); 40 | return accountOptional; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/service/EmailService.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.service; 2 | 3 | import java.util.concurrent.Future; 4 | 5 | import com.leanstacks.ws.model.Greeting; 6 | 7 | /** 8 | *

9 | * The EmailService interface defines all public business behaviors for composing and transmitting email messages. 10 | *

11 | *

12 | * This interface should be injected into EmailService clients, not the implementation bean. 13 | *

14 | * 15 | * @author Matt Warman 16 | */ 17 | public interface EmailService { 18 | 19 | /** 20 | * Send a Greeting via email synchronously. 21 | * 22 | * @param greeting A Greeting to send. 23 | * @return A Boolean whose value is TRUE if sent successfully; otherwise FALSE. 24 | */ 25 | Boolean send(Greeting greeting); 26 | 27 | /** 28 | * Send a Greeting via email asynchronously. 29 | * 30 | * @param greeting A Greeting to send. 31 | */ 32 | void sendAsync(Greeting greeting); 33 | 34 | /** 35 | * Send a Greeting via email asynchronously. Returns a Future<Boolean> response allowing the client to obtain 36 | * the status of the operation once it is completed. 37 | * 38 | * @param greeting A Greeting to send. 39 | * @return A Future<Boolean> whose value is TRUE if sent successfully; otherwise, FALSE. 40 | */ 41 | Future sendAsyncWithResult(Greeting greeting); 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/actuator/health/GreetingHealthIndicator.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.actuator.health; 2 | 3 | import java.util.Collection; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.actuate.health.Health; 7 | import org.springframework.boot.actuate.health.HealthIndicator; 8 | import org.springframework.stereotype.Component; 9 | 10 | import com.leanstacks.ws.model.Greeting; 11 | import com.leanstacks.ws.service.GreetingService; 12 | 13 | /** 14 | * The GreetingHealthIndicator is an example implementation of a Spring Boot 15 | * Actuator HealthIndicator. When Actuator's Health Endpoint is invoked, it 16 | * polls all HealthIndicator implementations to ascertain an aggregate status of 17 | * the application's health status. 18 | * 19 | * @author Matt Warman 20 | * 21 | */ 22 | @Component 23 | public class GreetingHealthIndicator implements HealthIndicator { 24 | 25 | /** 26 | * The GreetingService business service. 27 | */ 28 | @Autowired 29 | private transient GreetingService greetingService; 30 | 31 | @Override 32 | public Health health() { 33 | final Collection greetings = greetingService.findAll(); 34 | 35 | if (greetings == null || greetings.isEmpty()) { 36 | return Health.down().withDetail("count", 0).build(); 37 | } 38 | 39 | return Health.up().withDetail("count", greetings.size()).build(); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/test/java/com/leanstacks/ws/AbstractTest.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws; 2 | 3 | import org.junit.After; 4 | import org.junit.Before; 5 | 6 | import com.leanstacks.ws.util.RequestContext; 7 | 8 | /** 9 | * The AbstractTest class is the parent of all JUnit test classes. This class configures the test ApplicationContext and 10 | * test runner environment. 11 | * 12 | * @author Matt Warman 13 | */ 14 | public abstract class AbstractTest { 15 | 16 | /** 17 | * The username value used in the RequestContext for Unit Tests. 18 | */ 19 | public static final String USERNAME = "unittest"; 20 | 21 | /** 22 | * Tasks performed before each test method. 23 | */ 24 | @Before 25 | public void before() { 26 | RequestContext.setUsername(AbstractTest.USERNAME); 27 | doBeforeEachTest(); 28 | } 29 | 30 | /** 31 | * Perform initialization tasks before the execution of each test method. Concrete test classes may override this 32 | * method to implement class-specific tasks. 33 | */ 34 | public abstract void doBeforeEachTest(); 35 | 36 | /** 37 | * Tasks performed after each test method. 38 | */ 39 | @After 40 | public void after() { 41 | doAfterEachTest(); 42 | } 43 | 44 | /** 45 | * Perform clean up tasks after the execution of each test method. Concrete test classes may override this method to 46 | * implement class-specific tasks. 47 | */ 48 | public abstract void doAfterEachTest(); 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/web/filter/RequestContextInitializationFilter.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.web.filter; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.FilterChain; 6 | import javax.servlet.ServletException; 7 | import javax.servlet.ServletRequest; 8 | import javax.servlet.ServletResponse; 9 | 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | import org.springframework.core.Ordered; 13 | import org.springframework.core.annotation.Order; 14 | import org.springframework.stereotype.Component; 15 | import org.springframework.web.filter.GenericFilterBean; 16 | 17 | import com.leanstacks.ws.util.RequestContext; 18 | 19 | /** 20 | * The RequestContextInitializationFilter is executed for every web request. The filter initializes the RequestContext 21 | * for the current thread, preventing leaking of RequestContext attributes from the previous thread's execution. 22 | * 23 | * @author Matt Warman 24 | */ 25 | @Component 26 | @Order(Ordered.HIGHEST_PRECEDENCE) 27 | public class RequestContextInitializationFilter extends GenericFilterBean { 28 | 29 | /** 30 | * The Logger for this class. 31 | */ 32 | private static final Logger logger = LoggerFactory.getLogger(RequestContextInitializationFilter.class); 33 | 34 | @Override 35 | public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain) 36 | throws IOException, ServletException { 37 | logger.info("> doFilter"); 38 | 39 | RequestContext.init(); 40 | 41 | chain.doFilter(req, resp); 42 | logger.info("< doFilter"); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/util/RequestContext.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.util; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | /** 7 | *

8 | * The RequestContext facilitates the storage of information for the duration of a single request (or web service 9 | * transaction). 10 | *

11 | *

12 | * RequestContext attributes are stored in ThreadLocal objects. 13 | *

14 | * 15 | * @author Matt Warman 16 | * 17 | */ 18 | public final class RequestContext { 19 | 20 | /** 21 | * The Logger for this Class. 22 | */ 23 | private static final Logger logger = LoggerFactory.getLogger(RequestContext.class); 24 | 25 | /** 26 | * ThreadLocal storage of username Strings. 27 | */ 28 | private static ThreadLocal usernames = new ThreadLocal(); 29 | 30 | private RequestContext() { 31 | 32 | } 33 | 34 | /** 35 | * Get the username for the current thread. 36 | * 37 | * @return A String username. 38 | */ 39 | public static String getUsername() { 40 | return usernames.get(); 41 | } 42 | 43 | /** 44 | * Set the username for the current thread. 45 | * 46 | * @param username A String username. 47 | */ 48 | public static void setUsername(final String username) { 49 | usernames.set(username); 50 | logger.debug("RequestContext added username {} to current thread", username); 51 | } 52 | 53 | /** 54 | * Initialize the ThreadLocal attributes for the current thread. 55 | */ 56 | public static void init() { 57 | usernames.set(null); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/service/GreetingService.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.service; 2 | 3 | import java.util.List; 4 | import java.util.Optional; 5 | 6 | import com.leanstacks.ws.model.Greeting; 7 | 8 | /** 9 | *

10 | * The GreetingService interface defines all public business behaviors for operations on the Greeting entity model. 11 | *

12 | *

13 | * This interface should be injected into GreetingService clients, not the implementation bean. 14 | *

15 | * 16 | * @author Matt Warman 17 | */ 18 | public interface GreetingService { 19 | 20 | /** 21 | * Find all Greeting entities. 22 | * 23 | * @return A List of Greeting objects. 24 | */ 25 | List findAll(); 26 | 27 | /** 28 | * Find a single Greeting entity by primary key identifier. Returns an Optional wrapped Greeting. 29 | * 30 | * @param id A Long primary key identifier. 31 | * @return A Optional Greeting 32 | */ 33 | Optional findOne(Long id); 34 | 35 | /** 36 | * Persists a Greeting entity in the data store. 37 | * 38 | * @param greeting A Greeting object to be persisted. 39 | * @return A persisted Greeting object or null if a problem occurred. 40 | */ 41 | Greeting create(Greeting greeting); 42 | 43 | /** 44 | * Updates a previously persisted Greeting entity in the data store. 45 | * 46 | * @param greeting A Greeting object to be updated. 47 | * @return An updated Greeting object or null if a problem occurred. 48 | */ 49 | Greeting update(Greeting greeting); 50 | 51 | /** 52 | * Removes a previously persisted Greeting entity from the data store. 53 | * 54 | * @param id A Long primary key identifier. 55 | */ 56 | void delete(Long id); 57 | 58 | /** 59 | * Evicts all members of the "greetings" cache. 60 | */ 61 | void evictCache(); 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/service/EmailServiceBean.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.service; 2 | 3 | import java.util.concurrent.Future; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.scheduling.annotation.Async; 8 | import org.springframework.scheduling.annotation.AsyncResult; 9 | import org.springframework.stereotype.Service; 10 | 11 | import com.leanstacks.ws.model.Greeting; 12 | 13 | /** 14 | * The EmailServiceBean encapsulates all business behaviors defined by the EmailService interface. 15 | * 16 | * @author Matt Warman 17 | */ 18 | @Service 19 | public class EmailServiceBean implements EmailService { 20 | 21 | /** 22 | * The Logger for this Class. 23 | */ 24 | private static final Logger logger = LoggerFactory.getLogger(EmailServiceBean.class); 25 | 26 | /** 27 | * Default Thread sleep time in milliseconds. 28 | */ 29 | private static final long SLEEP_MILLIS = 5000; 30 | 31 | @Override 32 | public Boolean send(final Greeting greeting) { 33 | logger.info("> send"); 34 | 35 | Boolean success; 36 | 37 | // Simulate method execution time 38 | try { 39 | Thread.sleep(SLEEP_MILLIS); 40 | } catch (InterruptedException ie) { 41 | logger.info("- Thread interrupted.", ie); 42 | // Do nothing. 43 | } 44 | logger.info("Processing time was {} seconds.", SLEEP_MILLIS / 1000); 45 | 46 | success = Boolean.TRUE; 47 | 48 | logger.info("< send"); 49 | return success; 50 | } 51 | 52 | @Async 53 | @Override 54 | public void sendAsync(final Greeting greeting) { 55 | logger.info("> sendAsync"); 56 | 57 | send(greeting); 58 | 59 | logger.info("< sendAsync"); 60 | } 61 | 62 | @Async 63 | @Override 64 | public Future sendAsyncWithResult(final Greeting greeting) { 65 | logger.info("> sendAsyncWithResult"); 66 | 67 | final Boolean success = send(greeting); 68 | 69 | logger.info("< sendAsyncWithResult"); 70 | return new AsyncResult(success); 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/test/java/com/leanstacks/ws/web/api/DeleteGreetingDocTest.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.web.api; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation; 7 | import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | import org.springframework.test.web.servlet.MvcResult; 10 | import org.springframework.test.web.servlet.result.MockMvcResultMatchers; 11 | 12 | import com.leanstacks.ws.AbstractDocTest; 13 | import com.leanstacks.ws.RestControllerTest; 14 | 15 | /** 16 | *

17 | * Generate REST API documentation for the GreetingController. 18 | *

19 | *

20 | * These tests utilize Spring's REST Docs Framework to generate API documentation. There is a separate test class 21 | * responsible for unit testing functionality. 22 | *

23 | * 24 | * @author Matt Warman 25 | */ 26 | @RunWith(SpringRunner.class) 27 | @RestControllerTest 28 | public class DeleteGreetingDocTest extends AbstractDocTest { 29 | 30 | @Override 31 | public void doBeforeEachTest() { 32 | // perform test initialization 33 | } 34 | 35 | @Override 36 | public void doAfterEachTest() { 37 | // perform test cleanup 38 | } 39 | 40 | /** 41 | * Generate API documentation for DELETE /api/greetings/{id}. 42 | * 43 | * @throws Exception Thrown if documentation generation failure occurs. 44 | */ 45 | @Test 46 | public void documentDeleteGreeting() throws Exception { 47 | 48 | // Generate API Documentation 49 | final MvcResult result = this.mockMvc.perform(RestDocumentationRequestBuilders.delete("/api/greetings/{id}", 1)) 50 | .andExpect(MockMvcResultMatchers.status().isNoContent()) 51 | .andDo(MockMvcRestDocumentation.document("delete-greeting")).andReturn(); 52 | 53 | // Perform a simple, standard JUnit assertion to satisfy PMD rule 54 | Assert.assertEquals("failure - expected HTTP status 204", 204, result.getResponse().getStatus()); 55 | 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/main/resources/config/application.properties: -------------------------------------------------------------------------------- 1 | ## 2 | # The Base Application Configuration File 3 | ## 4 | 5 | ## 6 | # Profile Configuration 7 | # profiles: hsqldb, mysql, batch 8 | ## 9 | spring.profiles.active=hsqldb,batch 10 | 11 | ## 12 | # Web Server Configuration 13 | ## 14 | #server.port= 15 | 16 | ## 17 | # Cache Configuration 18 | ## 19 | spring.cache.cache-names=greetings 20 | spring.cache.caffeine.spec=maximumSize=250,expireAfterAccess=600s 21 | 22 | ## 23 | # Task Execution (Async) Configuration 24 | ## 25 | spring.task.execution.pool.core-size=8 26 | 27 | ## 28 | # Task Scheduling Configuration 29 | ## 30 | spring.task.scheduling.pool.size=2 31 | 32 | ## 33 | # Data Source Configuration 34 | ## 35 | 36 | # Hibernate 37 | spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl 38 | spring.jpa.properties.jadira.usertype.autoRegisterUserTypes=true 39 | 40 | # Liquibase 41 | spring.liquibase.change-log=classpath:/data/changelog/db.changelog-master.xml 42 | 43 | ## 44 | # Actuator Configuration 45 | ## 46 | management.endpoints.web.base-path=/actuators 47 | management.endpoints.web.exposure.include=* 48 | management.endpoints.web.exposure.exclude=shutdown 49 | 50 | management.endpoint.health.show-details=when-authorized 51 | management.endpoint.health.roles=SYSADMIN 52 | 53 | ## 54 | # Logging Configuration 55 | ## 56 | # Use a logging pattern easily parsed by aggregation tools. Comment to use standard Spring Boot logging pattern. 57 | logging.pattern.console=[%date{ISO8601}] [%clr(%-5level)] [${PID:-}] [%-15.15thread] [%-40.40logger{39}] [%m]%n 58 | logging.level.com.leanstacks.ws=DEBUG 59 | logging.level.org.springboot=INFO 60 | logging.level.org.springframework=INFO 61 | logging.level.org.springframework.security=INFO 62 | logging.level.org.springframework.restdocs=DEBUG 63 | # Uncomment the 2 hibernate appenders below to show SQL and params in logs 64 | logging.level.org.hibernate.SQL=DEBUG 65 | #logging.level.org.hibernate.type.descriptor.sql=TRACE 66 | 67 | ## 68 | # CORS Configuration 69 | ## 70 | leanstacks.cors.filter-registration-path=/** 71 | leanstacks.cors.allow-credentials=false 72 | leanstacks.cors.allowed-headers=accept,authorization,content-type 73 | leanstacks.cors.allowed-methods=GET,OPTIONS,POST,PUT,PATCH,DELETE 74 | leanstacks.cors.allowed-origins=* 75 | leanstacks.cors.exposed-headers= 76 | leanstacks.cors.max-age-seconds=3600 77 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /etc/pmd/ruleset.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | This is the LeanStacks Official PMD ruleset. 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/security/AccountUserDetailsService.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.security; 2 | 3 | import java.util.Optional; 4 | import java.util.Set; 5 | import java.util.stream.Collectors; 6 | 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.security.core.GrantedAuthority; 11 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 12 | import org.springframework.security.core.userdetails.User; 13 | import org.springframework.security.core.userdetails.UserDetails; 14 | import org.springframework.security.core.userdetails.UserDetailsService; 15 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 16 | import org.springframework.stereotype.Service; 17 | 18 | import com.leanstacks.ws.model.Account; 19 | import com.leanstacks.ws.model.Role; 20 | import com.leanstacks.ws.service.AccountService; 21 | 22 | /** 23 | * A Spring Security UserDetailsService implementation which creates UserDetails objects from the Account and Role 24 | * entities. 25 | * 26 | * @author Matt Warman 27 | */ 28 | @Service 29 | public class AccountUserDetailsService implements UserDetailsService { 30 | 31 | /** 32 | * The Logger for this Class. 33 | */ 34 | private static final Logger logger = LoggerFactory.getLogger(AccountUserDetailsService.class); 35 | 36 | /** 37 | * The AccountService business service. 38 | */ 39 | @Autowired 40 | private transient AccountService accountService; 41 | 42 | @Override 43 | public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { 44 | logger.info("> loadUserByUsername {}", username); 45 | 46 | final Optional accountOptional = accountService.findByUsername(username); 47 | final Account account = accountOptional 48 | .orElseThrow(() -> new UsernameNotFoundException("Invalid credentials.")); 49 | 50 | final Set roles = account.getRoles(); 51 | if (roles == null || roles.isEmpty()) { 52 | // No Roles assigned to Account... 53 | throw new UsernameNotFoundException("Invalid credentials."); 54 | } 55 | 56 | final Set authorities = roles.stream().map(role -> new SimpleGrantedAuthority(role.getCode())) 57 | .collect(Collectors.toSet()); 58 | 59 | final User userDetails = new User(account.getUsername(), account.getPassword(), account.isEnabled(), 60 | !account.isExpired(), !account.isCredentialsexpired(), !account.isLocked(), authorities); 61 | 62 | logger.info("< loadUserByUsername {}", username); 63 | return userDetails; 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/test/java/com/leanstacks/ws/util/BCryptPasswordEncoderUtil.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.util; 2 | 3 | import java.io.IOException; 4 | import java.io.OutputStreamWriter; 5 | import java.io.Writer; 6 | 7 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 8 | 9 | /** 10 | *

11 | * The BCryptPasswordEncoderUtil class assists engineers during application construction. It is not intended for use in 12 | * a 'live' application. 13 | *

14 | *

15 | * The class uses a BCryptPasswordEncoder to encrypt clear text values using it's native hashing algorithm. This utility 16 | * may be used to create encrypted password values in a database initialization script used for unit testing or local 17 | * machine development. 18 | *

19 | * 20 | * @author Matt Warman 21 | * 22 | */ 23 | public class BCryptPasswordEncoderUtil { 24 | 25 | /** 26 | * The format for encoder messages. 27 | */ 28 | private static final String ENCODED_FORMAT = "Argument: %s \tEncoded: %s \n"; 29 | 30 | /** 31 | * A Writer for printing messages to the console. 32 | */ 33 | private transient Writer writer; 34 | 35 | /** 36 | * Uses a BCryptPasswordEncoder to hash the clear text value. 37 | * 38 | * @param clearText A String of clear text to be encrypted. 39 | * @return The encrypted (hashed) value. 40 | */ 41 | public String encode(final String clearText) { 42 | final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); 43 | return encoder.encode(clearText); 44 | } 45 | 46 | /** 47 | * Facilitates gathering user input and invoking the class behavior. 48 | * 49 | * @param args An array of command line input values. (not used) 50 | * @throws IOException Thrown if performing IO operations fails. 51 | */ 52 | public static void main(final String... args) throws IOException { 53 | 54 | final BCryptPasswordEncoderUtil encoderUtil = new BCryptPasswordEncoderUtil(); 55 | 56 | for (final String arg : args) { 57 | final String encodedText = encoderUtil.encode(arg); 58 | final String message = String.format(ENCODED_FORMAT, arg, encodedText); 59 | encoderUtil.write(message); 60 | } 61 | 62 | encoderUtil.close(); 63 | 64 | } 65 | 66 | /** 67 | * Writes a message to the console. 68 | * 69 | * @param str A String message value. 70 | * @throws IOException Thrown if writing output fails. 71 | */ 72 | private void write(final String str) throws IOException { 73 | 74 | if (writer == null) { 75 | writer = new OutputStreamWriter(System.out); 76 | } 77 | writer.write(str); 78 | 79 | } 80 | 81 | /** 82 | * Closes all system resources and prepares for application termination. 83 | * 84 | * @throws IOException Thrown if closing the output stream fails. 85 | */ 86 | private void close() throws IOException { 87 | 88 | if (writer != null) { 89 | writer.close(); 90 | } 91 | 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /src/test/java/com/leanstacks/ws/AbstractDocTest.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws; 2 | 3 | import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; 4 | import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; 5 | 6 | import org.junit.After; 7 | import org.junit.Before; 8 | import org.junit.Rule; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.restdocs.JUnitRestDocumentation; 11 | import org.springframework.test.web.servlet.MockMvc; 12 | import org.springframework.test.web.servlet.setup.MockMvcBuilders; 13 | import org.springframework.web.context.WebApplicationContext; 14 | 15 | import com.leanstacks.ws.util.RequestContext; 16 | 17 | /** 18 | * The AbstractDocTest class is the parent of all JUnit test classes which create Spring REST Docs. This class 19 | * configures the test ApplicationContext and test runner environment to facilitate the creation of API documentation 20 | * via Spring REST Docs. 21 | * 22 | * @author Matt Warman 23 | */ 24 | public abstract class AbstractDocTest { 25 | 26 | /** 27 | * A MockMvc instance configured with Spring REST Docs configuration. 28 | */ 29 | protected transient MockMvc mockMvc; 30 | 31 | /** 32 | * A WebApplicationContext instance. 33 | */ 34 | @Autowired 35 | private transient WebApplicationContext context; 36 | 37 | /** 38 | * A JUnit 4.x Rule for Spring REST Documentation generation. Note that the snippet output directory is only 39 | * provided because this project contains both 'build.gradle' and 'pom.xml' files. Spring REST Docs uses those files 40 | * to auto-detect the build system and automatically sets certain configuration values which cannot be overridden. 41 | */ 42 | @Rule 43 | public transient JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("build/generated-snippets"); 44 | 45 | /** 46 | * Perform set up activities before each unit test. Invoked by the JUnit framework. 47 | */ 48 | @Before 49 | public void before() { 50 | RequestContext.setUsername(AbstractTest.USERNAME); 51 | this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) 52 | .apply(documentationConfiguration(this.restDocumentation).uris().withScheme("https") 53 | .withHost("api.leanstacks.net").withPort(443).and().operationPreprocessors() 54 | .withRequestDefaults(prettyPrint()).withResponseDefaults(prettyPrint())) 55 | .build(); 56 | doBeforeEachTest(); 57 | } 58 | 59 | /** 60 | * Perform initialization tasks before the execution of each test method. 61 | */ 62 | public abstract void doBeforeEachTest(); 63 | 64 | /** 65 | * Perform clean up activities after each unit test. Invoked by the JUnit framework. 66 | */ 67 | @After 68 | public void after() { 69 | doAfterEachTest(); 70 | } 71 | 72 | /** 73 | * Perform clean up tasks after the execution of each test method. 74 | */ 75 | public abstract void doAfterEachTest(); 76 | 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/model/ReferenceEntity.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.model; 2 | 3 | import java.io.Serializable; 4 | import java.time.Instant; 5 | 6 | import javax.persistence.Id; 7 | import javax.persistence.MappedSuperclass; 8 | import javax.validation.constraints.NotNull; 9 | 10 | /** 11 | * The parent class for all reference entities (i.e. reference data as opposed to transactional data). 12 | * 13 | * @see com.leanstacks.ws.model.TransactionalEntity 14 | * 15 | * @author Matt Warman 16 | */ 17 | @MappedSuperclass 18 | public class ReferenceEntity implements Serializable { 19 | 20 | /** 21 | * The default serial version UID. 22 | */ 23 | private static final long serialVersionUID = 1L; 24 | 25 | /** 26 | * The primary key identifier. 27 | */ 28 | @Id 29 | private Long id; 30 | 31 | /** 32 | * The unique code value, sometimes used for external reference. 33 | */ 34 | @NotNull 35 | private String code; 36 | 37 | /** 38 | * A brief description of the entity. 39 | */ 40 | @NotNull 41 | private String label; 42 | 43 | /** 44 | * The ordinal value facilitates sorting the entities. 45 | */ 46 | @NotNull 47 | private Integer ordinal; 48 | 49 | /** 50 | * The timestamp at which the entity's values may be applied or used by the system. 51 | */ 52 | @NotNull 53 | private Instant effectiveAt; 54 | 55 | /** 56 | * The timestamp at which the entity's values cease to be used by the system. If null the entity is not 57 | * expired. 58 | */ 59 | private Instant expiresAt; 60 | 61 | /** 62 | * The timestamp when this entity instance was created. 63 | */ 64 | @NotNull 65 | private Instant createdAt; 66 | 67 | public Long getId() { 68 | return id; 69 | } 70 | 71 | public void setId(final Long id) { 72 | this.id = id; 73 | } 74 | 75 | public String getCode() { 76 | return code; 77 | } 78 | 79 | public void setCode(final String code) { 80 | this.code = code; 81 | } 82 | 83 | public String getLabel() { 84 | return label; 85 | } 86 | 87 | public void setLabel(final String label) { 88 | this.label = label; 89 | } 90 | 91 | public Integer getOrdinal() { 92 | return ordinal; 93 | } 94 | 95 | public void setOrdinal(final Integer ordinal) { 96 | this.ordinal = ordinal; 97 | } 98 | 99 | public Instant getEffectiveAt() { 100 | return effectiveAt; 101 | } 102 | 103 | public void setEffectiveAt(final Instant effectiveAt) { 104 | this.effectiveAt = effectiveAt; 105 | } 106 | 107 | public Instant getExpiresAt() { 108 | return expiresAt; 109 | } 110 | 111 | public void setExpiresAt(final Instant expiresAt) { 112 | this.expiresAt = expiresAt; 113 | } 114 | 115 | public Instant getCreatedAt() { 116 | return createdAt; 117 | } 118 | 119 | public void setCreatedAt(final Instant createdAt) { 120 | this.createdAt = createdAt; 121 | } 122 | 123 | } 124 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/security/AccountAuthenticationProvider.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.security; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.security.authentication.BadCredentialsException; 7 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 8 | import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider; 9 | import org.springframework.security.core.AuthenticationException; 10 | import org.springframework.security.core.userdetails.UserDetails; 11 | import org.springframework.security.crypto.password.PasswordEncoder; 12 | import org.springframework.stereotype.Component; 13 | 14 | import com.leanstacks.ws.util.RequestContext; 15 | 16 | /** 17 | *

18 | * A Spring Security AuthenticationProvider which extends AbstractUserDetailsAuthenticationProvider. This 19 | * class uses the AccountUserDetailsService to retrieve a UserDetails instance. 20 | *

21 | *

22 | * A PasswordEncoder compares the supplied authentication credentials to those in the UserDetails. 23 | *

24 | * 25 | * @author Matt Warman 26 | */ 27 | @Component 28 | public class AccountAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider { 29 | 30 | /** 31 | * The Logger for this Class. 32 | */ 33 | private static final Logger logger = LoggerFactory.getLogger(AccountAuthenticationProvider.class); 34 | 35 | /** 36 | * A Spring Security UserDetailsService implementation based upon the Account entity model. 37 | */ 38 | @Autowired 39 | private transient AccountUserDetailsService userDetailsService; 40 | 41 | /** 42 | * A PasswordEncoder instance to hash clear test password values. 43 | */ 44 | @Autowired 45 | private transient PasswordEncoder passwordEncoder; 46 | 47 | @Override 48 | protected void additionalAuthenticationChecks(final UserDetails userDetails, 49 | final UsernamePasswordAuthenticationToken token) throws AuthenticationException { 50 | logger.info("> additionalAuthenticationChecks"); 51 | 52 | if (token.getCredentials() == null || userDetails.getPassword() == null) { 53 | logger.info("< additionalAuthenticationChecks"); 54 | throw new BadCredentialsException("Credentials may not be null."); 55 | } 56 | 57 | if (!passwordEncoder.matches((String) token.getCredentials(), userDetails.getPassword())) { 58 | logger.info("< additionalAuthenticationChecks"); 59 | throw new BadCredentialsException("Invalid credentials."); 60 | } 61 | 62 | RequestContext.setUsername(userDetails.getUsername()); 63 | 64 | logger.info("< additionalAuthenticationChecks"); 65 | } 66 | 67 | @Override 68 | protected UserDetails retrieveUser(final String username, final UsernamePasswordAuthenticationToken token) 69 | throws AuthenticationException { 70 | logger.info("> retrieveUser"); 71 | 72 | final UserDetails userDetails = userDetailsService.loadUserByUsername(username); 73 | 74 | logger.info("< retrieveUser"); 75 | return userDetails; 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /src/test/java/com/leanstacks/ws/web/api/GetGreetingsDocTest.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.web.api; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.http.MediaType; 7 | import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation; 8 | import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders; 9 | import org.springframework.restdocs.payload.PayloadDocumentation; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | import org.springframework.test.web.servlet.MvcResult; 12 | import org.springframework.test.web.servlet.result.MockMvcResultMatchers; 13 | 14 | import com.leanstacks.ws.AbstractDocTest; 15 | import com.leanstacks.ws.RestControllerTest; 16 | 17 | /** 18 | *

19 | * Generate REST API documentation for the GreetingController. 20 | *

21 | *

22 | * These tests utilize Spring's REST Docs Framework to generate API documentation. There is a separate test class 23 | * responsible for unit testing functionality. 24 | *

25 | * 26 | * @author Matt Warman 27 | */ 28 | @RunWith(SpringRunner.class) 29 | @RestControllerTest 30 | public class GetGreetingsDocTest extends AbstractDocTest { 31 | 32 | @Override 33 | public void doBeforeEachTest() { 34 | // perform test initialization 35 | } 36 | 37 | @Override 38 | public void doAfterEachTest() { 39 | // perform test cleanup 40 | } 41 | 42 | /** 43 | * Generate API documentation for GET /api/greetings. 44 | * 45 | * @throws Exception Thrown if documentation generation failure occurs. 46 | */ 47 | @Test 48 | public void documentGetGreetings() throws Exception { 49 | 50 | // Generate API Documentation 51 | final MvcResult result = this.mockMvc 52 | .perform(RestDocumentationRequestBuilders.get("/api/greetings").accept(MediaType.APPLICATION_JSON)) 53 | .andExpect(MockMvcResultMatchers.status().isOk()) 54 | .andDo(MockMvcRestDocumentation.document("get-greetings", 55 | PayloadDocumentation.relaxedResponseFields( 56 | PayloadDocumentation.fieldWithPath("[].id").description( 57 | "The identifier. Used to reference specific greetings in API requests."), 58 | PayloadDocumentation.fieldWithPath("[].referenceId") 59 | .description("The supplementary identifier."), 60 | PayloadDocumentation.fieldWithPath("[].text").description("The text."), 61 | PayloadDocumentation.fieldWithPath("[].version").description("The entity version."), 62 | PayloadDocumentation.fieldWithPath("[].createdBy").description("The entity creator."), 63 | PayloadDocumentation.fieldWithPath("[].createdAt") 64 | .description("The creation timestamp."), 65 | PayloadDocumentation.fieldWithPath("[].updatedBy").description("The last modifier."), 66 | PayloadDocumentation.fieldWithPath("[].updatedAt") 67 | .description("The last modification timestamp.")))) 68 | .andReturn(); 69 | 70 | // Perform a simple, standard JUnit assertion to satisfy PMD rule 71 | Assert.assertEquals("failure - expected HTTP status 200", 200, result.getResponse().getStatus()); 72 | 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 4.0.0 5 | 6 | com.leanstacks 7 | skeleton-ws-spring-boot 8 | 2.3.0 9 | Spring Boot Starter Project 10 | Starter application stack for RESTful web services using Spring Boot. 11 | 12 | 13 | org.springframework.boot 14 | spring-boot-starter-parent 15 | 2.1.1.RELEASE 16 | 17 | 18 | 19 | UTF-8 20 | 11 21 | 22 | 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-web 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-security 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-actuator 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-data-jpa 39 | 40 | 41 | 42 | org.hsqldb 43 | hsqldb 44 | runtime 45 | 46 | 47 | mysql 48 | mysql-connector-java 49 | runtime 50 | 51 | 52 | org.liquibase 53 | liquibase-core 54 | 55 | 56 | 57 | 58 | org.springframework 59 | spring-context-support 60 | 61 | 62 | com.github.ben-manes.caffeine 63 | caffeine 64 | 65 | 66 | 67 | 68 | 69 | 70 | org.springframework.boot 71 | spring-boot-starter-test 72 | test 73 | 74 | 75 | org.springframework.security 76 | spring-security-test 77 | test 78 | 79 | 80 | com.google.guava 81 | guava 82 | 27.0.1-jre 83 | test 84 | 85 | 86 | 87 | 88 | org.springframework.restdocs 89 | spring-restdocs-mockmvc 90 | 91 | 92 | 93 | 94 | 95 | 96 | org.springframework.boot 97 | spring-boot-maven-plugin 98 | 99 | true 100 | 101 | 102 | 103 | 104 | build-info 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/web/api/ExceptionDetailBuilder.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.web.api; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | 5 | import org.springframework.http.HttpStatus; 6 | import org.springframework.web.context.request.ServletWebRequest; 7 | import org.springframework.web.context.request.WebRequest; 8 | 9 | /** 10 | * A builder for ExceptionDetail objects. This class facilitates the construction and population of ExceptionDetail 11 | * objects from an Exception and from REST service request data. 12 | * 13 | * @author Matt Warman 14 | */ 15 | public class ExceptionDetailBuilder { 16 | 17 | /** 18 | * The ExceptionDetail object under construction. 19 | */ 20 | private final transient ExceptionDetail exceptionDetail; 21 | 22 | /** 23 | * Constructs a new ExceptionDetailBuilder. 24 | */ 25 | public ExceptionDetailBuilder() { 26 | exceptionDetail = new ExceptionDetail(); 27 | } 28 | 29 | /** 30 | * Invoke this method to obtain the ExceptionDetail object after using builder methods to populate it. 31 | * 32 | * @return An ExceptionDetail object. 33 | */ 34 | public ExceptionDetail build() { 35 | return exceptionDetail; 36 | } 37 | 38 | /** 39 | * Populate the ExceptionDetail attributes with information from the Exception. Returns this ExceptionDetailBuilder 40 | * to chain method invocations. 41 | * 42 | * @param ex An Exception. 43 | * @return This ExceptionDetailBuilder object. 44 | */ 45 | public ExceptionDetailBuilder exception(final Exception ex) { 46 | if (ex != null) { 47 | exceptionDetail.setExceptionClass(ex.getClass().getName()); 48 | exceptionDetail.setExceptionMessage(ex.getMessage()); 49 | } 50 | return this; 51 | } 52 | 53 | /** 54 | * Populate the ExceptionDetail attributes with information from a HttpStatus. Returns this ExceptionDetailBuilder 55 | * to chain method invocations. 56 | * 57 | * @param status A HttpStatus. 58 | * @return This ExceptionDetailBuilder object. 59 | */ 60 | public ExceptionDetailBuilder httpStatus(final HttpStatus status) { 61 | if (status != null) { 62 | exceptionDetail.setStatus(status.value()); 63 | exceptionDetail.setStatusText(status.getReasonPhrase()); 64 | } 65 | return this; 66 | } 67 | 68 | /** 69 | * Populate the ExceptionDetail attributes with information from a WebRequest. Typically use either a WebRequest or 70 | * HttpServletRequest, but not both. Returns this ExceptionDetailBuilder to chain method invocations. 71 | * 72 | * @param request A WebRequest. 73 | * @return This ExceptionDetailBuilder object. 74 | */ 75 | public ExceptionDetailBuilder webRequest(final WebRequest request) { 76 | if (request instanceof ServletWebRequest) { 77 | final HttpServletRequest httpRequest = ((ServletWebRequest) request) 78 | .getNativeRequest(HttpServletRequest.class); 79 | return httpServletRequest(httpRequest); 80 | } 81 | return this; 82 | } 83 | 84 | /** 85 | * Populate the ExceptionDetail attributes with information from a HttpServletRequest. Typically use either a 86 | * WebRequest or HttpServletRequest, but not both. Returns this ExceptionDetailBuilder to chain method invocations. 87 | * 88 | * @param request A HttpServletRequest. 89 | * @return This ExceptionDetailBuilder object. 90 | */ 91 | public ExceptionDetailBuilder httpServletRequest(final HttpServletRequest request) { 92 | if (request != null) { 93 | exceptionDetail.setMethod(request.getMethod()); 94 | exceptionDetail.setPath(request.getServletPath()); 95 | } 96 | return this; 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /src/test/java/com/leanstacks/ws/web/api/GetGreetingDocTest.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.web.api; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.http.MediaType; 7 | import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation; 8 | import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders; 9 | import org.springframework.restdocs.payload.JsonFieldType; 10 | import org.springframework.restdocs.payload.PayloadDocumentation; 11 | import org.springframework.restdocs.request.RequestDocumentation; 12 | import org.springframework.test.context.junit4.SpringRunner; 13 | import org.springframework.test.web.servlet.MvcResult; 14 | import org.springframework.test.web.servlet.result.MockMvcResultMatchers; 15 | 16 | import com.leanstacks.ws.AbstractDocTest; 17 | import com.leanstacks.ws.RestControllerTest; 18 | 19 | /** 20 | *

21 | * Generate REST API documentation for the GreetingController. 22 | *

23 | *

24 | * These tests utilize Spring's REST Docs Framework to generate API documentation. There is a separate test class 25 | * responsible for unit testing functionality. 26 | *

27 | * 28 | * @author Matt Warman 29 | */ 30 | @RunWith(SpringRunner.class) 31 | @RestControllerTest 32 | public class GetGreetingDocTest extends AbstractDocTest { 33 | 34 | @Override 35 | public void doBeforeEachTest() { 36 | // perform test initialization 37 | } 38 | 39 | @Override 40 | public void doAfterEachTest() { 41 | // perform test cleanup 42 | } 43 | 44 | /** 45 | * Generate API documentation for GET /api/greetings/{id}. 46 | * 47 | * @throws Exception Thrown if documentation generation failure occurs. 48 | */ 49 | @Test 50 | public void documentGetGreeting() throws Exception { 51 | 52 | // Generate API Documentation 53 | final MvcResult result = this.mockMvc 54 | .perform(RestDocumentationRequestBuilders 55 | .get("/api/greetings/{id}", "0").accept(MediaType.APPLICATION_JSON)) 56 | .andExpect(MockMvcResultMatchers.status().isOk()) 57 | .andDo(MockMvcRestDocumentation.document("get-greeting", 58 | RequestDocumentation.pathParameters( 59 | RequestDocumentation.parameterWithName("id").description("The greeting identifier.")), 60 | PayloadDocumentation.relaxedResponseFields( 61 | PayloadDocumentation.fieldWithPath("id") 62 | .description( 63 | "The identifier. Used to reference specific greetings in API requests.") 64 | .type(JsonFieldType.NUMBER), 65 | PayloadDocumentation.fieldWithPath("referenceId") 66 | .description("The supplementary identifier.").type(JsonFieldType.STRING), 67 | PayloadDocumentation.fieldWithPath("text").description("The text.") 68 | .type(JsonFieldType.STRING), 69 | PayloadDocumentation.fieldWithPath("version").description("The entity version.") 70 | .type(JsonFieldType.NUMBER), 71 | PayloadDocumentation.fieldWithPath("createdBy").description("The entity creator.") 72 | .type(JsonFieldType.STRING), 73 | PayloadDocumentation.fieldWithPath("createdAt").description("The creation timestamp.") 74 | .type(JsonFieldType.STRING), 75 | PayloadDocumentation.fieldWithPath("updatedBy").description("The last modifier.") 76 | .type(JsonFieldType.STRING).optional(), 77 | PayloadDocumentation.fieldWithPath("updatedAt") 78 | .description("The last modification timestamp.").type(JsonFieldType.STRING) 79 | .optional()))) 80 | .andReturn(); 81 | 82 | // Perform a simple, standard JUnit assertion to satisfy PMD rule 83 | Assert.assertEquals("failure - expected HTTP status 200", 200, result.getResponse().getStatus()); 84 | 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/model/Account.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.model; 2 | 3 | import java.util.Set; 4 | 5 | import javax.persistence.CascadeType; 6 | import javax.persistence.Entity; 7 | import javax.persistence.FetchType; 8 | import javax.persistence.JoinColumn; 9 | import javax.persistence.JoinTable; 10 | import javax.persistence.ManyToMany; 11 | import javax.validation.constraints.NotNull; 12 | 13 | /** 14 | * The Account class is an entity model object. An Account describes the security credentials and authentication flags 15 | * that permit access to application functionality. 16 | * 17 | * @author Matt Warman 18 | */ 19 | @Entity 20 | public class Account extends TransactionalEntity { 21 | 22 | private static final long serialVersionUID = 1L; 23 | 24 | /** 25 | * Login username. 26 | */ 27 | @NotNull 28 | private String username; 29 | 30 | /** 31 | * Login password. 32 | */ 33 | @NotNull 34 | private String password; 35 | 36 | /** 37 | * Account enabled status indicator. 38 | */ 39 | @NotNull 40 | private boolean enabled = true; 41 | 42 | /** 43 | * Credential status indicator. 44 | */ 45 | @NotNull 46 | private boolean credentialsexpired; 47 | 48 | /** 49 | * Account expired status indicator. 50 | */ 51 | @NotNull 52 | private boolean expired; 53 | 54 | /** 55 | * Account locked indicator. 56 | */ 57 | @NotNull 58 | private boolean locked; 59 | 60 | /** 61 | * Authorization information. 62 | */ 63 | @ManyToMany(fetch = FetchType.EAGER, 64 | cascade = CascadeType.ALL) 65 | @JoinTable(name = "AccountRole", 66 | joinColumns = @JoinColumn(name = "accountId", 67 | referencedColumnName = "id"), 68 | inverseJoinColumns = @JoinColumn(name = "roleId", 69 | referencedColumnName = "id")) 70 | private Set roles; 71 | 72 | /** 73 | * Create a new Account object. 74 | */ 75 | public Account() { 76 | super(); 77 | } 78 | 79 | /** 80 | * Create a new Account object with the supplied username and password values. 81 | * 82 | * @param username A String username value. 83 | * @param password A String clear text password value. 84 | */ 85 | public Account(final String username, final String password) { 86 | super(); 87 | this.username = username; 88 | this.password = password; 89 | } 90 | 91 | /** 92 | * Create a new Account object with the supplied username, password, and Set of Role objects. 93 | * 94 | * @param username A String username value. 95 | * @param password A String clear text password value. 96 | * @param roles A Set of Role objects. 97 | */ 98 | public Account(final String username, final String password, final Set roles) { 99 | super(); 100 | this.username = username; 101 | this.password = password; 102 | this.roles = roles; 103 | } 104 | 105 | public String getUsername() { 106 | return username; 107 | } 108 | 109 | public void setUsername(final String username) { 110 | this.username = username; 111 | } 112 | 113 | public String getPassword() { 114 | return password; 115 | } 116 | 117 | public void setPassword(final String password) { 118 | this.password = password; 119 | } 120 | 121 | public boolean isEnabled() { 122 | return enabled; 123 | } 124 | 125 | public void setEnabled(final boolean enabled) { 126 | this.enabled = enabled; 127 | } 128 | 129 | public boolean isCredentialsexpired() { 130 | return credentialsexpired; 131 | } 132 | 133 | public void setCredentialsexpired(final boolean credentialsexpired) { 134 | this.credentialsexpired = credentialsexpired; 135 | } 136 | 137 | public boolean isExpired() { 138 | return expired; 139 | } 140 | 141 | public void setExpired(final boolean expired) { 142 | this.expired = expired; 143 | } 144 | 145 | public boolean isLocked() { 146 | return locked; 147 | } 148 | 149 | public void setLocked(final boolean locked) { 150 | this.locked = locked; 151 | } 152 | 153 | public Set getRoles() { 154 | return roles; 155 | } 156 | 157 | public void setRoles(final Set roles) { 158 | this.roles = roles; 159 | } 160 | 161 | } 162 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/web/api/ExceptionDetail.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.web.api; 2 | 3 | import java.time.Instant; 4 | 5 | /** 6 | * The ExceptionDetail class models information about a web service request which results in an Exception. This 7 | * information may be returned to the client. 8 | * 9 | * @author Matt Warman 10 | * 11 | */ 12 | public class ExceptionDetail { 13 | 14 | /** 15 | * The time the exception occurred. 16 | */ 17 | private Instant timestamp; 18 | /** 19 | * The HTTP method (e.g. GET, POST, etc.) 20 | */ 21 | private String method = ""; 22 | /** 23 | * The web service context path. 24 | */ 25 | private String path = ""; 26 | /** 27 | * The HTTP status code of the response. 28 | */ 29 | private int status; 30 | /** 31 | * The text description of the HTTP status code of the response. 32 | */ 33 | private String statusText = ""; 34 | /** 35 | * The fully qualified Class name of the Exception. 36 | */ 37 | private String exceptionClass = ""; 38 | /** 39 | * The value of the Exception message attribute. 40 | */ 41 | private String exceptionMessage = ""; 42 | 43 | /** 44 | * Construct an ExceptionDetail. 45 | */ 46 | public ExceptionDetail() { 47 | this.timestamp = Instant.now(); 48 | } 49 | 50 | /** 51 | * Returns the timestamp attribute value. 52 | * 53 | * @return An Instant. 54 | */ 55 | public Instant getTimestamp() { 56 | return timestamp; 57 | } 58 | 59 | /** 60 | * Sets the timestamp attribute value. 61 | * 62 | * @param timestamp An Instant. 63 | */ 64 | public void setTimestamp(final Instant timestamp) { 65 | this.timestamp = timestamp; 66 | } 67 | 68 | /** 69 | * Returns the method attribute value. 70 | * 71 | * @return A String. 72 | */ 73 | public String getMethod() { 74 | return method; 75 | } 76 | 77 | /** 78 | * Sets the method attribute value. 79 | * 80 | * @param method A String. 81 | */ 82 | public void setMethod(final String method) { 83 | this.method = method; 84 | } 85 | 86 | /** 87 | * Returns the path attribute value. 88 | * 89 | * @return A String. 90 | */ 91 | public String getPath() { 92 | return path; 93 | } 94 | 95 | /** 96 | * Sets the path attribute value. 97 | * 98 | * @param path A String. 99 | */ 100 | public void setPath(final String path) { 101 | this.path = path; 102 | } 103 | 104 | /** 105 | * Returns the status attribute value. 106 | * 107 | * @return An int. 108 | */ 109 | public int getStatus() { 110 | return status; 111 | } 112 | 113 | /** 114 | * Sets the status attribute value. 115 | * 116 | * @param status An int. 117 | */ 118 | public void setStatus(final int status) { 119 | this.status = status; 120 | } 121 | 122 | /** 123 | * Returns the statusText attribute value. 124 | * 125 | * @return A String. 126 | */ 127 | public String getStatusText() { 128 | return statusText; 129 | } 130 | 131 | /** 132 | * Sets the statusText attribute value. 133 | * 134 | * @param statusText A String. 135 | */ 136 | public void setStatusText(final String statusText) { 137 | this.statusText = statusText; 138 | } 139 | 140 | /** 141 | * Returns the exceptionClass attribute value. 142 | * 143 | * @return A String. 144 | */ 145 | public String getExceptionClass() { 146 | return exceptionClass; 147 | } 148 | 149 | /** 150 | * Sets the exceptionClass attribute value. 151 | * 152 | * @param exceptionClass A String. 153 | */ 154 | public void setExceptionClass(final String exceptionClass) { 155 | this.exceptionClass = exceptionClass; 156 | } 157 | 158 | /** 159 | * Returns the exceptionMessage attribute value. 160 | * 161 | * @return A String. 162 | */ 163 | public String getExceptionMessage() { 164 | return exceptionMessage; 165 | } 166 | 167 | /** 168 | * Sets the exceptionMessage attribute value. 169 | * 170 | * @param exceptionMessage A String. 171 | */ 172 | public void setExceptionMessage(final String exceptionMessage) { 173 | this.exceptionMessage = exceptionMessage; 174 | } 175 | 176 | } 177 | -------------------------------------------------------------------------------- /src/test/java/com/leanstacks/ws/web/api/CreateGreetingDocTest.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.web.api; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.http.MediaType; 7 | import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation; 8 | import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders; 9 | import org.springframework.restdocs.payload.JsonFieldType; 10 | import org.springframework.restdocs.payload.PayloadDocumentation; 11 | import org.springframework.test.context.junit4.SpringRunner; 12 | import org.springframework.test.web.servlet.MvcResult; 13 | import org.springframework.test.web.servlet.result.MockMvcResultMatchers; 14 | 15 | import com.leanstacks.ws.AbstractDocTest; 16 | import com.leanstacks.ws.RestControllerTest; 17 | 18 | /** 19 | *

20 | * Generate REST API documentation for the GreetingController. 21 | *

22 | *

23 | * These tests utilize Spring's REST Docs Framework to generate API documentation. There is a separate test class 24 | * responsible for unit testing functionality. 25 | *

26 | * 27 | * @author Matt Warman 28 | */ 29 | @RunWith(SpringRunner.class) 30 | @RestControllerTest 31 | public class CreateGreetingDocTest extends AbstractDocTest { 32 | 33 | /** 34 | * The HTTP request body content. 35 | */ 36 | private static final String REQUEST_BODY = "{ \"text\": \"Bonjour le monde!\" }"; 37 | 38 | @Override 39 | public void doBeforeEachTest() { 40 | // perform test initialization 41 | } 42 | 43 | @Override 44 | public void doAfterEachTest() { 45 | // perform test cleanup 46 | } 47 | 48 | /** 49 | * Generate API documentation for POST /api/greetings. 50 | * 51 | * @throws Exception Thrown if documentation generation failure occurs. 52 | */ 53 | @Test 54 | public void documentCreateGreeting() throws Exception { 55 | 56 | // Generate API Documentation 57 | final MvcResult result = this.mockMvc 58 | .perform(RestDocumentationRequestBuilders.post("/api/greetings").contentType(MediaType.APPLICATION_JSON) 59 | .accept(MediaType.APPLICATION_JSON).content(REQUEST_BODY)) 60 | .andExpect(MockMvcResultMatchers.status().isCreated()) 61 | .andDo(MockMvcRestDocumentation.document("create-greeting", 62 | PayloadDocumentation.relaxedRequestFields(PayloadDocumentation.fieldWithPath("text") 63 | .description("The text.").type(JsonFieldType.STRING)), 64 | PayloadDocumentation.relaxedResponseFields( 65 | PayloadDocumentation 66 | .fieldWithPath("id") 67 | .description( 68 | "The identifier. Used to reference specific greetings in API requests.") 69 | .type(JsonFieldType.NUMBER), 70 | PayloadDocumentation.fieldWithPath("referenceId") 71 | .description("The supplementary identifier.").type(JsonFieldType.STRING), 72 | PayloadDocumentation.fieldWithPath("text").description("The text.") 73 | .type(JsonFieldType.STRING), 74 | PayloadDocumentation.fieldWithPath("version").description("The entity version.") 75 | .type(JsonFieldType.NUMBER), 76 | PayloadDocumentation.fieldWithPath("createdBy").description("The entity creator.") 77 | .type(JsonFieldType.STRING), 78 | PayloadDocumentation.fieldWithPath("createdAt").description("The creation timestamp.") 79 | .type(JsonFieldType.STRING), 80 | PayloadDocumentation.fieldWithPath("updatedBy").description("The last modifier.") 81 | .type(JsonFieldType.STRING).optional(), 82 | PayloadDocumentation.fieldWithPath("updatedAt") 83 | .description("The last modification timestamp.").type(JsonFieldType.STRING) 84 | .optional()))) 85 | .andReturn(); 86 | 87 | // Perform a simple, standard JUnit assertion to satisfy PMD rule 88 | Assert.assertEquals("failure - expected HTTP status 201", 201, result.getResponse().getStatus()); 89 | 90 | } 91 | 92 | } 93 | -------------------------------------------------------------------------------- /src/test/java/com/leanstacks/ws/web/api/SendGreetingDocTest.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.web.api; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.http.MediaType; 7 | import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation; 8 | import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders; 9 | import org.springframework.restdocs.payload.JsonFieldType; 10 | import org.springframework.restdocs.payload.PayloadDocumentation; 11 | import org.springframework.restdocs.request.RequestDocumentation; 12 | import org.springframework.test.context.junit4.SpringRunner; 13 | import org.springframework.test.web.servlet.MvcResult; 14 | import org.springframework.test.web.servlet.result.MockMvcResultMatchers; 15 | 16 | import com.leanstacks.ws.AbstractDocTest; 17 | import com.leanstacks.ws.RestControllerTest; 18 | 19 | /** 20 | *

21 | * Generate REST API documentation for the GreetingController. 22 | *

23 | *

24 | * These tests utilize Spring's REST Docs Framework to generate API documentation. There is a separate test class 25 | * responsible for unit testing functionality. 26 | *

27 | * 28 | * @author Matt Warman 29 | */ 30 | @RunWith(SpringRunner.class) 31 | @RestControllerTest 32 | public class SendGreetingDocTest extends AbstractDocTest { 33 | 34 | @Override 35 | public void doBeforeEachTest() { 36 | // perform test initialization 37 | } 38 | 39 | @Override 40 | public void doAfterEachTest() { 41 | // perform test cleanup 42 | } 43 | 44 | /** 45 | * Generate API documentation for POST /api/greetings/{id}/send. 46 | * 47 | * @throws Exception Thrown if documentation generation failure occurs. 48 | */ 49 | @Test 50 | public void documentSendGreeting() throws Exception { 51 | 52 | // Generate API Documentation 53 | final MvcResult result = this.mockMvc 54 | .perform(RestDocumentationRequestBuilders 55 | .post("/api/greetings/{id}/send?wait=true", 1).accept(MediaType.APPLICATION_JSON)) 56 | .andExpect(MockMvcResultMatchers.status().isOk()) 57 | .andDo(MockMvcRestDocumentation.document("send-greeting", 58 | RequestDocumentation.pathParameters( 59 | RequestDocumentation.parameterWithName("id").description("The greeting identifier.")), 60 | RequestDocumentation.requestParameters(RequestDocumentation.parameterWithName("wait") 61 | .description("Optional. Boolean. Wait for email to be sent.").optional()), 62 | PayloadDocumentation.relaxedResponseFields( 63 | PayloadDocumentation 64 | .fieldWithPath("id") 65 | .description( 66 | "The identifier. Used to reference specific greetings in API requests.") 67 | .type(JsonFieldType.NUMBER), 68 | PayloadDocumentation.fieldWithPath("referenceId") 69 | .description("The supplementary identifier.").type(JsonFieldType.STRING), 70 | PayloadDocumentation.fieldWithPath("text").description("The text.") 71 | .type(JsonFieldType.STRING), 72 | PayloadDocumentation.fieldWithPath("version").description("The entity version.") 73 | .type(JsonFieldType.NUMBER), 74 | PayloadDocumentation.fieldWithPath("createdBy").description("The entity creator.") 75 | .type(JsonFieldType.STRING), 76 | PayloadDocumentation.fieldWithPath("createdAt").description("The creation timestamp.") 77 | .type(JsonFieldType.STRING), 78 | PayloadDocumentation.fieldWithPath("updatedBy").description("The last modifier.") 79 | .type(JsonFieldType.STRING).optional(), 80 | PayloadDocumentation.fieldWithPath("updatedAt") 81 | .description("The last modification timestamp.").type(JsonFieldType.STRING) 82 | .optional()))) 83 | .andReturn(); 84 | 85 | // Perform a simple, standard JUnit assertion to satisfy PMD rule 86 | Assert.assertEquals("failure - expected HTTP status 200", 200, result.getResponse().getStatus()); 87 | 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /src/test/java/com/leanstacks/ws/web/api/UpdateGreetingDocTest.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.web.api; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.http.MediaType; 7 | import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation; 8 | import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders; 9 | import org.springframework.restdocs.payload.JsonFieldType; 10 | import org.springframework.restdocs.payload.PayloadDocumentation; 11 | import org.springframework.restdocs.request.RequestDocumentation; 12 | import org.springframework.test.context.junit4.SpringRunner; 13 | import org.springframework.test.web.servlet.MvcResult; 14 | import org.springframework.test.web.servlet.result.MockMvcResultMatchers; 15 | 16 | import com.leanstacks.ws.AbstractDocTest; 17 | import com.leanstacks.ws.RestControllerTest; 18 | 19 | /** 20 | *

21 | * Generate REST API documentation for the GreetingController. 22 | *

23 | *

24 | * These tests utilize Spring's REST Docs Framework to generate API documentation. There is a separate test class 25 | * responsible for unit testing functionality. 26 | *

27 | * 28 | * @author Matt Warman 29 | */ 30 | @RunWith(SpringRunner.class) 31 | @RestControllerTest 32 | public class UpdateGreetingDocTest extends AbstractDocTest { 33 | 34 | /** 35 | * The HTTP request body content. 36 | */ 37 | private static final String REQUEST_BODY = "{ \"text\": \"Bonjour le monde!\" }"; 38 | 39 | @Override 40 | public void doBeforeEachTest() { 41 | // perform test initialization 42 | } 43 | 44 | @Override 45 | public void doAfterEachTest() { 46 | // perform test cleanup 47 | } 48 | 49 | /** 50 | * Generate API documentation for PUT /api/greetings/{id}. 51 | * 52 | * @throws Exception Thrown if documentation generation failure occurs. 53 | */ 54 | @Test 55 | public void documentUpdateGreeting() throws Exception { 56 | 57 | // Generate API Documentation 58 | final MvcResult result = this.mockMvc.perform(RestDocumentationRequestBuilders.put("/api/greetings/{id}", 1) 59 | .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).content(REQUEST_BODY)) 60 | .andExpect(MockMvcResultMatchers.status().isOk()) 61 | .andDo(MockMvcRestDocumentation.document("update-greeting", 62 | RequestDocumentation.pathParameters( 63 | RequestDocumentation.parameterWithName("id").description("The greeting identifier.")), 64 | PayloadDocumentation.relaxedRequestFields(PayloadDocumentation.fieldWithPath("text") 65 | .description("The text.").type(JsonFieldType.STRING)), 66 | PayloadDocumentation.relaxedResponseFields( 67 | PayloadDocumentation 68 | .fieldWithPath("id") 69 | .description( 70 | "The identifier. Used to reference specific greetings in API requests.") 71 | .type(JsonFieldType.NUMBER), 72 | PayloadDocumentation.fieldWithPath("referenceId") 73 | .description("The supplementary identifier.").type(JsonFieldType.STRING), 74 | PayloadDocumentation.fieldWithPath("text").description("The text.") 75 | .type(JsonFieldType.STRING), 76 | PayloadDocumentation.fieldWithPath("version").description("The entity version.") 77 | .type(JsonFieldType.NUMBER), 78 | PayloadDocumentation.fieldWithPath("createdBy").description("The entity creator.") 79 | .type(JsonFieldType.STRING), 80 | PayloadDocumentation.fieldWithPath("createdAt").description("The creation timestamp.") 81 | .type(JsonFieldType.STRING), 82 | PayloadDocumentation.fieldWithPath("updatedBy").description("The last modifier.") 83 | .type(JsonFieldType.STRING).optional(), 84 | PayloadDocumentation.fieldWithPath("updatedAt") 85 | .description("The last modification timestamp.").type(JsonFieldType.STRING) 86 | .optional()))) 87 | .andReturn(); 88 | 89 | // Perform a simple, standard JUnit assertion to satisfy PMD rule 90 | Assert.assertEquals("failure - expected HTTP status 200", 200, result.getResponse().getStatus()); 91 | 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/security/CorsProperties.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.security; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | import org.springframework.boot.context.properties.ConfigurationProperties; 7 | 8 | /** 9 | * A container for CORS configuration values. 10 | * 11 | * @author Matt Warman 12 | * 13 | */ 14 | @ConfigurationProperties("leanstacks.cors") 15 | public class CorsProperties { 16 | 17 | /** 18 | * The path at which the CorsFilter is registered. The CorsFilter will handle all requests matching this path. 19 | */ 20 | private String filterRegistrationPath = "/**"; 21 | 22 | /** 23 | * The value of the Access-Control-Allow-Credentials header. 24 | */ 25 | private Boolean allowCredentials = false; 26 | 27 | /** 28 | * The value of the Access-Control-Allow-Headers header. 29 | */ 30 | private List allowedHeaders = Arrays.asList("accept", "content-type"); 31 | 32 | /** 33 | * The value of the Access-Control-Allow-Methods header. 34 | */ 35 | private List allowedMethods = Arrays.asList("GET"); 36 | 37 | /** 38 | * The value of the Access-Control-Allow-Origin header. 39 | */ 40 | private List allowedOrigins = Arrays.asList("*"); 41 | 42 | /** 43 | * The value of the Access-Control-Expose-Headers header. 44 | */ 45 | private List exposedHeaders; 46 | 47 | /** 48 | * The value of the Access-Control-Max-Age header. 49 | */ 50 | private Long maxAgeSeconds = 1800L; 51 | 52 | /** 53 | * Returns the filter registration path. 54 | * 55 | * @return A String. 56 | */ 57 | public String getFilterRegistrationPath() { 58 | return filterRegistrationPath; 59 | } 60 | 61 | /** 62 | * Sets the filter registration path. 63 | * 64 | * @param filterRegistrationPath A String. 65 | */ 66 | public void setFilterRegistrationPath(final String filterRegistrationPath) { 67 | this.filterRegistrationPath = filterRegistrationPath; 68 | } 69 | 70 | /** 71 | * Returns the value of the Access-Control-Allow-Credentials header. 72 | * 73 | * @return A Boolean. 74 | */ 75 | public Boolean getAllowCredentials() { 76 | return allowCredentials; 77 | } 78 | 79 | /** 80 | * Sets the value of the Access-Control-Allow-Credentials header. 81 | * 82 | * @param allowCredentials A Boolean. 83 | */ 84 | public void setAllowCredentials(final Boolean allowCredentials) { 85 | this.allowCredentials = allowCredentials; 86 | } 87 | 88 | /** 89 | * Returns the value of the Access-Control-Allow-Headers header. 90 | * 91 | * @return A List of Strings. 92 | */ 93 | public List getAllowedHeaders() { 94 | return allowedHeaders; 95 | } 96 | 97 | /** 98 | * Sets the value of the Access-Control-Allow-Headers header. 99 | * 100 | * @param allowedHeaders A List of Strings. 101 | */ 102 | public void setAllowedHeaders(final List allowedHeaders) { 103 | this.allowedHeaders = allowedHeaders; 104 | } 105 | 106 | /** 107 | * Returns the value of the Access-Control-Allow-Methods header. 108 | * 109 | * @return A List of Strings. 110 | */ 111 | public List getAllowedMethods() { 112 | return allowedMethods; 113 | } 114 | 115 | /** 116 | * Sets the value of the Access-Control-Allow-Methods header. 117 | * 118 | * @param allowedMethods A List of Strings. 119 | */ 120 | public void setAllowedMethods(final List allowedMethods) { 121 | this.allowedMethods = allowedMethods; 122 | } 123 | 124 | /** 125 | * Returns the value of the Access-Control-Allow-Origin header. 126 | * 127 | * @return A List of Strings. 128 | */ 129 | public List getAllowedOrigins() { 130 | return allowedOrigins; 131 | } 132 | 133 | /** 134 | * Sets the value of the Access-Control-Allow-Origin header. 135 | * 136 | * @param allowedOrigins A List of Strings. 137 | */ 138 | public void setAllowedOrigins(final List allowedOrigins) { 139 | this.allowedOrigins = allowedOrigins; 140 | } 141 | 142 | /** 143 | * Returns the value of the Access-Control-Expose-Headers header. 144 | * 145 | * @return A List of Strings. 146 | */ 147 | public List getExposedHeaders() { 148 | return exposedHeaders; 149 | } 150 | 151 | /** 152 | * Sets the value of the Access-Control-Expose-Headers header. 153 | * 154 | * @param exposedHeaders A List of Strings. 155 | */ 156 | public void setExposedHeaders(final List exposedHeaders) { 157 | this.exposedHeaders = exposedHeaders; 158 | } 159 | 160 | /** 161 | * Returns the value of the Access-Control-Max-Age header in seconds. 162 | * 163 | * @return A Long. 164 | */ 165 | public Long getMaxAgeSeconds() { 166 | return maxAgeSeconds; 167 | } 168 | 169 | /** 170 | * Sets the value of the Access-Control-Max-Age header in seconds. 171 | * 172 | * @param maxAgeSeconds A Long. 173 | */ 174 | public void setMaxAgeSeconds(final Long maxAgeSeconds) { 175 | this.maxAgeSeconds = maxAgeSeconds; 176 | } 177 | 178 | } 179 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | 121 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 122 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 123 | 124 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 125 | if ERRORLEVEL 1 goto error 126 | goto end 127 | 128 | :error 129 | set ERROR_CODE=1 130 | 131 | :end 132 | @endlocal & set ERROR_CODE=%ERROR_CODE% 133 | 134 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 135 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 136 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 137 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 138 | :skipRcPost 139 | 140 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 141 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 142 | 143 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 144 | 145 | exit /B %ERROR_CODE% 146 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /src/test/java/com/leanstacks/ws/service/GreetingServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.service; 2 | 3 | import java.util.Collection; 4 | import java.util.List; 5 | import java.util.NoSuchElementException; 6 | import java.util.Optional; 7 | 8 | import org.junit.Assert; 9 | import org.junit.Test; 10 | import org.junit.runner.RunWith; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.test.context.junit4.SpringRunner; 13 | 14 | import com.leanstacks.ws.AbstractTest; 15 | import com.leanstacks.ws.BasicTransactionalTest; 16 | import com.leanstacks.ws.model.Greeting; 17 | 18 | /** 19 | * Unit test methods for the GreetingService and GreetingServiceBean. 20 | * 21 | * @author Matt Warman 22 | */ 23 | @RunWith(SpringRunner.class) 24 | @BasicTransactionalTest 25 | public class GreetingServiceTest extends AbstractTest { 26 | 27 | /** 28 | * Constant 'test'. 29 | */ 30 | private static final String VALUE_TEXT = "test"; 31 | 32 | /** 33 | * The GreetingService business service. 34 | */ 35 | @Autowired 36 | private transient GreetingService greetingService; 37 | 38 | @Override 39 | public void doBeforeEachTest() { 40 | greetingService.evictCache(); 41 | } 42 | 43 | @Override 44 | public void doAfterEachTest() { 45 | // perform test clean up 46 | } 47 | 48 | /** 49 | * Test fetch a collection of Greetings. 50 | */ 51 | @Test 52 | public void testGetGreetings() { 53 | 54 | final Collection greetings = greetingService.findAll(); 55 | 56 | Assert.assertNotNull("failure - expected not null", greetings); 57 | Assert.assertEquals("failure - expected 2 greetings", 2, greetings.size()); 58 | 59 | } 60 | 61 | /** 62 | * Test fetch a single Greeting. 63 | */ 64 | @Test 65 | public void testGetGreeting() { 66 | 67 | final Long id = Long.valueOf(1); 68 | 69 | final Greeting greeting = greetingService.findOne(id).get(); 70 | 71 | Assert.assertNotNull("failure - expected not null", greeting); 72 | Assert.assertEquals("failure - expected greeting.id match", id, greeting.getId()); 73 | 74 | } 75 | 76 | /** 77 | * Test fetch a single greeting with invalid identifier. 78 | */ 79 | @Test 80 | public void testGetGreetingNotFound() { 81 | 82 | final Long id = Long.MAX_VALUE; 83 | 84 | final Optional greetingOptional = greetingService.findOne(id); 85 | 86 | Assert.assertTrue("failure - expected null", greetingOptional.isEmpty()); 87 | 88 | } 89 | 90 | /** 91 | * Test create a Greeting. 92 | */ 93 | @Test 94 | public void testCreateGreeting() { 95 | 96 | final Greeting greeting = new Greeting(); 97 | greeting.setText(VALUE_TEXT); 98 | 99 | final Greeting createdGreeting = greetingService.create(greeting); 100 | 101 | Assert.assertNotNull("failure - expected greeting not null", createdGreeting); 102 | Assert.assertNotNull("failure - expected greeting.id not null", createdGreeting.getId()); 103 | Assert.assertEquals("failure - expected greeting.text match", VALUE_TEXT, createdGreeting.getText()); 104 | 105 | final List greetings = greetingService.findAll(); 106 | 107 | Assert.assertEquals("failure - expected 3 greetings", 3, greetings.size()); 108 | 109 | } 110 | 111 | /** 112 | * Test create a Greeting with invalid data. 113 | */ 114 | @Test 115 | public void testCreateGreetingWithId() { 116 | 117 | final Greeting greeting = new Greeting(); 118 | greeting.setId(Long.MAX_VALUE); 119 | greeting.setText(VALUE_TEXT); 120 | 121 | try { 122 | greetingService.create(greeting); 123 | Assert.fail("failure - expected exception"); 124 | } catch (IllegalArgumentException ex) { 125 | Assert.assertNotNull("failure - expected exception not null", ex); 126 | } 127 | 128 | } 129 | 130 | /** 131 | * Test update a Greeting. 132 | */ 133 | @Test 134 | public void testUpdateGreeting() { 135 | 136 | final Long id = Long.valueOf(1); 137 | 138 | final Greeting greeting = greetingService.findOne(id).get(); 139 | 140 | Assert.assertNotNull("failure - expected greeting not null", greeting); 141 | 142 | final String updatedText = greeting.getText() + " test"; 143 | greeting.setText(updatedText); 144 | final Greeting updatedGreeting = greetingService.update(greeting); 145 | 146 | Assert.assertNotNull("failure - expected updated greeting not null", updatedGreeting); 147 | Assert.assertEquals("failure - expected updated greeting id unchanged", id, updatedGreeting.getId()); 148 | Assert.assertEquals("failure - expected updated greeting text match", updatedText, updatedGreeting.getText()); 149 | 150 | } 151 | 152 | /** 153 | * Test update a Greeting which does not exist. 154 | */ 155 | @Test 156 | public void testUpdateGreetingNotFound() { 157 | 158 | final Greeting greeting = new Greeting(); 159 | greeting.setId(Long.MAX_VALUE); 160 | greeting.setText("test"); 161 | 162 | try { 163 | greetingService.update(greeting); 164 | Assert.fail("failure - expected exception"); 165 | } catch (NoSuchElementException ex) { 166 | Assert.assertNotNull("failure - expected exception not null", ex); 167 | } 168 | 169 | } 170 | 171 | /** 172 | * Test delete a Greeting. 173 | */ 174 | @Test 175 | public void testDeleteGreeting() { 176 | 177 | final Long id = Long.valueOf(1); 178 | 179 | final Greeting greeting = greetingService.findOne(id).get(); 180 | 181 | Assert.assertNotNull("failure - expected greeting not null", greeting); 182 | 183 | greetingService.delete(id); 184 | 185 | final List greetings = greetingService.findAll(); 186 | 187 | Assert.assertEquals("failure - expected 1 greeting", 1, greetings.size()); 188 | 189 | final Optional deletedGreetingOptional = greetingService.findOne(id); 190 | 191 | Assert.assertTrue("failure - expected greeting to be deleted", deletedGreetingOptional.isEmpty()); 192 | 193 | } 194 | 195 | } 196 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/web/api/RestResponseEntityExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.web.api; 2 | 3 | import java.util.NoSuchElementException; 4 | 5 | import javax.persistence.NoResultException; 6 | 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.dao.EmptyResultDataAccessException; 10 | import org.springframework.http.HttpHeaders; 11 | import org.springframework.http.HttpStatus; 12 | import org.springframework.http.ResponseEntity; 13 | import org.springframework.web.bind.annotation.ControllerAdvice; 14 | import org.springframework.web.bind.annotation.ExceptionHandler; 15 | import org.springframework.web.context.request.WebRequest; 16 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; 17 | 18 | /** 19 | * A @ControllerAdvice class which provides exception handling to all REST controllers. 20 | * 21 | * @author Matt Warman 22 | */ 23 | @ControllerAdvice 24 | public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { 25 | 26 | /** 27 | * The Logger for this Class. 28 | */ 29 | private static final Logger logger = LoggerFactory.getLogger(RestResponseEntityExceptionHandler.class); 30 | 31 | /** 32 | * Handles JPA NoResultExceptions thrown from web service controller methods. Creates a response with an 33 | * ExceptionDetail body and HTTP status code 404, not found. 34 | * 35 | * @param ex A NoResultException instance. 36 | * @return A ResponseEntity with an ExceptionDetail response body and HTTP status code 404. 37 | */ 38 | @ExceptionHandler(NoResultException.class) 39 | public ResponseEntity handleNoResultException(final NoResultException ex, final WebRequest request) { 40 | logger.info("> handleNoResultException"); 41 | logger.info("- NoResultException: ", ex); 42 | final ExceptionDetail detail = new ExceptionDetailBuilder().exception(ex).httpStatus(HttpStatus.NOT_FOUND) 43 | .webRequest(request).build(); 44 | logger.info("< handleNoResultException"); 45 | return handleExceptionInternal(ex, detail, new HttpHeaders(), HttpStatus.NOT_FOUND, request); 46 | } 47 | 48 | /** 49 | * Handles JPA NoSuchElementException thrown when an empty Optional is accessed. Creates a response with an 50 | * ExceptionDetail body and HTTP status code 404, not found. 51 | * 52 | * @param ex A NoSuchElementException instance. 53 | * @return A ResponseEntity with an ExceptionDetail response body and HTTP status code 404. 54 | */ 55 | @ExceptionHandler(NoSuchElementException.class) 56 | public ResponseEntity handleNoSuchElementException(final NoSuchElementException ex, 57 | final WebRequest request) { 58 | logger.info("> handleNoSuchElementException"); 59 | logger.info("- NoSuchElementException: ", ex); 60 | final ExceptionDetail detail = new ExceptionDetailBuilder().exception(ex).httpStatus(HttpStatus.NOT_FOUND) 61 | .webRequest(request).build(); 62 | logger.info("< handleNoSuchElementException"); 63 | return handleExceptionInternal(ex, detail, new HttpHeaders(), HttpStatus.NOT_FOUND, request); 64 | } 65 | 66 | /** 67 | * Handles EmptyResultDataAccessException thrown from web service controller methods. Creates a response with an 68 | * ExceptionDetail body and HTTP status code 404, not found. 69 | * 70 | * @param ex An EmptyResultDataAccessException instance. 71 | * @return A ResponseEntity with an ExceptionDetail response body and HTTP status code 404. 72 | */ 73 | @ExceptionHandler(EmptyResultDataAccessException.class) 74 | public ResponseEntity handleEmptyResultDataAccessException(final EmptyResultDataAccessException ex, 75 | final WebRequest request) { 76 | logger.info("> handleEmptyResultDataAccessException"); 77 | logger.info("- EmptyResultDataAccessException: ", ex); 78 | final ExceptionDetail detail = new ExceptionDetailBuilder().exception(ex).httpStatus(HttpStatus.NOT_FOUND) 79 | .webRequest(request).build(); 80 | logger.info("< handleEmptyResultDataAccessException"); 81 | return handleExceptionInternal(ex, detail, new HttpHeaders(), HttpStatus.NOT_FOUND, request); 82 | } 83 | 84 | /** 85 | * Handles IllegalArgumentException thrown from web service controller methods. Creates a response with an 86 | * ExceptionDetail body and HTTP status code 400, not found. 87 | * 88 | * @param ex An IllegalArgumentException instance. 89 | * @return A ResponseEntity with an ExceptionDetail response body and HTTP status code 400. 90 | */ 91 | @ExceptionHandler(IllegalArgumentException.class) 92 | public ResponseEntity handleIllegalArgumentException(final IllegalArgumentException ex, 93 | final WebRequest request) { 94 | logger.info("> handleIllegalArgumentException"); 95 | logger.warn("- IllegalArgumentException: ", ex); 96 | final ExceptionDetail detail = new ExceptionDetailBuilder().exception(ex).httpStatus(HttpStatus.BAD_REQUEST) 97 | .webRequest(request).build(); 98 | logger.info("< handleIllegalArgumentException"); 99 | return handleExceptionInternal(ex, detail, new HttpHeaders(), HttpStatus.BAD_REQUEST, request); 100 | } 101 | 102 | /** 103 | * Handles all Exceptions not addressed by more specific @ExceptionHandler methods. Creates a response 104 | * with the ExceptionDetail in the response body as JSON and a HTTP status code of 500, internal server error. 105 | * 106 | * @param ex An Exception instance. 107 | * @return A ResponseEntity containing a the ExceptionDetail in the response body and a HTTP status code 500. 108 | */ 109 | @ExceptionHandler(Exception.class) 110 | public ResponseEntity handleGenericException(final Exception ex, final WebRequest request) { 111 | logger.info("> handleException"); 112 | logger.error("- Exception: ", ex); 113 | final ExceptionDetail detail = new ExceptionDetailBuilder().exception(ex) 114 | .httpStatus(HttpStatus.INTERNAL_SERVER_ERROR).webRequest(request).build(); 115 | logger.info("< handleException"); 116 | return handleExceptionInternal(ex, detail, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request); 117 | } 118 | 119 | } 120 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/model/TransactionalEntity.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.model; 2 | 3 | import java.io.Serializable; 4 | import java.time.Instant; 5 | import java.util.UUID; 6 | 7 | import javax.persistence.GeneratedValue; 8 | import javax.persistence.GenerationType; 9 | import javax.persistence.Id; 10 | import javax.persistence.MappedSuperclass; 11 | import javax.persistence.PrePersist; 12 | import javax.persistence.PreUpdate; 13 | import javax.persistence.Version; 14 | import javax.validation.constraints.NotNull; 15 | 16 | import com.leanstacks.ws.util.RequestContext; 17 | 18 | /** 19 | * The parent class for all transactional persistent entities. 20 | * 21 | * @author Matt Warman 22 | */ 23 | @MappedSuperclass 24 | public class TransactionalEntity implements Serializable { 25 | 26 | /** 27 | * The default serial version UID. 28 | */ 29 | private static final long serialVersionUID = 1L; 30 | 31 | /** 32 | * The primary key identifier. 33 | */ 34 | @Id 35 | @GeneratedValue(strategy = GenerationType.IDENTITY) 36 | private Long id; 37 | 38 | /** 39 | * A secondary unique identifier which may be used as a reference to this entity by external systems. 40 | */ 41 | @NotNull 42 | private String referenceId = UUID.randomUUID().toString(); 43 | 44 | /** 45 | * The entity instance version used for optimistic locking. 46 | */ 47 | @Version 48 | private Integer version; 49 | 50 | /** 51 | * A reference to the entity or process which created this entity instance. 52 | */ 53 | @NotNull 54 | private String createdBy; 55 | 56 | /** 57 | * The timestamp when this entity instance was created. 58 | */ 59 | @NotNull 60 | private Instant createdAt; 61 | 62 | /** 63 | * A reference to the entity or process which most recently updated this entity instance. 64 | */ 65 | private String updatedBy; 66 | 67 | /** 68 | * The timestamp when this entity instance was most recently updated. 69 | */ 70 | private Instant updatedAt; 71 | 72 | public Long getId() { 73 | return id; 74 | } 75 | 76 | public void setId(final Long id) { 77 | this.id = id; 78 | } 79 | 80 | public String getReferenceId() { 81 | return referenceId; 82 | } 83 | 84 | public void setReferenceId(final String referenceId) { 85 | this.referenceId = referenceId; 86 | } 87 | 88 | public Integer getVersion() { 89 | return version; 90 | } 91 | 92 | public void setVersion(final Integer version) { 93 | this.version = version; 94 | } 95 | 96 | public String getCreatedBy() { 97 | return createdBy; 98 | } 99 | 100 | public void setCreatedBy(final String createdBy) { 101 | this.createdBy = createdBy; 102 | } 103 | 104 | public Instant getCreatedAt() { 105 | return createdAt; 106 | } 107 | 108 | public void setCreatedAt(final Instant createdAt) { 109 | this.createdAt = createdAt; 110 | } 111 | 112 | public String getUpdatedBy() { 113 | return updatedBy; 114 | } 115 | 116 | public void setUpdatedBy(final String updatedBy) { 117 | this.updatedBy = updatedBy; 118 | } 119 | 120 | public Instant getUpdatedAt() { 121 | return updatedAt; 122 | } 123 | 124 | public void setUpdatedAt(final Instant updatedAt) { 125 | this.updatedAt = updatedAt; 126 | } 127 | 128 | /** 129 | * A listener method which is invoked on instances of TransactionalEntity (or their subclasses) prior to initial 130 | * persistence. Sets the created audit values for the entity. Attempts to obtain this thread's instance 131 | * of a username from the RequestContext. If none exists, throws an IllegalArgumentException. The username is used 132 | * to set the createdBy value. The createdAt value is set to the current timestamp. 133 | */ 134 | @PrePersist 135 | public void beforePersist() { 136 | final String username = RequestContext.getUsername(); 137 | if (username == null) { 138 | throw new IllegalArgumentException("Cannot persist a TransactionalEntity without a username " 139 | + "in the RequestContext for this thread."); 140 | } 141 | setCreatedBy(username); 142 | 143 | setCreatedAt(Instant.now()); 144 | } 145 | 146 | /** 147 | * A listener method which is invoked on instances of TransactionalEntity (or their subclasses) prior to being 148 | * updated. Sets the updated audit values for the entity. Attempts to obtain this thread's instance of 149 | * username from the RequestContext. If none exists, throws an IllegalArgumentException. The username is used to set 150 | * the updatedBy value. The updatedAt value is set to the current timestamp. 151 | */ 152 | @PreUpdate 153 | public void beforeUpdate() { 154 | final String username = RequestContext.getUsername(); 155 | if (username == null) { 156 | throw new IllegalArgumentException("Cannot update a TransactionalEntity without a username " 157 | + "in the RequestContext for this thread."); 158 | } 159 | setUpdatedBy(username); 160 | 161 | setUpdatedAt(Instant.now()); 162 | } 163 | 164 | /** 165 | * Determines the equality of two TransactionalEntity objects. If the supplied object is null, returns false. If 166 | * both objects are of the same class, and their id values are populated and equal, return 167 | * true. Otherwise, return false. 168 | * 169 | * @param that An Object 170 | * @return A boolean 171 | * @see java.lang.Object#equals(java.lang.Object) 172 | */ 173 | @Override 174 | public boolean equals(final Object that) { 175 | if (that == null) { 176 | return false; 177 | } 178 | if (this.getClass().equals(that.getClass())) { 179 | final TransactionalEntity thatEntity = (TransactionalEntity) that; 180 | if (this.getId() == null || thatEntity.getId() == null) { 181 | return false; 182 | } 183 | if (this.getId().equals(thatEntity.getId())) { 184 | return true; 185 | } 186 | } 187 | return false; 188 | } 189 | 190 | /** 191 | * Returns the hash value of this object. 192 | * 193 | * @return An int 194 | * @see java.lang.Object#hashCode() 195 | */ 196 | @Override 197 | public int hashCode() { 198 | if (getId() == null) { 199 | return -1; 200 | } 201 | return getId().hashCode(); 202 | } 203 | 204 | } 205 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/service/GreetingServiceBean.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.service; 2 | 3 | import java.util.List; 4 | import java.util.Optional; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.cache.annotation.CacheEvict; 10 | import org.springframework.cache.annotation.CachePut; 11 | import org.springframework.cache.annotation.Cacheable; 12 | import org.springframework.stereotype.Service; 13 | import org.springframework.transaction.annotation.Transactional; 14 | 15 | import com.leanstacks.ws.Application; 16 | import com.leanstacks.ws.model.Greeting; 17 | import com.leanstacks.ws.repository.GreetingRepository; 18 | 19 | import io.micrometer.core.instrument.Counter; 20 | import io.micrometer.core.instrument.MeterRegistry; 21 | 22 | /** 23 | * The GreetingServiceBean encapsulates all business behaviors operating on the Greeting entity model. 24 | * 25 | * @author Matt Warman 26 | */ 27 | @Service 28 | public class GreetingServiceBean implements GreetingService { 29 | 30 | /** 31 | * The Logger for this Class. 32 | */ 33 | private static final Logger logger = LoggerFactory.getLogger(GreetingServiceBean.class); 34 | 35 | /** 36 | * Metric Counter for findAll method invocations. 37 | */ 38 | private final transient Counter findAllMethodInvocationCounter; 39 | /** 40 | * Metric Counter for findOne method invocations. 41 | */ 42 | private final transient Counter findOneMethodInvocationCounter; 43 | /** 44 | * Metric Counter for create method invocations. 45 | */ 46 | private final transient Counter createMethodInvocationCounter; 47 | /** 48 | * Metric Counter for update method invocations. 49 | */ 50 | private final transient Counter updateMethodInvocationCounter; 51 | /** 52 | * Metric Counter for delete method invocations. 53 | */ 54 | private final transient Counter deleteMethodInvocationCounter; 55 | /** 56 | * Metric Counter for evictCache method invocations. 57 | */ 58 | private final transient Counter evictCacheMethodInvocationCounter; 59 | 60 | /** 61 | * The Spring Data repository for Greeting entities. 62 | */ 63 | private final transient GreetingRepository greetingRepository; 64 | 65 | /** 66 | * Construct a GreetingServiceBean. 67 | * 68 | * @param greetingRepository A GreetingRepository. 69 | * @param meterRegistry A MeterRegistry. 70 | */ 71 | @Autowired 72 | public GreetingServiceBean(final GreetingRepository greetingRepository, final MeterRegistry meterRegistry) { 73 | this.greetingRepository = greetingRepository; 74 | this.findAllMethodInvocationCounter = meterRegistry.counter("method.invoked.greetingServiceBean.findAll"); 75 | this.findOneMethodInvocationCounter = meterRegistry.counter("method.invoked.greetingServiceBean.findOne"); 76 | this.createMethodInvocationCounter = meterRegistry.counter("method.invoked.greetingServiceBean.create"); 77 | this.updateMethodInvocationCounter = meterRegistry.counter("method.invoked.greetingServiceBean.update"); 78 | this.deleteMethodInvocationCounter = meterRegistry.counter("method.invoked.greetingServiceBean.delete"); 79 | this.evictCacheMethodInvocationCounter = meterRegistry.counter("method.invoked.greetingServiceBean.evictCache"); 80 | } 81 | 82 | @Override 83 | public List findAll() { 84 | logger.info("> findAll"); 85 | 86 | findAllMethodInvocationCounter.increment(); 87 | 88 | final List greetings = greetingRepository.findAll(); 89 | 90 | logger.info("< findAll"); 91 | return greetings; 92 | } 93 | 94 | @Cacheable(value = Application.CACHE_GREETINGS, 95 | key = "#id") 96 | @Override 97 | public Optional findOne(final Long id) { 98 | logger.info("> findOne {}", id); 99 | 100 | findOneMethodInvocationCounter.increment(); 101 | 102 | final Optional greetingOptional = greetingRepository.findById(id); 103 | 104 | logger.info("< findOne {}", id); 105 | return greetingOptional; 106 | } 107 | 108 | @CachePut(value = Application.CACHE_GREETINGS, 109 | key = "#result?.id") 110 | @Transactional 111 | @Override 112 | public Greeting create(final Greeting greeting) { 113 | logger.info("> create"); 114 | 115 | createMethodInvocationCounter.increment(); 116 | 117 | // Ensure the entity object to be created does NOT exist in the 118 | // repository. Prevent the default behavior of save() which will update 119 | // an existing entity if the entity matching the supplied id exists. 120 | if (greeting.getId() != null) { 121 | logger.error("Attempted to create a Greeting, but id attribute was not null."); 122 | logger.info("< create"); 123 | throw new IllegalArgumentException( 124 | "Cannot create new Greeting with supplied id. The id attribute must be null to create an entity."); 125 | } 126 | 127 | final Greeting savedGreeting = greetingRepository.save(greeting); 128 | 129 | logger.info("< create"); 130 | return savedGreeting; 131 | } 132 | 133 | @CachePut(value = Application.CACHE_GREETINGS, 134 | key = "#greeting.id") 135 | @Transactional 136 | @Override 137 | public Greeting update(final Greeting greeting) { 138 | logger.info("> update {}", greeting.getId()); 139 | 140 | updateMethodInvocationCounter.increment(); 141 | 142 | // findOne returns an Optional which will throw NoSuchElementException when null. 143 | // This will prevent the default behavior of save() which will persist a new 144 | // entity if the entity matching the id does not exist 145 | final Greeting greetingToUpdate = findOne(greeting.getId()).get(); 146 | 147 | greetingToUpdate.setText(greeting.getText()); 148 | final Greeting updatedGreeting = greetingRepository.save(greetingToUpdate); 149 | 150 | logger.info("< update {}", greeting.getId()); 151 | return updatedGreeting; 152 | } 153 | 154 | @CacheEvict(value = Application.CACHE_GREETINGS, 155 | key = "#id") 156 | @Transactional 157 | @Override 158 | public void delete(final Long id) { 159 | logger.info("> delete {}", id); 160 | 161 | deleteMethodInvocationCounter.increment(); 162 | 163 | greetingRepository.deleteById(id); 164 | 165 | logger.info("< delete {}", id); 166 | } 167 | 168 | @CacheEvict(value = Application.CACHE_GREETINGS, 169 | allEntries = true) 170 | @Override 171 | public void evictCache() { 172 | logger.info("> evictCache"); 173 | 174 | evictCacheMethodInvocationCounter.increment(); 175 | 176 | logger.info("< evictCache"); 177 | } 178 | 179 | } 180 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/batch/GreetingBatchBean.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.batch; 2 | 3 | import java.util.Collection; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.context.annotation.Profile; 9 | import org.springframework.scheduling.annotation.Scheduled; 10 | import org.springframework.stereotype.Component; 11 | 12 | import com.leanstacks.ws.model.Greeting; 13 | import com.leanstacks.ws.service.GreetingService; 14 | 15 | import io.micrometer.core.instrument.Counter; 16 | import io.micrometer.core.instrument.MeterRegistry; 17 | 18 | /** 19 | * The GreetingBatchBean contains @Scheduled methods operating on Greeting entities to perform batch 20 | * operations. 21 | * 22 | * @author Matt Warman 23 | */ 24 | @Component 25 | @Profile("batch") 26 | public class GreetingBatchBean { 27 | 28 | /** 29 | * The Logger for this Class. 30 | */ 31 | private static final Logger logger = LoggerFactory.getLogger(GreetingBatchBean.class); 32 | 33 | /** 34 | * Format for printed messages. 35 | */ 36 | private static final String MESSAGE_FORMAT = "There are {} greetings in the data store."; 37 | 38 | /** 39 | * Metric Counter for cron method invocations. 40 | */ 41 | private final transient Counter cronMethodCounter; 42 | /** 43 | * Metric Counter for fixed rate method invocations. 44 | */ 45 | private final transient Counter fixedRateMethodCounter; 46 | /** 47 | * Metric Counter for fixed rate initial delay method invocations. 48 | */ 49 | private final transient Counter fixedRateInitialDelayMethodCounter; 50 | /** 51 | * Metric Counter for fixed delay method invocations. 52 | */ 53 | private final transient Counter fixedDelayMethodCounter; 54 | /** 55 | * Metric Counter for fixed delay initial delay method invocations. 56 | */ 57 | private final transient Counter fixedDelayInitialDelayMethodCounter; 58 | 59 | /** 60 | * The GreetingService business service. 61 | */ 62 | private final transient GreetingService greetingService; 63 | 64 | /** 65 | * Construct a GreetingBatchBean with supplied dependencies. 66 | * 67 | * @param greetingService A GreetingService. 68 | * @param meterRegistry A MeterRegistry. 69 | */ 70 | @Autowired 71 | public GreetingBatchBean(final GreetingService greetingService, final MeterRegistry meterRegistry) { 72 | this.greetingService = greetingService; 73 | this.cronMethodCounter = meterRegistry.counter("method.invoked.greetingBatchBean.cronJob"); 74 | this.fixedRateMethodCounter = meterRegistry.counter("method.invoked.greetingBatchBean.fixedRateJob"); 75 | this.fixedRateInitialDelayMethodCounter = meterRegistry 76 | .counter("method.invoked.greetingBatchBean.fixedRateJobWithInitialDelay"); 77 | this.fixedDelayMethodCounter = meterRegistry.counter("method.invoked.greetingBatchBean.fixedDelayJob"); 78 | this.fixedDelayInitialDelayMethodCounter = meterRegistry 79 | .counter("method.invoked.greetingBatchBean.fixedDelayJobWithInitialDelay"); 80 | } 81 | 82 | /** 83 | * Use a cron expression to execute logic on a schedule. Expression: second minute hour day-of-month month weekday 84 | * 85 | * @see http ://docs.spring.io/spring/docs/current/javadoc-api/org/ springframework 86 | * /scheduling/support/CronSequenceGenerator.html 87 | */ 88 | @Scheduled(cron = "${batch.greeting.cron}") 89 | public void cronJob() { 90 | logger.info("> cronJob"); 91 | 92 | cronMethodCounter.increment(); 93 | 94 | // Add scheduled logic here 95 | 96 | final Collection greetings = greetingService.findAll(); 97 | logger.info(MESSAGE_FORMAT, greetings.size()); 98 | 99 | logger.info("< cronJob"); 100 | } 101 | 102 | /** 103 | * Execute logic beginning at fixed intervals. Use the fixedRate element to indicate how frequently the 104 | * method is to be invoked. 105 | */ 106 | @Scheduled(fixedRateString = "${batch.greeting.fixedrate}") 107 | public void fixedRateJob() { 108 | logger.info("> fixedRateJob"); 109 | 110 | fixedRateMethodCounter.increment(); 111 | 112 | // Add scheduled logic here 113 | 114 | final Collection greetings = greetingService.findAll(); 115 | logger.info(MESSAGE_FORMAT, greetings.size()); 116 | 117 | logger.info("< fixedRateJob"); 118 | } 119 | 120 | /** 121 | * Execute logic beginning at fixed intervals with a delay after the application starts. Use the 122 | * fixedRate element to indicate how frequently the method is to be invoked. Use the 123 | * initialDelay element to indicate how long to wait after application startup to schedule the first 124 | * execution. 125 | */ 126 | @Scheduled(initialDelayString = "${batch.greeting.initialdelay}", 127 | fixedRateString = "${batch.greeting.fixedrate}") 128 | public void fixedRateJobWithInitialDelay() { 129 | logger.info("> fixedRateJobWithInitialDelay"); 130 | 131 | fixedRateInitialDelayMethodCounter.increment(); 132 | 133 | // Add scheduled logic here 134 | 135 | final Collection greetings = greetingService.findAll(); 136 | logger.info(MESSAGE_FORMAT, greetings.size()); 137 | 138 | logger.info("< fixedRateJobWithInitialDelay"); 139 | } 140 | 141 | /** 142 | * Execute logic with a delay between the end of the last execution and the beginning of the next. Use the 143 | * fixedDelay element to indicate the time to wait between executions. 144 | */ 145 | @Scheduled(fixedDelayString = "${batch.greeting.fixeddelay}") 146 | public void fixedDelayJob() { 147 | logger.info("> fixedDelayJob"); 148 | 149 | fixedDelayMethodCounter.increment(); 150 | 151 | // Add scheduled logic here 152 | 153 | final Collection greetings = greetingService.findAll(); 154 | logger.info(MESSAGE_FORMAT, greetings.size()); 155 | 156 | logger.info("< fixedDelayJob"); 157 | } 158 | 159 | /** 160 | * Execute logic with a delay between the end of the last execution and the beginning of the next. Use the 161 | * fixedDelay element to indicate the time to wait between executions. Use the 162 | * initialDelay element to indicate how long to wait after application startup to schedule the first 163 | * execution. 164 | */ 165 | @Scheduled(initialDelayString = "${batch.greeting.initialdelay}", 166 | fixedDelayString = "${batch.greeting.fixeddelay}") 167 | public void fixedDelayJobWithInitialDelay() { 168 | logger.info("> fixedDelayJobWithInitialDelay"); 169 | 170 | fixedDelayInitialDelayMethodCounter.increment(); 171 | 172 | // Add scheduled logic here 173 | 174 | final Collection greetings = greetingService.findAll(); 175 | logger.info(MESSAGE_FORMAT, greetings.size()); 176 | 177 | logger.info("< fixedDelayJobWithInitialDelay"); 178 | } 179 | 180 | } 181 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | if [ "$MVNW_VERBOSE" = true ]; then 205 | echo $MAVEN_PROJECTBASEDIR 206 | fi 207 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 208 | 209 | # For Cygwin, switch paths to Windows format before running java 210 | if $cygwin; then 211 | [ -n "$M2_HOME" ] && 212 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 213 | [ -n "$JAVA_HOME" ] && 214 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 215 | [ -n "$CLASSPATH" ] && 216 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 217 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 218 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 219 | fi 220 | 221 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 222 | 223 | exec "$JAVACMD" \ 224 | $MAVEN_OPTS \ 225 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 226 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 227 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 228 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/security/SecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.security; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest; 5 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.core.annotation.Order; 9 | import org.springframework.http.HttpMethod; 10 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 11 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 12 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 13 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 14 | import org.springframework.security.config.http.SessionCreationPolicy; 15 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 16 | import org.springframework.security.crypto.password.PasswordEncoder; 17 | import org.springframework.security.web.AuthenticationEntryPoint; 18 | import org.springframework.web.cors.CorsConfiguration; 19 | import org.springframework.web.cors.CorsConfigurationSource; 20 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 21 | 22 | /** 23 | * The SecurityConfiguration class provides a centralized location for application security configuration. This class 24 | * bootstraps the Spring Security components during application startup. 25 | * 26 | * @author Matt Warman 27 | */ 28 | @Configuration 29 | @EnableWebSecurity 30 | @EnableConfigurationProperties(CorsProperties.class) 31 | public class SecurityConfiguration { 32 | 33 | /** 34 | * The AccountAuthenticationProvider is a custom Spring Security AuthenticationProvider. 35 | */ 36 | @Autowired 37 | private transient AccountAuthenticationProvider accountAuthenticationProvider; 38 | 39 | /** 40 | * Supplies a PasswordEncoder instance to the Spring ApplicationContext. The PasswordEncoder is used by the 41 | * AuthenticationProvider to perform one-way hash operations on passwords for credential comparison. 42 | * 43 | * @return A PasswordEncoder. 44 | */ 45 | @Bean 46 | public PasswordEncoder passwordEncoder() { 47 | return new BCryptPasswordEncoder(); 48 | } 49 | 50 | /** 51 | * This method builds the AuthenticationProvider used by the system to process authentication requests. 52 | * 53 | * @param auth An AuthenticationManagerBuilder instance used to construct the AuthenticationProvider. 54 | * @throws Exception Thrown if a problem occurs constructing the AuthenticationProvider. 55 | */ 56 | @Autowired 57 | public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception { 58 | 59 | auth.authenticationProvider(accountAuthenticationProvider); 60 | 61 | } 62 | 63 | /** 64 | * This inner class configures the WebSecurityConfigurerAdapter instance for the web service API context paths. 65 | * 66 | * @author Matt Warman 67 | */ 68 | @Configuration 69 | @Order(1) 70 | public static class ApiWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { 71 | 72 | /** 73 | * The CORS configuration. 74 | */ 75 | @Autowired 76 | private transient CorsProperties corsProperties; 77 | 78 | /** 79 | * Defines a ConfigurationSource for CORS attributes. 80 | * 81 | * @return A CorsConfigurationSource. 82 | */ 83 | @Bean 84 | public CorsConfigurationSource corsConfigurationSource() { 85 | final CorsConfiguration configuration = new CorsConfiguration(); 86 | configuration.setAllowedOrigins(corsProperties.getAllowedOrigins()); 87 | configuration.setAllowedMethods(corsProperties.getAllowedMethods()); 88 | configuration.setAllowedHeaders(corsProperties.getAllowedHeaders()); 89 | configuration.setAllowCredentials(corsProperties.getAllowCredentials()); 90 | configuration.setExposedHeaders(corsProperties.getExposedHeaders()); 91 | configuration.setMaxAge(corsProperties.getMaxAgeSeconds()); 92 | 93 | final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 94 | source.registerCorsConfiguration(corsProperties.getFilterRegistrationPath(), configuration); 95 | return source; 96 | } 97 | 98 | @Override 99 | protected void configure(final HttpSecurity http) throws Exception { 100 | 101 | // @formatter:off 102 | 103 | http 104 | .cors() 105 | .and() 106 | .csrf().disable() 107 | .requestMatchers().antMatchers("/api/**") 108 | .and() 109 | .authorizeRequests() 110 | .antMatchers(HttpMethod.OPTIONS).permitAll() 111 | .anyRequest().hasRole("USER") 112 | .and() 113 | .httpBasic().authenticationEntryPoint(apiAuthenticationEntryPoint()) 114 | .and() 115 | .sessionManagement() 116 | .sessionCreationPolicy(SessionCreationPolicy.STATELESS); 117 | 118 | // @formatter:on 119 | 120 | } 121 | 122 | /** 123 | * Create a RestBasicAuthenticationEntryPoint bean. Overrides the default BasicAuthenticationEntryPoint behavior 124 | * to support Basic Authentication for REST API interaction. 125 | * 126 | * @return An AuthenticationEntryPoint instance. 127 | */ 128 | @Bean 129 | public AuthenticationEntryPoint apiAuthenticationEntryPoint() { 130 | final RestBasicAuthenticationEntryPoint entryPoint = new RestBasicAuthenticationEntryPoint(); 131 | entryPoint.setRealmName("api realm"); 132 | return entryPoint; 133 | } 134 | 135 | } 136 | 137 | /** 138 | * This inner class configures the WebSecurityConfigurerAdapter instance for the Spring Actuator web service context 139 | * paths. 140 | * 141 | * @author Matt Warman 142 | */ 143 | @Configuration 144 | @Order(2) 145 | public static class ActuatorWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { 146 | 147 | @Override 148 | protected void configure(final HttpSecurity http) throws Exception { 149 | 150 | // @formatter:off 151 | 152 | http 153 | .csrf().disable() 154 | .requestMatcher(EndpointRequest.toAnyEndpoint()) 155 | .authorizeRequests() 156 | // Permit access to health check 157 | .requestMatchers(EndpointRequest.to("health")).permitAll() 158 | // Require authorization for everthing else 159 | .anyRequest().hasRole("SYSADMIN") 160 | .and() 161 | .httpBasic().authenticationEntryPoint(actuatorAuthenticationEntryPoint()) 162 | .and() 163 | .sessionManagement() 164 | .sessionCreationPolicy(SessionCreationPolicy.STATELESS); 165 | 166 | // @formatter:on 167 | 168 | } 169 | 170 | /** 171 | * Create a RestBasicAuthenticationEntryPoint bean. Overrides the default BasicAuthenticationEntryPoint behavior 172 | * to support Basic Authentication for REST API interaction. 173 | * 174 | * @return An AuthenticationEntryPoint instance. 175 | */ 176 | @Bean 177 | public AuthenticationEntryPoint actuatorAuthenticationEntryPoint() { 178 | final RestBasicAuthenticationEntryPoint entryPoint = new RestBasicAuthenticationEntryPoint(); 179 | entryPoint.setRealmName("actuator realm"); 180 | return entryPoint; 181 | } 182 | 183 | } 184 | 185 | } 186 | -------------------------------------------------------------------------------- /src/main/java/com/leanstacks/ws/web/api/GreetingController.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.web.api; 2 | 3 | import java.util.List; 4 | import java.util.Optional; 5 | import java.util.concurrent.ExecutionException; 6 | import java.util.concurrent.Future; 7 | 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.http.HttpStatus; 12 | import org.springframework.web.bind.annotation.DeleteMapping; 13 | import org.springframework.web.bind.annotation.GetMapping; 14 | import org.springframework.web.bind.annotation.PathVariable; 15 | import org.springframework.web.bind.annotation.PostMapping; 16 | import org.springframework.web.bind.annotation.PutMapping; 17 | import org.springframework.web.bind.annotation.RequestBody; 18 | import org.springframework.web.bind.annotation.RequestMapping; 19 | import org.springframework.web.bind.annotation.RequestParam; 20 | import org.springframework.web.bind.annotation.ResponseStatus; 21 | import org.springframework.web.bind.annotation.RestController; 22 | 23 | import com.leanstacks.ws.model.Greeting; 24 | import com.leanstacks.ws.service.EmailService; 25 | import com.leanstacks.ws.service.GreetingService; 26 | 27 | /** 28 | * The GreetingController class is a RESTful web service controller. The @RestController annotation informs 29 | * Spring that each @RequestMapping method returns a @ResponseBody. 30 | * 31 | * @author Matt Warman 32 | */ 33 | @RestController 34 | @RequestMapping("/api/greetings") 35 | public class GreetingController { 36 | 37 | /** 38 | * The Logger for this Class. 39 | */ 40 | private static final Logger logger = LoggerFactory.getLogger(GreetingController.class); 41 | 42 | /** 43 | * The GreetingService business service. 44 | */ 45 | @Autowired 46 | private transient GreetingService greetingService; 47 | 48 | /** 49 | * The EmailService business service. 50 | */ 51 | @Autowired 52 | private transient EmailService emailService; 53 | 54 | /** 55 | * Web service endpoint to fetch all Greeting entities. The service returns the collection of Greeting entities as 56 | * JSON. 57 | * 58 | * @return A List of Greeting objects. 59 | */ 60 | @GetMapping 61 | public List getGreetings() { 62 | logger.info("> getGreetings"); 63 | 64 | final List greetings = greetingService.findAll(); 65 | 66 | logger.info("< getGreetings"); 67 | return greetings; 68 | } 69 | 70 | /** 71 | *

72 | * Web service endpoint to fetch a single Greeting entity by primary key identifier. 73 | *

74 | *

75 | * If found, the Greeting is returned as JSON with HTTP status 200. If not found, the service returns an empty 76 | * response body with HTTP status 404. 77 | *

78 | * 79 | * @param id A Long URL path variable containing the Greeting primary key identifier. 80 | * @return A Greeting object, if found, and a HTTP status code as described in the method comment. 81 | */ 82 | @GetMapping("/{id}") 83 | public Greeting getGreeting(@PathVariable final Long id) { 84 | logger.info("> getGreeting"); 85 | 86 | final Optional greetingOptional = greetingService.findOne(id); 87 | 88 | logger.info("< getGreeting"); 89 | return greetingOptional.get(); 90 | } 91 | 92 | /** 93 | *

94 | * Web service endpoint to create a single Greeting entity. The HTTP request body is expected to contain a Greeting 95 | * object in JSON format. The Greeting is persisted in the data repository. 96 | *

97 | *

98 | * If created successfully, the persisted Greeting is returned as JSON with HTTP status 201. If not created 99 | * successfully, the service returns an ExceptionDetail response body with HTTP status 400 or 500. 100 | *

101 | * 102 | * @param greeting The Greeting object to be created. 103 | * @return A Greeting object, if created successfully, and a HTTP status code as described in the method comment. 104 | */ 105 | @PostMapping 106 | @ResponseStatus(HttpStatus.CREATED) 107 | public Greeting createGreeting(@RequestBody final Greeting greeting) { 108 | logger.info("> createGreeting"); 109 | 110 | final Greeting savedGreeting = greetingService.create(greeting); 111 | 112 | logger.info("< createGreeting"); 113 | return savedGreeting; 114 | } 115 | 116 | /** 117 | *

118 | * Web service endpoint to update a single Greeting entity. The HTTP request body is expected to contain a Greeting 119 | * object in JSON format. The Greeting is updated in the data repository. 120 | *

121 | *

122 | * If updated successfully, the persisted Greeting is returned as JSON with HTTP status 200. If not found, the 123 | * service returns an ExceptionDetail response body and HTTP status 404. If not updated successfully, the service 124 | * returns an empty response body with HTTP status 400 or 500. 125 | *

126 | * 127 | * @param greeting The Greeting object to be updated. 128 | * @return A Greeting object, if updated successfully, and a HTTP status code as described in the method comment. 129 | */ 130 | @PutMapping("/{id}") 131 | public Greeting updateGreeting(@PathVariable("id") final Long id, @RequestBody final Greeting greeting) { 132 | logger.info("> updateGreeting"); 133 | 134 | greeting.setId(id); 135 | 136 | final Greeting updatedGreeting = greetingService.update(greeting); 137 | 138 | logger.info("< updateGreeting"); 139 | return updatedGreeting; 140 | } 141 | 142 | /** 143 | *

144 | * Web service endpoint to delete a single Greeting entity. The HTTP request body is empty. The primary key 145 | * identifier of the Greeting to be deleted is supplied in the URL as a path variable. 146 | *

147 | *

148 | * If deleted successfully, the service returns an empty response body with HTTP status 204. If not deleted 149 | * successfully, the service returns an ExceptionDetail response body with HTTP status 500. 150 | *

151 | * 152 | * @param id A Long URL path variable containing the Greeting primary key identifier. 153 | */ 154 | @DeleteMapping("/{id}") 155 | @ResponseStatus(HttpStatus.NO_CONTENT) 156 | public void deleteGreeting(@PathVariable("id") final Long id) { 157 | logger.info("> deleteGreeting"); 158 | 159 | greetingService.delete(id); 160 | 161 | logger.info("< deleteGreeting"); 162 | } 163 | 164 | /** 165 | *

166 | * Web service endpoint to fetch a single Greeting entity by primary key identifier and send it as an email. 167 | *

168 | *

169 | * If found, the Greeting is returned as JSON with HTTP status 200 and sent via Email. If not found, the service 170 | * returns an Exception response body with HTTP status 404. 171 | *

172 | * 173 | * @param id A Long URL path variable containing the Greeting primary key identifier. 174 | * @param waitForAsyncResult A boolean indicating if the web service should wait for the asynchronous email 175 | * transmission. 176 | * @return A Greeting object, if found, and a HTTP status code as described in the method comment. 177 | */ 178 | @PostMapping("/{id}/send") 179 | public Greeting sendGreeting(@PathVariable("id") final Long id, @RequestParam(value = "wait", 180 | defaultValue = "false") final boolean waitForAsyncResult) { 181 | 182 | logger.info("> sendGreeting"); 183 | 184 | Greeting greeting; 185 | 186 | try { 187 | greeting = greetingService.findOne(id).get(); 188 | 189 | if (waitForAsyncResult) { 190 | final Future asyncResponse = emailService.sendAsyncWithResult(greeting); 191 | final boolean emailSent = asyncResponse.get(); 192 | logger.info("- greeting email sent? {}", emailSent); 193 | } else { 194 | emailService.sendAsync(greeting); 195 | } 196 | } catch (ExecutionException | InterruptedException ex) { 197 | logger.error("A problem occurred sending the Greeting.", ex); 198 | throw new IllegalStateException(ex); 199 | } 200 | 201 | logger.info("< sendGreeting"); 202 | return greeting; 203 | 204 | } 205 | 206 | } 207 | -------------------------------------------------------------------------------- /src/main/resources/data/changelog/db.changelog-1.7.0.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | INSERT INTO AccountRole (accountId, roleId) SELECT a.id, r.id FROM Account a, Role r WHERE a.username = 'user' and r.code = 'ROLE_USER' 182 | 183 | 184 | INSERT INTO AccountRole (accountId, roleId) SELECT a.id, r.id FROM Account a, Role r WHERE a.username = 'operations' and r.code = 'ROLE_SYSADMIN' 185 | 186 | 187 | 188 | 189 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /etc/checkstyle/rules.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 31 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 50 | 51 | 52 | 53 | 54 | 55 | 58 | 59 | 60 | 61 | 62 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 73 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 117 | 118 | 119 | 121 | 122 | 123 | 124 | 126 | 127 | 128 | 129 | 131 | 132 | 133 | 134 | 136 | 137 | 138 | 139 | 140 | 142 | 143 | 144 | 145 | 147 | 148 | 149 | 150 | 152 | 153 | 154 | 155 | 157 | 158 | 159 | 160 | 162 | 164 | 166 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 189 | 190 | 191 | 192 | 194 | 195 | 196 | 197 | 198 | 199 | 202 | 203 | 204 | 205 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 218 | 219 | 220 | 221 | 222 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | -------------------------------------------------------------------------------- /src/test/java/com/leanstacks/ws/web/api/GreetingControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.leanstacks.ws.web.api; 2 | 3 | import static org.mockito.ArgumentMatchers.any; 4 | import static org.mockito.Mockito.times; 5 | import static org.mockito.Mockito.verify; 6 | import static org.mockito.Mockito.when; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | import java.util.Optional; 11 | 12 | import org.junit.Assert; 13 | import org.junit.Test; 14 | import org.junit.runner.RunWith; 15 | import org.springframework.beans.factory.annotation.Autowired; 16 | import org.springframework.boot.test.mock.mockito.MockBean; 17 | import org.springframework.http.MediaType; 18 | import org.springframework.security.test.context.support.WithMockUser; 19 | import org.springframework.test.context.junit4.SpringRunner; 20 | import org.springframework.test.web.servlet.MockMvc; 21 | import org.springframework.test.web.servlet.MvcResult; 22 | import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; 23 | 24 | import com.fasterxml.jackson.databind.ObjectMapper; 25 | import com.google.common.base.Strings; 26 | import com.leanstacks.ws.AbstractTest; 27 | import com.leanstacks.ws.RestControllerTest; 28 | import com.leanstacks.ws.model.Greeting; 29 | import com.leanstacks.ws.service.EmailService; 30 | import com.leanstacks.ws.service.GreetingService; 31 | 32 | /** 33 | *

34 | * Unit tests for the GreetingController using mocked business components. 35 | *

36 | *

37 | * These tests utilize Spring's Test Framework to mock objects to simulate interaction with back-end components. 38 | * Back-end components are mocked and injected into the controller. Verifications are performed ensuring controller 39 | * behaviors. 40 | *

41 | * 42 | * @author Matt Warman 43 | */ 44 | @RunWith(SpringRunner.class) 45 | @RestControllerTest 46 | @WithMockUser 47 | public class GreetingControllerTest extends AbstractTest { 48 | 49 | /** 50 | * The base resource URI. 51 | */ 52 | private static final String RESOURCE_URI = "/api/greetings"; 53 | /** 54 | * The resource single item URI. 55 | */ 56 | private static final String RESOURCE_ITEM_URI = "/api/greetings/{id}"; 57 | /** 58 | * The resource single item URI with the 'send' action. 59 | */ 60 | private static final String RESOURCE_ITEM_URI_ACTION_SEND = "/api/greetings/{id}/send"; 61 | 62 | /** 63 | * A mocked GreetingService. 64 | */ 65 | @MockBean 66 | private transient GreetingService greetingService; 67 | 68 | /** 69 | * A mocked EmailService. 70 | */ 71 | @MockBean 72 | private transient EmailService emailService; 73 | 74 | /** 75 | * A mock servlet environment. 76 | */ 77 | @Autowired 78 | private transient MockMvc mvc; 79 | 80 | /** 81 | * A Jackson ObjectMapper for JSON conversion. 82 | */ 83 | @Autowired 84 | private transient ObjectMapper mapper; 85 | 86 | @Override 87 | public void doBeforeEachTest() { 88 | // perform test initialization 89 | } 90 | 91 | @Override 92 | public void doAfterEachTest() { 93 | // perform test clean up 94 | } 95 | 96 | /** 97 | * Test fetch collection of Greetings. 98 | * 99 | * @throws Exception Thrown if mocking failure occurs. 100 | */ 101 | @Test 102 | public void testGetGreetings() throws Exception { 103 | 104 | // Create some test data 105 | final List list = getEntityListStubData(); 106 | 107 | // Stub the GreetingService.findAll method return value 108 | when(greetingService.findAll()).thenReturn(list); 109 | 110 | // Perform the behavior being tested 111 | final MvcResult result = mvc 112 | .perform(MockMvcRequestBuilders.get(RESOURCE_URI).accept(MediaType.APPLICATION_JSON)).andReturn(); 113 | 114 | // Extract the response status and body 115 | final String content = result.getResponse().getContentAsString(); 116 | final int status = result.getResponse().getStatus(); 117 | 118 | // Verify the GreetingService.findAll method was invoked once 119 | verify(greetingService, times(1)).findAll(); 120 | 121 | // Perform standard JUnit assertions on the response 122 | Assert.assertEquals("failure - expected HTTP status 200", 200, status); 123 | Assert.assertTrue("failure - expected HTTP response body to have a value", !Strings.isNullOrEmpty(content)); 124 | 125 | } 126 | 127 | /** 128 | * Test fetch a Greeting by identifier. 129 | * 130 | * @throws Exception Thrown if mocking failure occurs. 131 | */ 132 | @Test 133 | public void testGetGreeting() throws Exception { 134 | 135 | // Create some test data 136 | final Long id = Long.valueOf(1); 137 | final Optional greetingOptional = Optional.of(getEntityStubData()); 138 | 139 | // Stub the GreetingService.findOne method return value 140 | when(greetingService.findOne(id)).thenReturn(greetingOptional); 141 | 142 | // Perform the behavior being tested 143 | final MvcResult result = mvc 144 | .perform(MockMvcRequestBuilders.get(RESOURCE_ITEM_URI, id).accept(MediaType.APPLICATION_JSON)) 145 | .andReturn(); 146 | 147 | // Extract the response status and body 148 | final String content = result.getResponse().getContentAsString(); 149 | final int status = result.getResponse().getStatus(); 150 | 151 | // Verify the GreetingService.findOne method was invoked once 152 | verify(greetingService, times(1)).findOne(id); 153 | 154 | // Perform standard JUnit assertions on the test results 155 | Assert.assertEquals("failure - expected HTTP status 200", 200, status); 156 | Assert.assertTrue("failure - expected HTTP response body to have a value", !Strings.isNullOrEmpty(content)); 157 | } 158 | 159 | /** 160 | * Test fetch a Greeting with unknown identifier. 161 | * 162 | * @throws Exception Thrown if mocking failure occurs. 163 | */ 164 | @Test 165 | public void testGetGreetingNotFound() throws Exception { 166 | 167 | // Create some test data 168 | final Long id = Long.MAX_VALUE; 169 | 170 | // Stub the GreetingService.findOne method return value 171 | when(greetingService.findOne(id)).thenReturn(Optional.empty()); 172 | 173 | // Perform the behavior being tested 174 | final MvcResult result = mvc 175 | .perform(MockMvcRequestBuilders.get(RESOURCE_ITEM_URI, id).accept(MediaType.APPLICATION_JSON)) 176 | .andReturn(); 177 | 178 | // Extract the response status and body 179 | final String content = result.getResponse().getContentAsString(); 180 | final int status = result.getResponse().getStatus(); 181 | 182 | // Verify the GreetingService.findOne method was invoked once 183 | verify(greetingService, times(1)).findOne(id); 184 | 185 | // Perform standard JUnit assertions on the test results 186 | Assert.assertEquals("failure - expected HTTP status 404", 404, status); 187 | Assert.assertTrue("failure - expected HTTP response body to have a value", !Strings.isNullOrEmpty(content)); 188 | 189 | } 190 | 191 | /** 192 | * Test create a Greeting. 193 | * 194 | * @throws Exception Thrown if mocking failure occurs. 195 | */ 196 | @Test 197 | public void testCreateGreeting() throws Exception { 198 | 199 | // Create some test data 200 | final Greeting entity = getEntityStubData(); 201 | 202 | // Stub the GreetingService.create method return value 203 | when(greetingService.create(any(Greeting.class))).thenReturn(entity); 204 | 205 | // Perform the behavior being tested 206 | // final String inputJson = json.mapToJson(entity); 207 | final String inputJson = mapper.writeValueAsString(entity); 208 | 209 | final MvcResult result = mvc.perform(MockMvcRequestBuilders.post(RESOURCE_URI) 210 | .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).content(inputJson)) 211 | .andReturn(); 212 | 213 | // Extract the response status and body 214 | final String content = result.getResponse().getContentAsString(); 215 | final int status = result.getResponse().getStatus(); 216 | 217 | // Verify the GreetingService.create method was invoked once 218 | verify(greetingService, times(1)).create(any(Greeting.class)); 219 | 220 | // Perform standard JUnit assertions on the test results 221 | Assert.assertEquals("failure - expected HTTP status 201", 201, status); 222 | Assert.assertTrue("failure - expected HTTP response body to have a value", !Strings.isNullOrEmpty(content)); 223 | 224 | // final Greeting createdEntity = json.mapFromJson(content, Greeting.class); 225 | final Greeting createdEntity = mapper.readValue(content, Greeting.class); 226 | 227 | Assert.assertNotNull("failure - expected entity not null", createdEntity); 228 | Assert.assertNotNull("failure - expected id attribute not null", createdEntity.getId()); 229 | Assert.assertEquals("failure - expected text attribute match", entity.getText(), createdEntity.getText()); 230 | } 231 | 232 | /** 233 | * Test update a Greeting. 234 | * 235 | * @throws Exception Thrown if mocking failure occurs. 236 | */ 237 | @Test 238 | public void testUpdateGreeting() throws Exception { 239 | 240 | // Create some test data 241 | final Greeting entity = getEntityStubData(); 242 | entity.setText(entity.getText() + " test"); 243 | final Long id = Long.valueOf(1); 244 | 245 | // Stub the GreetingService.update method return value 246 | when(greetingService.update(any(Greeting.class))).thenReturn(entity); 247 | 248 | // Perform the behavior being tested 249 | final String inputJson = mapper.writeValueAsString(entity); 250 | 251 | final MvcResult result = mvc.perform(MockMvcRequestBuilders.put(RESOURCE_ITEM_URI, id) 252 | .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).content(inputJson)) 253 | .andReturn(); 254 | 255 | // Extract the response status and body 256 | final String content = result.getResponse().getContentAsString(); 257 | final int status = result.getResponse().getStatus(); 258 | 259 | // Verify the GreetingService.update method was invoked once 260 | verify(greetingService, times(1)).update(any(Greeting.class)); 261 | 262 | // Perform standard JUnit assertions on the test results 263 | Assert.assertEquals("failure - expected HTTP status 200", 200, status); 264 | Assert.assertTrue("failure - expected HTTP response body to have a value", !Strings.isNullOrEmpty(content)); 265 | 266 | final Greeting updatedEntity = mapper.readValue(content, Greeting.class); 267 | 268 | Assert.assertNotNull("failure - expected entity not null", updatedEntity); 269 | Assert.assertEquals("failure - expected id attribute unchanged", entity.getId(), updatedEntity.getId()); 270 | Assert.assertEquals("failure - expected text attribute match", entity.getText(), updatedEntity.getText()); 271 | 272 | } 273 | 274 | /** 275 | * Test delete a Greeting. 276 | * 277 | * @throws Exception Thrown if mocking failure occurs. 278 | */ 279 | @Test 280 | public void testDeleteGreeting() throws Exception { 281 | 282 | // Create some test data 283 | final Long id = Long.valueOf(1); 284 | 285 | // Perform the behavior being tested 286 | final MvcResult result = mvc.perform(MockMvcRequestBuilders.delete(RESOURCE_ITEM_URI, id)).andReturn(); 287 | 288 | // Extract the response status and body 289 | final String content = result.getResponse().getContentAsString(); 290 | final int status = result.getResponse().getStatus(); 291 | 292 | // Verify the GreetingService.delete method was invoked once 293 | verify(greetingService, times(1)).delete(id); 294 | 295 | // Perform standard JUnit assertions on the test results 296 | Assert.assertEquals("failure - expected HTTP status 204", 204, status); 297 | Assert.assertTrue("failure - expected HTTP response body to be empty", Strings.isNullOrEmpty(content)); 298 | 299 | } 300 | 301 | /** 302 | * Test sending email asynchronously. 303 | * 304 | * @throws Exception Thrown if mocking failure occurs. 305 | */ 306 | @Test 307 | public void testSendGreetingAsync() throws Exception { 308 | 309 | // Create some test data 310 | final Long id = Long.valueOf(1); 311 | final Optional greetingOptional = Optional.of(getEntityStubData()); 312 | 313 | // Stub the GreetingService.findOne method return value 314 | when(greetingService.findOne(id)).thenReturn(greetingOptional); 315 | 316 | // Perform the behavior being tested 317 | final MvcResult result = mvc.perform( 318 | MockMvcRequestBuilders.post(RESOURCE_ITEM_URI_ACTION_SEND, id).accept(MediaType.APPLICATION_JSON)) 319 | .andReturn(); 320 | 321 | // Extract the response status and body 322 | final String content = result.getResponse().getContentAsString(); 323 | final int status = result.getResponse().getStatus(); 324 | 325 | // Verify the GreetingService.findOne method was invoked once 326 | verify(greetingService, times(1)).findOne(id); 327 | 328 | // Verify the EmailService.sendAsync method was invoked once 329 | verify(emailService, times(1)).sendAsync(any(Greeting.class)); 330 | 331 | // Perform standard JUnit assertions on the test results 332 | Assert.assertEquals("failure - expected HTTP status 200", 200, status); 333 | Assert.assertTrue("failure - expected HTTP response body to have a value", !Strings.isNullOrEmpty(content)); 334 | } 335 | 336 | private List getEntityListStubData() { 337 | final List list = new ArrayList(); 338 | list.add(getEntityStubData()); 339 | return list; 340 | } 341 | 342 | private Greeting getEntityStubData() { 343 | final Greeting entity = new Greeting(); 344 | entity.setId(1L); 345 | entity.setText("hello"); 346 | return entity; 347 | } 348 | 349 | } 350 | --------------------------------------------------------------------------------