├── .gitignore ├── .springBeans ├── .travis.yml ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── java │ └── com │ │ └── sambrannen │ │ └── spring │ │ └── events │ │ ├── Application.java │ │ ├── domain │ │ └── Event.java │ │ ├── repository │ │ └── EventRepository.java │ │ ├── service │ │ ├── EventNotFoundException.java │ │ ├── EventService.java │ │ └── StandardEventService.java │ │ └── web │ │ ├── EventsController.java │ │ ├── GlobalControllerAdvice.java │ │ ├── RestEventsController.java │ │ └── WebSecurityConfig.java └── resources │ ├── ValidationMessages.properties │ ├── ValidationMessages_en.properties │ ├── application.properties │ ├── data.sql │ ├── schema.sql │ ├── static │ ├── css │ │ └── style.css │ └── favicon.ico │ └── templates │ ├── event │ ├── form.html │ └── list.html │ └── global │ ├── footer.html │ ├── header.html │ └── meta.html └── test └── java └── com └── sambrannen └── spring └── events ├── ApplicationTests.java ├── SimpleScenarioTestNgTests.java ├── SpringEventsJUnit5TestSuite.java ├── repository └── EventRepositoryTests.java ├── service └── EventsServiceTests.java └── web ├── EventsControllerTestNgTests.java ├── EventsControllerTests.java ├── EventsControllerWithManuallyMockedServiceTests.java ├── EventsControllerWithMockedServiceTests.java ├── RestEventsControllerTests.java └── SpringEventsWebTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Gradle 2 | .gradle 3 | build/ 4 | 5 | # Ignore Gradle GUI config 6 | gradle-app.setting 7 | 8 | # Eclipse 9 | /.classpath 10 | /.settings/ 11 | /.project 12 | /bin/ 13 | 14 | # IntelliJ 15 | .idea 16 | spring-events.iml 17 | 18 | # TestNG 19 | /test-output/ 20 | 21 | # Misc 22 | *.log -------------------------------------------------------------------------------- /.springBeans: -------------------------------------------------------------------------------- 1 | 2 | 3 | 1 4 | 5 | 6 | 7 | 8 | 9 | 10 | java:com.sambrannen.spring.events.Application 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | jdk: 4 | - openjdk11 5 | 6 | before_cache: 7 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 8 | 9 | cache: 10 | directories: 11 | - $HOME/.gradle/caches/ 12 | - $HOME/.gradle/wrapper/ 13 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Spring Events 2 | 3 | _Spring Events_ is a sample application that demonstrates how to implement and test a modern Spring-powered web application. 4 | 5 | The following highlight the technologies used and features of the application. 6 | 7 | * Java 11 8 | * Spring Framework 5.2.0 9 | * Spring Boot 2.2.0 10 | * Spring Security 5.2.0 11 | * JUnit 5.5.2 12 | * TestNG 7.0.0 13 | * Simple POJO `Event` domain entity using JPA, Bean Validation, and Spring formatting annotations 14 | * Transactional service layer 15 | * Spring Data JPA repository layer 16 | * Spring @MVC + Thymeleaf & REST presentation layer 17 | 18 | ## Running the Application 19 | 20 | To see the application in action, simply execute `gradlew bootRun` and then go to [localhost:8080](http://localhost:8080/). 21 | 22 | To create a new event, click on the `New` link on the right-hand side and enter `admin` and `test` for the username and password. 23 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.2.0.RELEASE' 3 | id 'io.spring.dependency-management' version '1.0.8.RELEASE' 4 | id 'com.github.ben-manes.versions' version '0.24.0' // gradle dependencyUpdates 5 | id 'java' 6 | id 'eclipse' 7 | id 'idea' 8 | id 'maven' 9 | } 10 | 11 | group = 'com.sambrannen' 12 | version = '1.0.0-SNAPSHOT' 13 | 14 | sourceCompatibility = 11 15 | targetCompatibility = 11 16 | 17 | // Special syntax for overriding spring-boot-dependencies 18 | // https://repo1.maven.org/maven2/org/springframework/boot/spring-boot-dependencies/2.2.0.RELEASE/spring-boot-dependencies-2.2.0.RELEASE.pom 19 | // ext['junit-jupiter.version'] = '5.5.2' 20 | // ext['spring-security.version'] = '5.2.0.RELEASE' 21 | // ext['spring.version'] = '5.2.0.RELEASE' 22 | 23 | repositories { 24 | mavenCentral() 25 | // maven { url 'http://repo.spring.io/snapshot' } 26 | // maven { url 'http://repo.spring.io/milestone' } 27 | } 28 | 29 | dependencies { 30 | implementation('org.springframework.boot:spring-boot-starter-data-jpa') 31 | implementation('org.springframework.boot:spring-boot-starter-security') 32 | implementation('org.springframework.boot:spring-boot-starter-web') 33 | 34 | runtimeOnly('org.springframework.boot:spring-boot-starter-actuator') 35 | runtimeOnly('org.springframework.boot:spring-boot-starter-thymeleaf') 36 | runtimeOnly('com.fasterxml.jackson.datatype:jackson-datatype-jsr310') 37 | runtimeOnly('com.h2database:h2') 38 | 39 | testImplementation('org.springframework.boot:spring-boot-starter-test') { 40 | exclude group: 'org.junit.vintage', module: 'junit-vintage-engine' 41 | } 42 | testImplementation('org.springframework.security:spring-security-test') 43 | testImplementation('org.junit.jupiter:junit-jupiter-api') 44 | testImplementation('org.junit.platform:junit-platform-runner') 45 | testImplementation('org.testng:testng:7.0.0') 46 | 47 | testRuntimeOnly('org.junit.jupiter:junit-jupiter-engine') 48 | } 49 | 50 | task junit(type: Test) { 51 | description = 'Runs tests on the JUnit Platform.' 52 | useJUnitPlatform() 53 | testLogging { 54 | // events 'passed', 'skipped', 'failed', 'standardOut', 'standardError' 55 | events 'passed', 'skipped', 'failed' 56 | } 57 | include '**/*Tests.class' 58 | exclude '**/*TestNg*.*' 59 | } 60 | 61 | task testNG(type: Test) { 62 | description = 'Runs TestNG tests.' 63 | useTestNG() 64 | testLogging { 65 | // events 'passed', 'skipped', 'failed', 'standardOut', 'standardError' 66 | events 'passed', 'skipped', 'failed' 67 | } 68 | scanForTestClasses = false 69 | include '**/*TestNgTests.class' 70 | // Show STD_OUT & STD_ERR of the test JVM(s) on the console: 71 | // testLogging.showStandardStreams = true 72 | // forkEvery 1 73 | } 74 | 75 | test { 76 | description = 'Runs all tests.' 77 | dependsOn junit, testNG 78 | exclude(['**/*.*']) 79 | } 80 | 81 | task aggregateTestReports(type: TestReport) { 82 | description = 'Aggregates JUnit and TestNG test reports.' 83 | destinationDir = test.reports.html.destination 84 | reportOn junit, testNG 85 | } 86 | 87 | check.dependsOn aggregateTestReports 88 | 89 | wrapper { 90 | gradleVersion = '5.6.3' 91 | } 92 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbrannen/spring-events/2adb665cf7d6621eb7bddaf3158178cff30cd5db/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.3-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=$((i+1)) 158 | done 159 | case $i in 160 | (0) set -- ;; 161 | (1) set -- "$args0" ;; 162 | (2) set -- "$args0" "$args1" ;; 163 | (3) set -- "$args0" "$args1" "$args2" ;; 164 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=$(save "$@") 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 184 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 185 | cd "$(dirname "$0")" 186 | fi 187 | 188 | exec "$JAVACMD" "$@" 189 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 34 | 35 | @rem Find java.exe 36 | if defined JAVA_HOME goto findJavaFromJavaHome 37 | 38 | set JAVA_EXE=java.exe 39 | %JAVA_EXE% -version >NUL 2>&1 40 | if "%ERRORLEVEL%" == "0" goto init 41 | 42 | echo. 43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 44 | echo. 45 | echo Please set the JAVA_HOME variable in your environment to match the 46 | echo location of your Java installation. 47 | 48 | goto fail 49 | 50 | :findJavaFromJavaHome 51 | set JAVA_HOME=%JAVA_HOME:"=% 52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 53 | 54 | if exist "%JAVA_EXE%" goto init 55 | 56 | echo. 57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 58 | echo. 59 | echo Please set the JAVA_HOME variable in your environment to match the 60 | echo location of your Java installation. 61 | 62 | goto fail 63 | 64 | :init 65 | @rem Get command-line arguments, handling Windows variants 66 | 67 | if not "%OS%" == "Windows_NT" goto win9xME_args 68 | 69 | :win9xME_args 70 | @rem Slurp the command line arguments. 71 | set CMD_LINE_ARGS= 72 | set _SKIP=2 73 | 74 | :win9xME_args_slurp 75 | if "x%~1" == "x" goto execute 76 | 77 | set CMD_LINE_ARGS=%* 78 | 79 | :execute 80 | @rem Setup the command line 81 | 82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 83 | 84 | @rem Execute Gradle 85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 86 | 87 | :end 88 | @rem End local scope for the variables with windows NT shell 89 | if "%ERRORLEVEL%"=="0" goto mainEnd 90 | 91 | :fail 92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 93 | rem the _cmd.exe /c_ return code! 94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 95 | exit /b 1 96 | 97 | :mainEnd 98 | if "%OS%"=="Windows_NT" endlocal 99 | 100 | :omega 101 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'spring-events' 2 | -------------------------------------------------------------------------------- /src/main/java/com/sambrannen/spring/events/Application.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.sambrannen.spring.events; 18 | 19 | import com.sambrannen.spring.events.service.EventService; 20 | import com.sambrannen.spring.events.web.EventsController; 21 | 22 | import org.springframework.beans.factory.annotation.Autowired; 23 | import org.springframework.boot.SpringApplication; 24 | import org.springframework.boot.autoconfigure.SpringBootApplication; 25 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 26 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 27 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 28 | 29 | /** 30 | * Central configuration for the Spring Events sample application, 31 | * powered by Spring Boot. 32 | * 33 | * @author Sam Brannen 34 | * @since 1.0 35 | */ 36 | @SpringBootApplication(scanBasePackageClasses = { EventService.class, EventsController.class }) 37 | @EnableGlobalMethodSecurity(prePostEnabled = true) 38 | public class Application { 39 | 40 | public static void main(String[] args) { 41 | SpringApplication.run(Application.class, args); 42 | } 43 | 44 | @Autowired 45 | void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 46 | // @formatter:off 47 | auth.inMemoryAuthentication() 48 | .passwordEncoder(new BCryptPasswordEncoder()) 49 | .withUser("admin") 50 | // "test" is encoded using BCryptPasswordEncoder 51 | .password("$2a$10$ygTOAyJCpUirdPv9NufL9.IEBz1OHwSdD88Faf/0ZE6.MxWEsTWjW") 52 | .roles("ADMIN", "ACTUATOR"); 53 | // @formatter:on 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/sambrannen/spring/events/domain/Event.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.sambrannen.spring.events.domain; 18 | 19 | import java.io.Serializable; 20 | import java.time.LocalDate; 21 | 22 | import javax.persistence.Entity; 23 | import javax.persistence.GeneratedValue; 24 | import javax.persistence.GenerationType; 25 | import javax.persistence.Id; 26 | import javax.validation.constraints.NotNull; 27 | import javax.validation.constraints.Size; 28 | 29 | import org.springframework.format.annotation.DateTimeFormat; 30 | import org.springframework.format.annotation.DateTimeFormat.ISO; 31 | 32 | /** 33 | * Domain entity for Spring events. 34 | * 35 | * @author Sam Brannen 36 | * @since 1.0 37 | */ 38 | @Entity 39 | public class Event implements Serializable { 40 | 41 | private static final long serialVersionUID = 1L; 42 | 43 | @Id 44 | @GeneratedValue(strategy = GenerationType.AUTO) 45 | private Long id; 46 | 47 | @NotNull(message = "{errors.required}") 48 | @DateTimeFormat(iso = ISO.DATE) 49 | private LocalDate eventDate; 50 | 51 | @NotNull(message = "{errors.required}") 52 | @Size(min = 5, max = 30, message = "{errors.range}") 53 | private String name; 54 | 55 | @NotNull(message = "{errors.required}") 56 | @Size(min = 5, max = 30, message = "{errors.range}") 57 | private String location; 58 | 59 | 60 | public Event() { 61 | // It's necessary to set this here instead of at the field declaration 62 | // since Jackson will otherwise set the value to null. 63 | this.eventDate = LocalDate.now(); 64 | } 65 | 66 | public Event(Long id) { 67 | this(); 68 | this.id = id; 69 | } 70 | 71 | public Event(String name, String location) { 72 | this(); 73 | this.name = name; 74 | this.location = location; 75 | } 76 | 77 | public Event(Long id, LocalDate eventDate, String name, String location) { 78 | this(name, location); 79 | this.id = id; 80 | this.eventDate = eventDate; 81 | } 82 | 83 | public Long getId() { 84 | return id; 85 | } 86 | 87 | void setId(Long id) { 88 | this.id = id; 89 | } 90 | 91 | public LocalDate getEventDate() { 92 | return eventDate; 93 | } 94 | 95 | public void setEventDate(LocalDate eventDate) { 96 | this.eventDate = eventDate; 97 | } 98 | 99 | public String getName() { 100 | return name; 101 | } 102 | 103 | public void setName(String name) { 104 | this.name = name; 105 | } 106 | 107 | public String getLocation() { 108 | return location; 109 | } 110 | 111 | public void setLocation(String location) { 112 | this.location = location; 113 | } 114 | 115 | @Override 116 | public int hashCode() { 117 | final int prime = 31; 118 | int result = 1; 119 | result = prime * result + ((eventDate == null) ? 0 : eventDate.hashCode()); 120 | result = prime * result + ((location == null) ? 0 : location.hashCode()); 121 | result = prime * result + ((name == null) ? 0 : name.hashCode()); 122 | return result; 123 | } 124 | 125 | @Override 126 | public boolean equals(Object obj) { 127 | if (this == obj) 128 | return true; 129 | if (obj == null) 130 | return false; 131 | if (getClass() != obj.getClass()) 132 | return false; 133 | Event other = (Event) obj; 134 | if (eventDate == null) { 135 | if (other.eventDate != null) 136 | return false; 137 | } 138 | else if (!eventDate.equals(other.eventDate)) 139 | return false; 140 | if (location == null) { 141 | if (other.location != null) 142 | return false; 143 | } 144 | else if (!location.equals(other.location)) 145 | return false; 146 | if (name == null) { 147 | if (other.name != null) 148 | return false; 149 | } 150 | else if (!name.equals(other.name)) 151 | return false; 152 | return true; 153 | } 154 | 155 | @Override 156 | public String toString() { 157 | return "Event [id=" + id + ", eventDate=" + eventDate + ", name=" + name + ", location=" + location + "]"; 158 | } 159 | 160 | } 161 | -------------------------------------------------------------------------------- /src/main/java/com/sambrannen/spring/events/repository/EventRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.sambrannen.spring.events.repository; 18 | 19 | import org.springframework.data.jpa.repository.JpaRepository; 20 | import org.springframework.stereotype.Repository; 21 | 22 | import com.sambrannen.spring.events.domain.Event; 23 | 24 | /** 25 | * Repository API for the {@link Event} entity. 26 | * 27 | * @author Sam Brannen 28 | * @since 1.0 29 | */ 30 | @Repository 31 | public interface EventRepository extends JpaRepository { 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/sambrannen/spring/events/service/EventNotFoundException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.sambrannen.spring.events.service; 18 | 19 | import static org.springframework.http.HttpStatus.*; 20 | 21 | import org.springframework.web.bind.annotation.ResponseStatus; 22 | 23 | /** 24 | * Thrown to signal that an event could not be found for a given set of 25 | * search criteria. 26 | * 27 | * @author Sam Brannen 28 | * @since 1.0 29 | */ 30 | @ResponseStatus(NOT_FOUND) 31 | public class EventNotFoundException extends RuntimeException { 32 | 33 | private static final long serialVersionUID = -2411738770351557081L; 34 | 35 | 36 | public EventNotFoundException(String message) { 37 | super(message); 38 | } 39 | 40 | public EventNotFoundException(String message, Throwable cause) { 41 | super(message, cause); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/sambrannen/spring/events/service/EventService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.sambrannen.spring.events.service; 18 | 19 | import java.util.List; 20 | 21 | import com.sambrannen.spring.events.domain.Event; 22 | 23 | /** 24 | * Service API for the {@link Event} entity. 25 | * 26 | * @author Sam Brannen 27 | * @since 1.0 28 | */ 29 | public interface EventService { 30 | 31 | List findAll(); 32 | 33 | Event findById(Long id) throws EventNotFoundException; 34 | 35 | Event save(Event event); 36 | 37 | void deleteById(Long id); 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/sambrannen/spring/events/service/StandardEventService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.sambrannen.spring.events.service; 18 | 19 | import java.util.List; 20 | 21 | import org.springframework.security.access.prepost.PreAuthorize; 22 | import org.springframework.stereotype.Service; 23 | import org.springframework.transaction.annotation.Transactional; 24 | 25 | import com.sambrannen.spring.events.domain.Event; 26 | import com.sambrannen.spring.events.repository.EventRepository; 27 | 28 | /** 29 | * Standard implementation of the {@link EventService} API which delegates 30 | * to an {@link EventRepository}. 31 | * 32 | * @author Sam Brannen 33 | * @since 1.0 34 | */ 35 | @Service 36 | @Transactional(readOnly = true) 37 | public class StandardEventService implements EventService { 38 | 39 | private final EventRepository repository; 40 | 41 | 42 | public StandardEventService(EventRepository repository) { 43 | this.repository = repository; 44 | } 45 | 46 | @Override 47 | public List findAll() { 48 | return repository.findAll(); 49 | } 50 | 51 | @Override 52 | public Event findById(Long id) { 53 | return repository.findById(id).orElseThrow( 54 | () -> new EventNotFoundException("Could not find Event with ID [" + id + "]")); 55 | } 56 | 57 | @PreAuthorize("hasRole('ROLE_ADMIN')") 58 | @Transactional(readOnly = false) 59 | @Override 60 | public Event save(Event event) { 61 | return repository.save(event); 62 | } 63 | 64 | @PreAuthorize("hasRole('ROLE_ADMIN')") 65 | @Transactional(readOnly = false) 66 | @Override 67 | public void deleteById(Long id) { 68 | repository.deleteById(id); 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/com/sambrannen/spring/events/web/EventsController.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.sambrannen.spring.events.web; 18 | 19 | import javax.validation.Valid; 20 | 21 | import org.apache.commons.logging.Log; 22 | import org.apache.commons.logging.LogFactory; 23 | 24 | import org.springframework.stereotype.Controller; 25 | import org.springframework.ui.Model; 26 | import org.springframework.validation.BindingResult; 27 | import org.springframework.web.bind.annotation.GetMapping; 28 | import org.springframework.web.bind.annotation.PostMapping; 29 | 30 | import com.sambrannen.spring.events.domain.Event; 31 | import com.sambrannen.spring.events.service.EventService; 32 | 33 | /** 34 | * Spring MVC controller for displaying and creating {@link Event events}. 35 | * 36 | * @author Sam Brannen 37 | * @since 1.0 38 | */ 39 | @Controller 40 | public class EventsController { 41 | 42 | private static final String LIST_VIEW_NAME = "event/list"; 43 | private static final String FORM_VIEW_NAME = "event/form"; 44 | 45 | private static final Log log = LogFactory.getLog(EventsController.class); 46 | 47 | private final EventService service; 48 | 49 | public EventsController(EventService service) { 50 | this.service = service; 51 | } 52 | 53 | @GetMapping("/") 54 | public String list(Model model) { 55 | log.debug("Displaying all events"); 56 | model.addAttribute("events", service.findAll()); 57 | return LIST_VIEW_NAME; 58 | } 59 | 60 | @GetMapping("/form") 61 | public String edit(Model model) { 62 | log.debug("Displaying event form"); 63 | model.addAttribute(new Event()); 64 | return FORM_VIEW_NAME; 65 | } 66 | 67 | @PostMapping("/form") 68 | public String submit(@Valid Event event, BindingResult bindingResult) { 69 | if (bindingResult.hasErrors()) { 70 | log.debug("Redisplaying event form"); 71 | return FORM_VIEW_NAME; 72 | } 73 | 74 | log.debug("Submitting event form: " + event); 75 | service.save(event); 76 | return "redirect:/"; 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/sambrannen/spring/events/web/GlobalControllerAdvice.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.sambrannen.spring.events.web; 18 | 19 | import org.springframework.dao.DataIntegrityViolationException; 20 | import org.springframework.http.HttpStatus; 21 | import org.springframework.web.bind.WebDataBinder; 22 | import org.springframework.web.bind.annotation.ControllerAdvice; 23 | import org.springframework.web.bind.annotation.ExceptionHandler; 24 | import org.springframework.web.bind.annotation.InitBinder; 25 | import org.springframework.web.bind.annotation.ResponseStatus; 26 | 27 | /** 28 | * Global {@link ControllerAdvice @ControllerAdvice}. 29 | * 30 | * @author Sam Brannen 31 | * @since 1.0 32 | */ 33 | @ControllerAdvice 34 | public class GlobalControllerAdvice { 35 | 36 | @InitBinder 37 | public void configureBinding(WebDataBinder binder) { 38 | binder.setDisallowedFields("id"); 39 | } 40 | 41 | @ResponseStatus(HttpStatus.CONFLICT) 42 | @ExceptionHandler(DataIntegrityViolationException.class) 43 | public void handleDatabaseConstraintViolation() { 44 | /* no-op */ 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/sambrannen/spring/events/web/RestEventsController.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.sambrannen.spring.events.web; 18 | 19 | import static org.springframework.http.HttpStatus.NO_CONTENT; 20 | import static org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.fromMethodCall; 21 | import static org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.on; 22 | 23 | import java.util.List; 24 | 25 | import org.apache.commons.logging.Log; 26 | import org.apache.commons.logging.LogFactory; 27 | import org.springframework.http.HttpEntity; 28 | import org.springframework.http.ResponseEntity; 29 | import org.springframework.web.bind.annotation.DeleteMapping; 30 | import org.springframework.web.bind.annotation.GetMapping; 31 | import org.springframework.web.bind.annotation.PathVariable; 32 | import org.springframework.web.bind.annotation.PostMapping; 33 | import org.springframework.web.bind.annotation.PutMapping; 34 | import org.springframework.web.bind.annotation.RequestBody; 35 | import org.springframework.web.bind.annotation.RequestMapping; 36 | import org.springframework.web.bind.annotation.ResponseStatus; 37 | import org.springframework.web.bind.annotation.RestController; 38 | import org.springframework.web.util.UriComponents; 39 | 40 | import com.sambrannen.spring.events.domain.Event; 41 | import com.sambrannen.spring.events.service.EventService; 42 | 43 | /** 44 | * RESTful controller for {@link Event events}. 45 | * 46 | * @author Sam Brannen 47 | * @since 1.0 48 | */ 49 | @RestController 50 | @RequestMapping("/events") 51 | public class RestEventsController { 52 | 53 | private static final Log log = LogFactory.getLog(RestEventsController.class); 54 | 55 | private final EventService service; 56 | 57 | public RestEventsController(EventService service) { 58 | this.service = service; 59 | } 60 | 61 | @GetMapping 62 | public List retrieveAllEvents() { 63 | log.debug("Retrieving all events"); 64 | return service.findAll(); 65 | } 66 | 67 | @GetMapping("/{id}") 68 | public Event retrieveEvent(@PathVariable Long id) { 69 | log.debug("Finding event with ID: " + id); 70 | return service.findById(id); 71 | } 72 | 73 | @PostMapping 74 | public HttpEntity createEvent(@RequestBody Event postedEvent) { 75 | log.debug("Creating event: " + postedEvent); 76 | 77 | Event savedEvent = service.save(postedEvent); 78 | 79 | UriComponents uriComponents = fromMethodCall( 80 | on(getClass()).retrieveEvent(savedEvent.getId())).build(); 81 | 82 | return ResponseEntity.created(uriComponents.encode().toUri()).build(); 83 | } 84 | 85 | @PutMapping("/{id}") 86 | @ResponseStatus(NO_CONTENT) 87 | public void updateEvent(@RequestBody Event updatedEvent, @PathVariable Long id) { 88 | log.debug("Updating event: " + updatedEvent); 89 | service.save(updatedEvent); 90 | } 91 | 92 | @DeleteMapping("/{id}") 93 | @ResponseStatus(NO_CONTENT) 94 | public void deleteEvent(@PathVariable Long id) { 95 | log.debug("Deleting event with ID: " + id); 96 | service.deleteById(id); 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/com/sambrannen/spring/events/web/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.sambrannen.spring.events.web; 18 | 19 | import static org.springframework.http.HttpMethod.GET; 20 | 21 | import org.springframework.context.annotation.Configuration; 22 | import org.springframework.core.annotation.Order; 23 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 24 | import org.springframework.security.config.annotation.web.builders.WebSecurity; 25 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 26 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 27 | 28 | /** 29 | * Web security configuration for the Spring Events application. 30 | * 31 | * @author Sam Brannen 32 | * @since 1.0 33 | */ 34 | @Configuration 35 | @EnableWebSecurity 36 | public class WebSecurityConfig { 37 | 38 | @Configuration 39 | @Order(1) 40 | public static class HttpBasicWebSecurityConfig extends WebSecurityConfigurerAdapter { 41 | 42 | @Override 43 | protected void configure(HttpSecurity http) throws Exception { 44 | http 45 | .mvcMatcher("/events/**") 46 | .authorizeRequests() 47 | .mvcMatchers(GET, "/**").permitAll() 48 | .mvcMatchers("/**").hasRole("ADMIN") 49 | .and() 50 | .csrf().disable() 51 | .httpBasic(); 52 | } 53 | } 54 | 55 | @Configuration 56 | @Order(2) 57 | public static class FormLoginWebSecurityConfig extends WebSecurityConfigurerAdapter { 58 | 59 | @Override 60 | public void configure(WebSecurity web) { 61 | web.ignoring().mvcMatchers("/", "/favicon.ico", "/css/**", "/images/**"); 62 | } 63 | 64 | @Override 65 | protected void configure(HttpSecurity http) throws Exception { 66 | http 67 | .authorizeRequests() 68 | .mvcMatchers("/form**", "/h2-console/**").hasRole("ADMIN") 69 | .and() 70 | .csrf().disable() 71 | .formLogin(); 72 | } 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/main/resources/ValidationMessages.properties: -------------------------------------------------------------------------------- 1 | errors.date = is not a valid date 2 | errors.dateInFuture = must not be in the future 3 | errors.integer = must be a number 4 | errors.invalid = is invalid 5 | errors.maxlength = can not be greater than {max} characters 6 | errors.minlength = can not be less than {min} characters 7 | errors.money = must be in the form of #.## 8 | errors.numberRange = must be between {min} and {max} 9 | errors.numberRange.indexed = must be between {0} and {1} 10 | errors.range = must be between {min} and {max} characters long 11 | errors.range.indexed = must be between {0} and {1} characters long 12 | errors.required = is a required field 13 | typeMismatch.java.util.Date = is not a valid date 14 | typeMismatch.java.time.LocalDate = is not a valid date 15 | -------------------------------------------------------------------------------- /src/main/resources/ValidationMessages_en.properties: -------------------------------------------------------------------------------- 1 | ##errors.date = 2 | ##errors.dateInFuture = 3 | ##errors.integer = 4 | ##errors.invalid = 5 | ##errors.maxlength = 6 | ##errors.minlength = 7 | ##errors.money = 8 | ##errors.numberRange = 9 | ##errors.numberRange.indexed = 10 | ##errors.range = 11 | ##errors.range.indexed = 12 | ##errors.required = 13 | ##typeMismatch.java.util.Date = 14 | ##typeMismatch.java.time.LocalDate = 15 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # Ensure that auto-config doesn't overwrite our test data 2 | spring.jpa.hibernate.ddl-auto = validate 3 | 4 | # JPA / Hibernate SQL logging 5 | spring.jpa.show-sql=true 6 | spring.jpa.properties.hibernate.format_sql=true 7 | # logging.level.org.hibernate.SQL=DEBUG 8 | 9 | # Basename of properties files for JSR-303 Bean Validation error messages 10 | spring.messages.basename = ValidationMessages 11 | 12 | # Enable the H2 Web Console 13 | spring.h2.console.enabled = true 14 | 15 | # Instruct Jackson to serialize a LocalDate as an ISO-8601 string (i.e., yyyy-MM-dd) 16 | spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS = false 17 | 18 | # See: http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-logging 19 | logging.level.com.sambrannen.spring.events=DEBUG 20 | 21 | logging.level.org.hibernate.validator=WARN 22 | 23 | logging.level.org.springframework.boot.autoconfigure.security=INFO 24 | logging.level.org.springframework.boot=WARN 25 | 26 | logging.level.org.springframework.security=WARN 27 | 28 | logging.level.org.hibernate=WARN 29 | 30 | logging.level.org.springframework.context=WARN 31 | # logging.level.org.springframework.jdbc.datasource.embedded=INFO 32 | logging.level.org.springframework.web=WARN 33 | logging.level.org.springframework.test=WARN 34 | logging.level.org.springframework.test.context.cache=DEBUG 35 | 36 | # Uncommenting the following will override all above settings for org.springframework.* 37 | logging.level.org.springframework=WARN 38 | -------------------------------------------------------------------------------- /src/main/resources/data.sql: -------------------------------------------------------------------------------- 1 | insert into event (id, event_date, name, location) values (1, '2010-02-25', 'Spring Geek Night', 'Zurich'); -- What's new in Spring 3.0 2 | insert into event (id, event_date, name, location) values (2, '2011-02-17', 'Spring I/O', 'Madrid'); -- Effective out-of-container Integration Testing 3 | insert into event (id, event_date, name, location) values (3, '2011-10-28', 'SpringOne 2GX', 'Chicago'); -- Spring 3.1 and MVC Testing Support 4 | insert into event (id, event_date, name, location) values (4, '2012-10-18', 'SpringOne 2GX', 'Washington, D.C.'); -- Testing Web Applications with Spring 3.2 5 | insert into event (id, event_date, name, location) values (5, '2013-11-14', 'Devoxx', 'Antwerp'); -- Spring Framework 4.0 - The Next Generation 6 | insert into event (id, event_date, name, location) values (6, '2014-04-22', 'Spring User Group', 'Atlanta'); -- Spring Framework 4.0 to 4.1 7 | insert into event (id, event_date, name, location) values (7, '2014-09-10', 'SpringOne 2GX', 'Dallas'); -- Testing with Spring 4.x 8 | insert into event (id, event_date, name, location) values (8, '2014-11-06', 'Spring eXchange', 'London'); -- Testing with Spring: An Introduction 9 | insert into event (id, event_date, name, location) values (9, '2015-04-30', 'Spring I/O', 'Barcelona'); -- Testing with Spring 4.x 10 | insert into event (id, event_date, name, location) values (10, '2015-09-15', 'SpringOne 2GX', 'Washington, D.C.'); -- Get the Most out of Testing with Spring 4.2 11 | insert into event (id, event_date, name, location) values (11, '2016-05-19', 'Spring I/O', 'Barcelona'); -- JUnit 5: from Lambda to Alpha and Beyond 12 | insert into event (id, event_date, name, location) values (12, '2016-08-03', 'SpringOne Platform', 'Las Vegas'); -- Testing with Spring 4.3, JUnit 5, and Beyond 13 | -------------------------------------------------------------------------------- /src/main/resources/schema.sql: -------------------------------------------------------------------------------- 1 | drop table event if exists; 2 | drop sequence if exists hibernate_sequence; 3 | 4 | -- ----------------------------------------------------------------------------- 5 | 6 | -- 13 = 12 (number of entries in data.sql) + 1 7 | create sequence hibernate_sequence start with 13 increment by 1; 8 | 9 | create table event ( 10 | id bigint not null, 11 | name varchar(30) not null, 12 | event_date date not null, 13 | location varchar(30) not null, 14 | primary key (id) 15 | ); 16 | -------------------------------------------------------------------------------- /src/main/resources/static/css/style.css: -------------------------------------------------------------------------------- 1 | /* ----- Global ------------------------------------------------------------- */ 2 | body,html { 3 | font-family: Arial, Helvetica, sans-serif; 4 | font-size: 0.9em; 5 | height: 101%; 6 | color: #000; 7 | text-align: center; 8 | margin: 0 auto; 9 | } 10 | 11 | * { 12 | margin: 0px auto; 13 | } 14 | 15 | h1 { 16 | color: #369; 17 | } 18 | 19 | a, a:link, a:active, a:visited { 20 | color: #369; 21 | font-weight: bold; 22 | text-decoration: none; 23 | } 24 | 25 | a:hover { 26 | color: #147; 27 | text-decoration: underline; 28 | } 29 | 30 | a img { 31 | border: none; 32 | vertical-align: middle; 33 | } 34 | 35 | table { 36 | border: 1px #369 solid; 37 | text-align: left; 38 | } 39 | 40 | tr { 41 | border: 5px #369 solid; 42 | } 43 | 44 | th { 45 | color: #369; 46 | background-color: #F4F9FF; 47 | text-align: center; 48 | } 49 | 50 | th, td { 51 | padding: 5px; 52 | white-space: nowrap; 53 | } 54 | 55 | fieldset { 56 | border: 1px #369 solid; 57 | margin: 5px 0 10px 0; 58 | padding: 5px; 59 | text-align: left; 60 | } 61 | 62 | legend { 63 | margin: 0; 64 | padding: 2px 6px; 65 | background-color: #369; 66 | border: 1px #369 solid; 67 | color: white; 68 | font-weight: bold; 69 | } 70 | 71 | /* ----- DIVs --------------------------------------------------------------- */ 72 | #pagemargin { 73 | width: 826px; 74 | margin: 0 auto; 75 | padding: 0px; 76 | border: 1px #369 solid; 77 | text-align: left; 78 | } 79 | 80 | #header { 81 | background-color: #FFF; 82 | color: #000; 83 | text-align: left; 84 | } 85 | 86 | #navigation { 87 | background-color: #369; 88 | height: 16px; 89 | } 90 | 91 | #content { 92 | padding: 15px; 93 | background-color: #fff; 94 | color: #000; 95 | margin-bottom: 0px; 96 | text-align: left; 97 | } 98 | 99 | #footer { 100 | padding: 5px; 101 | height: 15px; 102 | background-color: #F4F9FF; 103 | color: #000; 104 | margin-top: 20px; 105 | font-size: 11px; 106 | text-align: center; 107 | } 108 | 109 | /* --- Common --------------------------------------------------------------- */ 110 | .boxleft { 111 | padding: 5px; 112 | float: left; 113 | background-color: #FFF; 114 | color: #000; 115 | width: 480px; 116 | height: 119px; 117 | } 118 | 119 | .logo { 120 | // float: right; 121 | width: 100%; 122 | font-size: 20px; 123 | text-align: center; 124 | margin-top: 20px; 125 | margin-bottom: 20px; 126 | } 127 | 128 | .clear { 129 | clear: both; 130 | } 131 | 132 | .right { 133 | float: right; 134 | } 135 | 136 | .bar { 137 | padding: 5px; 138 | height: 20px; 139 | background-color: #F4F9FF; 140 | color: #000; 141 | text-align: right; 142 | border-bottom: 1px #369 solid; 143 | } 144 | 145 | .bar span { 146 | font-family: Verdana, Arial, Helvetica, sans-serif; 147 | font-size: 1.2em; 148 | font-weight: bold; 149 | } 150 | 151 | .bar span a { 152 | color: #369; 153 | text-decoration: none; 154 | } 155 | 156 | .bar span a:hover { 157 | color: #147; 158 | text-decoration: underline; 159 | } 160 | 161 | .bar a img { 162 | border: none; 163 | vertical-align: middle; 164 | } 165 | 166 | .right_aligned { 167 | text-align: right; 168 | } 169 | 170 | .left_aligned { 171 | text-align: left; 172 | float: left; 173 | } 174 | 175 | input.btnsmall, .eventForm div.row div input.btnsmall, button.btnsmall { 176 | width: 100px; 177 | height: 18px; 178 | border: 0; 179 | font-family: Verdana, Arial, Helvetica, sans-serif; 180 | font-size: 10px; 181 | font-weight: bold; 182 | cursor: pointer; 183 | color: #369; 184 | margin: 0; 185 | padding: 0 0 2px 0; 186 | } 187 | 188 | /* ----- Errors ------------------------------------------------------------- */ 189 | .error { 190 | color: #B22; 191 | } 192 | 193 | .row span.error { 194 | float: right; 195 | } 196 | 197 | .row .col div { 198 | margin: 0; 199 | padding: 0; 200 | } 201 | 202 | .row .col div input.text, .row .col div select, .row .col div span.error { 203 | display: block; 204 | clear: both; 205 | float: left; 206 | margin: 0; 207 | padding: 0; 208 | } 209 | 210 | .row .col div span.error { 211 | white-space: nowrap; 212 | margin: 0; 213 | padding: 0; 214 | } 215 | 216 | /* ----- Event Form --------------------------------------------------------- */ 217 | 218 | .eventForm div { 219 | float: left; 220 | margin: 5px 0; 221 | } 222 | 223 | .eventForm div .right { 224 | float: right; 225 | margin: 0; 226 | } 227 | 228 | .eventForm div.row { 229 | clear: left; 230 | float: left; 231 | margin: 0; 232 | padding: 8px 0 2px 0; 233 | width: 100%; 234 | } 235 | 236 | .eventForm div.row div input { 237 | width: 100%; 238 | } 239 | 240 | .eventForm label, .eventForm .label { 241 | width: 130px; 242 | float: left; 243 | padding-right: 5px; 244 | font-weight: bold; 245 | vertical-align: middle; 246 | } 247 | 248 | .eventForm .row .col { 249 | margin: 0px; 250 | padding: 0px; 251 | } 252 | 253 | .eventForm .row .col label { 254 | margin: 0px; 255 | padding: 0px; 256 | padding-right: 5px; 257 | } 258 | 259 | .eventForm .row .col input { 260 | margin: 0px; 261 | padding: 0px; 262 | padding-left: 2px; 263 | } 264 | 265 | .eventForm input.text, .eventForm select, .eventForm textarea { 266 | margin: 0; 267 | border: 1px #b3b3b3 solid; 268 | width: 230px; 269 | } 270 | 271 | .eventForm .row .col, .eventForm .row .col .label, .eventForm .row .col .output { 272 | margin: 0; 273 | } 274 | 275 | .eventForm .row .col .output { 276 | padding-left: 2px; 277 | margin: 0; 278 | border: 1px #FFF solid; 279 | width: 230px; 280 | } 281 | 282 | .eventForm .row .col label, .eventForm .row .col .label { 283 | width: 130px; 284 | } 285 | 286 | .eventForm .row .col input.text, .eventForm .row .col div input.text { 287 | width: 230px; 288 | margin: 0 !important; 289 | padding: 0 !important; 290 | /* hack for IE6: negative margin */ 291 | margin-left: -3px; 292 | padding-left: 2px 293 | } 294 | 295 | .eventForm .row .col div input.text { 296 | /* set the margin "back" to zero inside a nested DIV */ 297 | margin-left: 0; 298 | } 299 | 300 | .eventForm .row .col_spacer { 301 | width: 20px; 302 | } 303 | 304 | input.submit { 305 | font-weight: bold; 306 | } 307 | 308 | .eventForm select { 309 | width: 233px; 310 | } 311 | 312 | .eventForm .row select, .eventForm .row textarea { 313 | margin: 0 !important; 314 | padding: 0 !important; 315 | /* hack for IE6: negative margin */ 316 | margin-left: -3px; 317 | padding-left: 2px 318 | } 319 | 320 | .eventForm .row div select, .eventForm .row div textarea { 321 | /* set the margin "back" to zero inside a nested DIV */ 322 | margin-left: 0; 323 | } 324 | 325 | .eventForm select:focus { 326 | background-color: #E0EDF9; 327 | } 328 | 329 | /* --- DOJO Dijits ---------------------------------------------------------- */ 330 | .eventForm div .dijit { 331 | width: 100%; 332 | } 333 | 334 | .eventForm .row .col div .dijit { 335 | width: auto; 336 | } 337 | 338 | .eventForm .dijitReset, .eventForm .dijitReset div, .eventForm table .dijitReset div { 339 | margin: 0; 340 | padding: 0; 341 | } 342 | 343 | .eventForm .dijitTextBox .dijitInputField { 344 | width: 210px; 345 | } 346 | -------------------------------------------------------------------------------- /src/main/resources/static/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbrannen/spring-events/2adb665cf7d6621eb7bddaf3158178cff30cd5db/src/main/resources/static/favicon.ico -------------------------------------------------------------------------------- /src/main/resources/templates/event/form.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Spring Events 5 | 6 | 7 | 8 |
9 |
10 | 11 |
12 | 13 |
14 | 15 |
16 | Errors in Form 17 |
18 |
19 | The field name 20 | The error message 21 |
22 |
23 |
24 | 25 |
26 | 27 | New Event 28 | 29 |
30 |
31 | 32 |
33 | 34 |

error

35 |
36 |
37 |
38 | 39 |
40 |
41 | 42 |
43 | 44 |

error

45 |
46 |
47 |
48 | 49 |
50 |
51 | 52 |
53 | 54 |

error

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 | -------------------------------------------------------------------------------- /src/main/resources/templates/event/list.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Spring Events 5 | 6 | 7 | 8 |
9 |
10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 |
DateEventLocation
1999-12-31EventLocation
24 |
25 | 26 |

27 |
28 |
29 |
30 | 31 | 32 | -------------------------------------------------------------------------------- /src/main/resources/templates/global/footer.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /src/main/resources/templates/global/header.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Spring Events 5 | 6 | 7 |
8 | 9 | 14 |
15 | 16 | HTML | JSON 17 | 18 | 19 | New 20 | 21 |
22 |
23 | 24 | 25 | -------------------------------------------------------------------------------- /src/main/resources/templates/global/meta.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Spring Events 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 16 | 17 | 18 | ... 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/test/java/com/sambrannen/spring/events/ApplicationTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.sambrannen.spring.events; 18 | 19 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT; 20 | 21 | import org.junit.jupiter.api.Disabled; 22 | import org.junit.jupiter.api.Test; 23 | import org.springframework.boot.test.context.SpringBootTest; 24 | 25 | /** 26 | * @author Sam Brannen 27 | * @since 1.0 28 | */ 29 | @SpringBootTest(webEnvironment = DEFINED_PORT) 30 | @Disabled 31 | class ApplicationTests { 32 | 33 | @Test 34 | void contextLoads() throws Exception { 35 | System.in.read(); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/test/java/com/sambrannen/spring/events/SimpleScenarioTestNgTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.sambrannen.spring.events; 18 | 19 | import static org.assertj.core.api.Assertions.assertThat; 20 | import static org.hamcrest.Matchers.greaterThanOrEqualTo; 21 | import static org.hamcrest.Matchers.hasSize; 22 | import static org.hamcrest.Matchers.isA; 23 | import static org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrint.SYSTEM_ERR; 24 | import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.MOCK; 25 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 26 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 27 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; 28 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; 29 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; 30 | 31 | import org.springframework.beans.factory.annotation.Autowired; 32 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 33 | import org.springframework.boot.test.context.SpringBootTest; 34 | import org.springframework.security.test.context.support.WithMockUser; 35 | import org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener; 36 | import org.springframework.test.context.TestExecutionListeners; 37 | import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; 38 | import org.springframework.test.web.servlet.MockMvc; 39 | import org.testng.annotations.Test; 40 | 41 | import com.sambrannen.spring.events.domain.Event; 42 | import com.sambrannen.spring.events.repository.EventRepository; 43 | 44 | /** 45 | * TestNG based scenario tests for the Spring Events application. 46 | * 47 | * @author Nicolas Frankel 48 | * @author Sam Brannen 49 | * @since 1.0 50 | */ 51 | @SpringBootTest(webEnvironment = MOCK) 52 | @AutoConfigureMockMvc(print = SYSTEM_ERR) 53 | @TestExecutionListeners(WithSecurityContextTestExecutionListener.class) 54 | class SimpleScenarioTestNgTests extends AbstractTestNGSpringContextTests { 55 | 56 | @Autowired 57 | MockMvc mockMvc; 58 | 59 | @Autowired 60 | EventRepository repository; 61 | 62 | 63 | @Test 64 | void shouldDisplayAtLeastTenItemsInitially() throws Exception { 65 | mockMvc.perform(get("/")) 66 | .andExpect(view().name("event/list")) 67 | .andExpect(model().attribute("events", hasSize(greaterThanOrEqualTo(10)))); 68 | } 69 | 70 | @Test(dependsOnMethods = "shouldDisplayAtLeastTenItemsInitially") 71 | @WithMockUser(roles = "ADMIN") 72 | void shouldDisplayEventForm() throws Exception { 73 | mockMvc.perform(get("/form")) 74 | .andExpect(view().name("event/form")) 75 | .andExpect(model().attribute("event", isA(Event.class))); 76 | } 77 | 78 | @Test(dependsOnMethods = "shouldDisplayEventForm") 79 | @WithMockUser(roles = "ADMIN") 80 | void shouldAddNewEvent() throws Exception { 81 | mockMvc.perform(post("/form").param("name", "THE Event").param("location", "Earth")) 82 | .andExpect(redirectedUrl("/")); 83 | 84 | assertThat(repository.count()).isGreaterThanOrEqualTo(11); 85 | } 86 | 87 | @Test(dependsOnMethods = "shouldAddNewEvent") 88 | void shouldDisplayAtLeastElevenItemsInTheEnd() throws Exception { 89 | mockMvc.perform(get("/")) 90 | .andExpect(view().name("event/list")) 91 | .andExpect(model().attribute("events", hasSize(greaterThanOrEqualTo(11)))); 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /src/test/java/com/sambrannen/spring/events/SpringEventsJUnit5TestSuite.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.sambrannen.spring.events; 18 | 19 | import org.junit.platform.runner.JUnitPlatform; 20 | import org.junit.platform.suite.api.IncludeEngines; 21 | import org.junit.platform.suite.api.SelectPackages; 22 | import org.junit.runner.RunWith; 23 | 24 | /** 25 | * Test suite for the Spring Events application that runs on the JUnit Platform. 26 | * 27 | * @author Sam Brannen 28 | * @since 1.0 29 | */ 30 | @RunWith(JUnitPlatform.class) 31 | @SelectPackages("com.sambrannen.spring.events") 32 | @IncludeEngines("junit-jupiter") 33 | public class SpringEventsJUnit5TestSuite { 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/com/sambrannen/spring/events/repository/EventRepositoryTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.sambrannen.spring.events.repository; 18 | 19 | import static org.assertj.core.api.Assertions.assertThat; 20 | import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS; 21 | 22 | import java.time.LocalDate; 23 | import java.util.List; 24 | 25 | import com.sambrannen.spring.events.domain.Event; 26 | 27 | import org.junit.jupiter.api.Test; 28 | import org.junit.jupiter.api.TestInstance; 29 | import org.springframework.beans.factory.annotation.Autowired; 30 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 31 | import org.springframework.jdbc.core.JdbcTemplate; 32 | import org.springframework.test.jdbc.JdbcTestUtils; 33 | 34 | /** 35 | * Integration tests for the {@link EventRepository}. 36 | * 37 | * @author Sam Brannen 38 | * @since 1.0 39 | */ 40 | @DataJpaTest(showSql = true) 41 | @TestInstance(PER_CLASS) 42 | class EventRepositoryTests { 43 | 44 | private final JdbcTemplate jdbcTemplate; 45 | 46 | private final EventRepository repo; 47 | 48 | @Autowired 49 | EventRepositoryTests(JdbcTemplate jdbcTemplate, EventRepository repo) { 50 | this.jdbcTemplate = jdbcTemplate; 51 | this.repo = repo; 52 | } 53 | 54 | @Test 55 | void findAll() { 56 | List events = repo.findAll(); 57 | assertThat(events).size().isGreaterThan(0); 58 | } 59 | 60 | @Test 61 | void findById() { 62 | assertThat(repo.findById(1L)).isPresent(); 63 | assertThat(repo.findById(999L)).isNotPresent(); 64 | } 65 | 66 | @Test 67 | void save() { 68 | final int numRowsInTable = countNumEvents(); 69 | final LocalDate tomorrow = LocalDate.now().plusDays(1); 70 | 71 | Event event = new Event(); 72 | event.setName("test event"); 73 | event.setLocation("test suite"); 74 | event.setEventDate(tomorrow); 75 | 76 | Event savedEvent = repo.save(event); 77 | repo.flush(); 78 | 79 | assertThat(savedEvent.getId()).isNotNull(); 80 | assertNumEvents(numRowsInTable + 1); 81 | Event retrievedSavedEvent = repo.findById(savedEvent.getId()).orElse(null); 82 | assertThat(retrievedSavedEvent).isEqualTo(event); 83 | assertThat(retrievedSavedEvent.getEventDate()).isEqualTo(tomorrow); 84 | } 85 | 86 | @Test 87 | void update() { 88 | final int numRowsInTable = countNumEvents(); 89 | 90 | Event event = repo.findById(1L).orElse(null); 91 | assertThat(event).isNotNull(); 92 | event.setName("updated name"); 93 | 94 | Event updatedEvent = repo.save(event); 95 | repo.flush(); 96 | 97 | assertNumEvents(numRowsInTable); 98 | String updatedName = lookUpNameInDatabase(updatedEvent); 99 | assertThat(updatedName).isEqualTo("updated name"); 100 | } 101 | 102 | @Test 103 | void delete() { 104 | final int numRowsInTable = countNumEvents(); 105 | 106 | Event event = repo.findById(1L).orElse(null); 107 | assertThat(event).isNotNull(); 108 | repo.delete(event); 109 | repo.flush(); 110 | assertNumEvents(numRowsInTable - 1); 111 | } 112 | 113 | private String lookUpNameInDatabase(Event event) { 114 | return jdbcTemplate.queryForObject("select name from event where id=?", String.class, event.getId()); 115 | } 116 | 117 | private int countNumEvents() { 118 | return JdbcTestUtils.countRowsInTable(jdbcTemplate, "event"); 119 | } 120 | 121 | private void assertNumEvents(int expectedNumRows) { 122 | assertThat(countNumEvents()).isEqualTo(expectedNumRows); 123 | } 124 | 125 | } 126 | -------------------------------------------------------------------------------- /src/test/java/com/sambrannen/spring/events/service/EventsServiceTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.sambrannen.spring.events.service; 18 | 19 | import static org.assertj.core.api.Assertions.assertThat; 20 | 21 | import com.sambrannen.spring.events.domain.Event; 22 | import com.sambrannen.spring.events.repository.EventRepository; 23 | 24 | import org.junit.jupiter.api.Test; 25 | import org.springframework.beans.factory.annotation.Autowired; 26 | import org.springframework.boot.test.context.SpringBootTest; 27 | import org.springframework.security.test.context.support.WithMockUser; 28 | import org.springframework.transaction.annotation.Transactional; 29 | 30 | /** 31 | * Integration tests for the {@link EventService}. 32 | * 33 | * @author Sam Brannen 34 | * @since 1.0 35 | */ 36 | @SpringBootTest 37 | @Transactional 38 | class EventsServiceTests { 39 | 40 | @Autowired 41 | EventService service; 42 | 43 | @Autowired 44 | EventRepository repo; 45 | 46 | @Test 47 | @WithMockUser(roles = "ADMIN") 48 | void save() { 49 | service.save(new Event("new event", "integration test")); 50 | 51 | assertThat(repo.findAll().stream().filter(e -> e.getName().equals("new event")).findFirst()).isPresent(); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/test/java/com/sambrannen/spring/events/web/EventsControllerTestNgTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.sambrannen.spring.events.web; 18 | 19 | import static org.hamcrest.Matchers.greaterThan; 20 | import static org.hamcrest.Matchers.hasSize; 21 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 22 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; 23 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; 24 | 25 | import org.springframework.beans.factory.annotation.Autowired; 26 | import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; 27 | import org.springframework.test.web.servlet.MockMvc; 28 | 29 | import org.testng.annotations.Test; 30 | 31 | /** 32 | * TestNG based integration tests for the {@link EventsController}. 33 | * 34 | * @author Nicolas Frankel 35 | * @author Sam Brannen 36 | * @since 1.0 37 | * @see EventsControllerTests 38 | */ 39 | @SpringEventsWebTest 40 | class EventsControllerTestNgTests extends AbstractTestNGSpringContextTests { 41 | 42 | @Autowired 43 | MockMvc mockMvc; 44 | 45 | 46 | @Test 47 | void listEvents() throws Exception { 48 | mockMvc.perform(get("/")) 49 | .andExpect(view().name("event/list")) 50 | .andExpect(model().attribute("events", hasSize(greaterThan(10)))); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/test/java/com/sambrannen/spring/events/web/EventsControllerTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.sambrannen.spring.events.web; 18 | 19 | import static org.hamcrest.Matchers.greaterThan; 20 | import static org.hamcrest.Matchers.hasSize; 21 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 22 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; 23 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; 24 | 25 | import org.junit.jupiter.api.DisplayName; 26 | import org.junit.jupiter.api.Test; 27 | 28 | import org.springframework.beans.factory.annotation.Autowired; 29 | import org.springframework.test.web.servlet.MockMvc; 30 | 31 | /** 32 | * JUnit based integration tests for the {@link EventsController}. 33 | * 34 | * @author Sam Brannen 35 | * @since 1.0 36 | * @see EventsControllerTestNgTests 37 | */ 38 | @SpringEventsWebTest 39 | class EventsControllerTests { 40 | 41 | @Test 42 | @DisplayName("Home page should display more than 10 events") 43 | void listEvents(@Autowired MockMvc mockMvc) throws Exception { 44 | mockMvc.perform(get("/")) 45 | .andExpect(view().name("event/list")) 46 | .andExpect(model().attribute("events", hasSize(greaterThan(10)))); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/test/java/com/sambrannen/spring/events/web/EventsControllerWithManuallyMockedServiceTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.sambrannen.spring.events.web; 18 | 19 | import static java.util.Collections.singletonList; 20 | import static org.hamcrest.Matchers.hasSize; 21 | import static org.mockito.Mockito.when; 22 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 23 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; 24 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; 25 | import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; 26 | 27 | import org.junit.Before; 28 | import org.junit.Test; 29 | import org.junit.runner.RunWith; 30 | 31 | import org.mockito.Mockito; 32 | 33 | import org.springframework.beans.factory.annotation.Autowired; 34 | import org.springframework.context.annotation.Bean; 35 | import org.springframework.context.annotation.ComponentScan; 36 | import org.springframework.context.annotation.Configuration; 37 | import org.springframework.context.annotation.Profile; 38 | import org.springframework.test.context.ActiveProfiles; 39 | import org.springframework.test.context.ContextConfiguration; 40 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 41 | import org.springframework.test.context.web.WebAppConfiguration; 42 | import org.springframework.test.web.servlet.MockMvc; 43 | import org.springframework.web.context.WebApplicationContext; 44 | import org.springframework.web.servlet.config.annotation.EnableWebMvc; 45 | 46 | import com.sambrannen.spring.events.domain.Event; 47 | import com.sambrannen.spring.events.service.EventService; 48 | 49 | /** 50 | * Integration tests for the {@link EventsController} with a manually 51 | * mocked {@link EventService} using JUnit 4 and pre-Spring 4.3 52 | * configuration mechanisms without Spring Boot. 53 | * 54 | * @author Sam Brannen 55 | * @since 1.0 56 | */ 57 | @RunWith(SpringJUnit4ClassRunner.class) 58 | @WebAppConfiguration 59 | @ContextConfiguration 60 | @ActiveProfiles("dev") 61 | public class EventsControllerWithManuallyMockedServiceTests { 62 | 63 | @Autowired 64 | EventService eventService; 65 | 66 | @Autowired 67 | WebApplicationContext wac; 68 | 69 | MockMvc mockMvc; 70 | 71 | 72 | @Before 73 | public void setUp() { 74 | this.mockMvc = webAppContextSetup(wac).build(); 75 | } 76 | 77 | @Test 78 | public void listEvents() throws Exception { 79 | when(eventService.findAll()).thenReturn(singletonList(new Event(1L))); 80 | 81 | mockMvc.perform(get("/"))// 82 | .andExpect(view().name("event/list"))// 83 | .andExpect(model().attribute("events", hasSize(1))); 84 | } 85 | 86 | 87 | @Configuration 88 | @EnableWebMvc 89 | @ComponentScan(basePackageClasses = EventsController.class) 90 | static class Config { 91 | 92 | @Bean 93 | @Profile("dev") 94 | EventService eventService() { 95 | return Mockito.mock(EventService.class); 96 | } 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /src/test/java/com/sambrannen/spring/events/web/EventsControllerWithMockedServiceTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.sambrannen.spring.events.web; 18 | 19 | import static java.util.Collections.singletonList; 20 | import static org.hamcrest.Matchers.hasSize; 21 | import static org.mockito.Mockito.when; 22 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 23 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; 24 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; 25 | 26 | import com.sambrannen.spring.events.domain.Event; 27 | import com.sambrannen.spring.events.service.EventService; 28 | 29 | import org.junit.jupiter.api.Test; 30 | import org.springframework.beans.factory.annotation.Autowired; 31 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 32 | import org.springframework.boot.test.mock.mockito.MockBean; 33 | import org.springframework.test.web.servlet.MockMvc; 34 | 35 | /** 36 | * Integration tests for the {@link EventsController} with a mocked 37 | * {@link EventService}. 38 | * 39 | * @author Sam Brannen 40 | * @since 1.0 41 | */ 42 | @WebMvcTest 43 | class EventsControllerWithMockedServiceTests { 44 | 45 | @MockBean 46 | EventService eventService; 47 | 48 | @Test 49 | void listEvents(@Autowired MockMvc mockMvc) throws Exception { 50 | when(eventService.findAll()).thenReturn(singletonList(new Event(1L))); 51 | 52 | mockMvc.perform(get("/"))// 53 | .andExpect(view().name("event/list"))// 54 | .andExpect(model().attribute("events", hasSize(1))); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/test/java/com/sambrannen/spring/events/web/RestEventsControllerTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.sambrannen.spring.events.web; 18 | 19 | import static org.assertj.core.api.Assertions.assertThat; 20 | import static org.hamcrest.CoreMatchers.hasItems; 21 | import static org.hamcrest.CoreMatchers.is; 22 | import static org.springframework.http.MediaType.APPLICATION_JSON; 23 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; 24 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 25 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 26 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; 27 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 28 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 29 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 30 | 31 | import java.util.Optional; 32 | 33 | import com.sambrannen.spring.events.domain.Event; 34 | import com.sambrannen.spring.events.repository.EventRepository; 35 | 36 | import org.junit.jupiter.api.Test; 37 | 38 | import org.springframework.beans.factory.annotation.Autowired; 39 | import org.springframework.security.test.context.support.WithMockUser; 40 | import org.springframework.test.web.servlet.MockMvc; 41 | 42 | /** 43 | * Integration tests for the {@link RestEventsController}. 44 | * 45 | * @author Sam Brannen 46 | * @since 1.0 47 | */ 48 | @SpringEventsWebTest 49 | class RestEventsControllerTests { 50 | 51 | @Autowired 52 | MockMvc mockMvc; 53 | 54 | @Autowired 55 | EventRepository repo; 56 | 57 | 58 | @Test 59 | void retrieveAllEvents() throws Exception { 60 | mockMvc.perform(get("/events").accept(APPLICATION_JSON))// 61 | .andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON))// 62 | .andExpect(status().isOk())// 63 | .andExpect(jsonPath("$[8]").exists())// 64 | .andExpect(jsonPath("$[?(@.name =~ /Spring I.O/)].location", 65 | hasItems("Madrid", "Barcelona"))); 66 | } 67 | 68 | @Test 69 | void retrieveEvent() throws Exception { 70 | mockMvc.perform(get("/events/{id}", 9).accept(APPLICATION_JSON))// 71 | .andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON))// 72 | .andExpect(status().isOk())// 73 | .andExpect(jsonPath("$.id", is(9)))// 74 | .andExpect(jsonPath("$.eventDate", is("2015-04-30")))// 75 | .andExpect(jsonPath("$.name", is("Spring I/O")))// 76 | .andExpect(jsonPath("$.location", is("Barcelona"))); 77 | } 78 | 79 | @Test 80 | void retrieveNonexistentEvent() throws Exception { 81 | mockMvc.perform(get("/events/{id}", 12345).accept(APPLICATION_JSON))// 82 | .andExpect(status().isNotFound()); 83 | } 84 | 85 | @Test 86 | @WithMockUser(roles = "ADMIN") 87 | void createEvent() throws Exception { 88 | mockMvc.perform( 89 | post("/events/") 90 | .contentType(APPLICATION_JSON)// 91 | .content("{\"name\": \"Spring!\", \"location\": \"Integration Test\"}")// 92 | //.with(user("admin").roles("ADMIN"))// 93 | ) 94 | .andExpect(status().isCreated()); 95 | } 96 | 97 | @Test 98 | @WithMockUser(roles = "ADMIN") 99 | void updateEvent() throws Exception { 100 | 101 | String json = "{\"id\": 9, \"eventDate\": \"2015-04-30\", \"name\": \"Edited\", \"location\": \"Integration Test\"}"; 102 | 103 | mockMvc.perform( 104 | put("/events/{id}", 9).contentType(APPLICATION_JSON) 105 | .content(json))// 106 | .andExpect(status().isNoContent()); 107 | 108 | Event updatedEvent = repo.findById(9L).get(); 109 | assertThat(updatedEvent.getName()).isEqualTo("Edited"); 110 | } 111 | 112 | @Test 113 | @WithMockUser(roles = "ADMIN") 114 | void deleteEvent() throws Exception { 115 | mockMvc.perform(delete("/events/{id}", 9))// 116 | .andExpect(status().isNoContent()); 117 | 118 | Optional deletedEvent = repo.findById(9L); 119 | assertThat(deletedEvent).isNotPresent(); 120 | } 121 | 122 | } 123 | 124 | // Example JSON Output 125 | // 126 | // [ 127 | // {"id":1,"eventDate":"2010-02-25","name":"Spring Geek Night","location":"Zurich"}, 128 | // {"id":2,"eventDate":"2011-02-17","name":"Spring I/O","location":"Madrid"}, 129 | // {"id":3,"eventDate":"2011-10-28","name":"SpringOne 2GX","location":"Chicago"}, 130 | // {"id":4,"eventDate":"2012-10-18","name":"SpringOne 2GX","location":"Washington, D.C."}, 131 | // {"id":5,"eventDate":"2013-11-14","name":"Devoxx","location":"Antwerp"}, 132 | // {"id":6,"eventDate":"2014-04-22","name":"Spring User Group","location":"Atlanta"}, 133 | // {"id":7,"eventDate":"2014-09-10","name":"SpringOne 2GX","location":"Dallas"}, 134 | // {"id":8,"eventDate":"2014-11-06","name":"Spring eXchange","location":"London"}, 135 | // {"id":9,"eventDate":"2015-04-30","name":"Spring I/O","location":"Barcelona"} 136 | // {"id":10,"eventDate":"2015-09-15","name":"SpringOne 2GX","location":"Washington, D.C."}, 137 | // {"id":11,"eventDate":"2016-05-19","name":"Spring I/O","location":"Barcelona"}, 138 | // {"id":12,"eventDate":"2016-08-03","name":"SpringOne Platform","location":"Las Vegas"} 139 | // ] 140 | 141 | //----------------------------------------------------------------------------- 142 | //--- httpie 143 | //----------------------------------------------------------------------------- 144 | 145 | // http GET http://localhost:8080/events 146 | 147 | // http GET http://localhost:8080/events/9 148 | 149 | // http -a admin:test POST http://localhost:8080/events/ name=Spring! location='Command Line' 150 | 151 | // http -a admin:test PUT http://localhost:8080/events/9 id=9 eventDate=2015-04-30 name=Edited location='Command Line' 152 | 153 | // http -a admin:test DELETE http://localhost:8080/events/9 154 | 155 | //----------------------------------------------------------------------------- 156 | //--- curl and json_pp 157 | //----------------------------------------------------------------------------- 158 | 159 | // curl -H "Accept:application/json" http://localhost:8080/events | json_pp 160 | 161 | // curl -H "Accept:application/json" http://localhost:8080/events/9 | json_pp 162 | 163 | // curl -u admin:test -i -X POST -H "Content-Type:application/json" http://localhost:8080/events/ -d '{"name": "Spring!", "location": "Command Line"}' 164 | 165 | // curl -u admin:test -i -X PUT -H "Content-Type:application/json" http://localhost:8080/events/9 -d '{"id":"9", "eventDate":"2015-04-30", "name": "Edited", "location": "Command Line"}' 166 | 167 | // curl -u admin:test -i -X DELETE http://localhost:8080/events/9 168 | -------------------------------------------------------------------------------- /src/test/java/com/sambrannen/spring/events/web/SpringEventsWebTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.sambrannen.spring.events.web; 18 | 19 | import java.lang.annotation.Documented; 20 | import java.lang.annotation.ElementType; 21 | import java.lang.annotation.Inherited; 22 | import java.lang.annotation.Retention; 23 | import java.lang.annotation.RetentionPolicy; 24 | import java.lang.annotation.Target; 25 | 26 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 27 | import org.springframework.boot.test.context.SpringBootTest; 28 | import org.springframework.transaction.annotation.Transactional; 29 | 30 | /** 31 | * Composed annotation that combines common web test configuration for the 32 | * Spring Events application. 33 | * 34 | * @author Sam Brannen 35 | * @since 1.0 36 | */ 37 | @Target(ElementType.TYPE) 38 | @Retention(RetentionPolicy.RUNTIME) 39 | @Documented 40 | @Inherited 41 | 42 | @SpringBootTest 43 | @AutoConfigureMockMvc // (print = MockMvcPrint.SYSTEM_ERR) 44 | @Transactional 45 | public @interface SpringEventsWebTest { 46 | } 47 | --------------------------------------------------------------------------------