├── .gitignore ├── LICENSE ├── NOTICE ├── README.md ├── build.gradle ├── ci.sh ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src ├── main ├── java │ └── hello │ │ ├── Application.java │ │ ├── DiffSyncConfig.java │ │ ├── JpaPersistenceCallback.java │ │ ├── Todo.java │ │ ├── TodoController.java │ │ ├── TodoRepository.java │ │ └── WebInitializer.java └── resources │ ├── application.properties │ └── public │ ├── .gitignore │ ├── TodosController.js │ ├── base.css │ ├── bower.json │ ├── index.html │ └── main.js └── test ├── java └── hello │ ├── EmbeddedDataSourceConfig.java │ └── MainControllerTest.java └── resources └── hello ├── patch-add-new-item.json ├── patch-change-single-status-and-desc.json ├── patch-change-single-status.json ├── patch-change-status-and-delete-two-items.json ├── patch-change-two-status-and-desc.json ├── patch-delete-twoitems-and-change-status-on-another.json ├── patch-failing-operation-first.json ├── patch-failing-operation-in-middle.json ├── patch-many-successful-operations.json ├── patch-modify-then-remove-item.json ├── patch-remove-item.json ├── patch-remove-two-items.json └── testdb.sql /.gitignore: -------------------------------------------------------------------------------- 1 | # Operating System Files 2 | 3 | *.DS_Store 4 | Thumbs.db 5 | *.sw? 6 | .#* 7 | *# 8 | *~ 9 | *.sublime-* 10 | 11 | # Build Artifacts 12 | 13 | .gradle/ 14 | build/ 15 | target/ 16 | bin/ 17 | manifest.yml 18 | 19 | # Eclipse Project Files 20 | 21 | .classpath 22 | .project 23 | .settings/ 24 | 25 | # IntelliJ IDEA Files 26 | 27 | *.iml 28 | *.ipr 29 | *.iws 30 | *.idea 31 | 32 | # Client Files 33 | /bower_components/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014 Roy Clarkson. All Rights Reserved. 2 | 3 | This product is licensed to you under the Apache License, Version 2.0 (the "License"). 4 | You may not use this product except in compliance with the License. 5 | 6 | This product may include a number of subcomponents with separate copyright notices 7 | and license terms. Your use of these subcomponents is subject to the terms and 8 | conditions of the subcomponent's license, as noted in the LICENSE file. 9 | 10 | This software downloads additional open source software components upon install 11 | that are distributed under separate terms and conditions. Please see the license 12 | information provided in the individual software components for more information. 13 | 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spring REST Todos 2 | 3 | [![Build Status](https://drone.io/github.com/royclarkson/spring-rest-todos/status.png)](https://drone.io/github.com/royclarkson/spring-rest-todos/latest) 4 | 5 | A simple todo list example built with Spring 6 | 7 | ## Build and Run 8 | 9 | > **NOTE:** 10 | > This project now depends on org.springframework:spring-sync:0.5.0.RELEASE. This project is not (yet) in any known Maven repository. Therefore, you'll need to clone it from https://github.com/habuma/spring-sync and do 'gradle build install' to get it into your local repository. 11 | 12 | ```sh 13 | ./gradlew clean build bootRun 14 | ``` 15 | 16 | ## Test 17 | 18 | The following curl commands can be used to test the API. 19 | 20 | Request the list of todos: 21 | 22 | ```sh 23 | curl -X "GET" -v localhost:8080/todos 24 | ``` 25 | 26 | Add a new todo: 27 | 28 | ```sh 29 | curl -X "POST" -v localhost:8080/todos -H "Content-Type: application/json" -d '{"description":"A Todo","complete":false}' 30 | ``` 31 | 32 | Modify an existing todo: 33 | 34 | ```sh 35 | curl -X "PUT" -v localhost:8080/todos/0 -H "Content-Type: application/json" -d '{"description":"Modified Todo","complete":false}' 36 | ``` 37 | 38 | Delete a todo: 39 | 40 | ```sh 41 | curl -X "DELETE" -v localhost:8080/todos/0 42 | ``` 43 | 44 | Apply a JSON PATCH to the todo list: 45 | 46 | ```sh 47 | curl -X "PATCH" -v localhost:8080/todos -H "Content-Type: application/json" -d '[{"op":"replace","path":"/0/description","value":"go go go!"}]' 48 | ``` 49 | 50 | Generate a JSON PATCH from a modified todo list: 51 | 52 | ```sh 53 | curl -X "POST" -v localhost:8080/todos/diff -H "Content-Type: application/json" -d '[{"description":"go go go!","complete":false},{"description":"b","complete":false}]' 54 | ``` 55 | 56 | ## Run the Web Client 57 | 58 | ### Setup 59 | 60 | ```sh 61 | npm install -g bower 62 | cd public 63 | bower install 64 | ``` 65 | 66 | ### Open in Browser 67 | 68 | Go to http://localhost:8080/index.html -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | maven { url "http://repo.spring.io/libs-release" } 4 | mavenLocal() 5 | } 6 | dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.1.4.RELEASE") } 7 | } 8 | 9 | apply plugin: "java" 10 | apply plugin: "eclipse" 11 | apply plugin: "eclipse-wtp" 12 | apply plugin: "idea" 13 | apply plugin: "spring-boot" 14 | apply plugin: "war" 15 | 16 | sourceCompatibility = 1.7 17 | targetCompatibility = 1.7 18 | 19 | jar { 20 | baseName = "spring-rest-todos" 21 | version = "0.1.0" 22 | } 23 | 24 | repositories { 25 | mavenLocal() 26 | mavenCentral() 27 | maven { url "http://repo.spring.io/libs-snapshot" } 28 | maven { url "http://repo.spring.io/libs-release" } 29 | } 30 | 31 | dependencies { 32 | compile("org.springframework.boot:spring-boot-starter-web") 33 | compile("org.springframework.boot:spring-boot-starter-data-jpa") 34 | compile("org.springframework.sync:spring-sync:1.0.0.BUILD-SNAPSHOT") 35 | compile("com.h2database:h2") 36 | compile("com.fasterxml.jackson.core:jackson-databind") 37 | compile("commons-lang:commons-lang:2.6") 38 | compile fileTree(dir: 'libs', include: '*.jar') 39 | compile("com.github.fge:jackson-coreutils:1.5") 40 | 41 | 42 | compile("com.googlecode.java-diff-utils:diffutils:1.2.1") 43 | 44 | 45 | testCompile("org.springframework.boot:spring-boot-starter-test") 46 | testCompile("com.jayway.jsonpath:json-path:0.8.1") 47 | testCompile("com.jayway.jsonpath:json-path-assert:0.8.1") 48 | } 49 | 50 | task wrapper(type: Wrapper) { gradleVersion = "2.0" } 51 | 52 | task clientInstall(type:Exec) { 53 | logging.captureStandardOutput LogLevel.INFO 54 | logging.captureStandardError LogLevel.LIFECYCLE 55 | workingDir './src/main/resources/public' 56 | commandLine 'bower', 'install' 57 | } 58 | 59 | war.dependsOn clientInstall 60 | -------------------------------------------------------------------------------- /ci.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | cd $(dirname $0) 3 | 4 | ./gradlew clean build 5 | ret=$? 6 | if [ $ret -ne 0 ]; then 7 | exit $ret 8 | fi 9 | rm -rf build 10 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/royclarkson/spring-rest-todos/22dde7bdf8c49d2f57c549c3f869a0387a4a11a7/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Jul 30 10:46:53 CDT 2014 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.0-bin.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /src/main/java/hello/Application.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 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 hello; 18 | 19 | import java.util.List; 20 | 21 | import org.springframework.boot.SpringApplication; 22 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 23 | import org.springframework.context.ApplicationContext; 24 | import org.springframework.context.annotation.Bean; 25 | import org.springframework.context.annotation.ComponentScan; 26 | import org.springframework.http.converter.HttpMessageConverter; 27 | import org.springframework.sync.diffsync.web.JsonPatchHttpMessageConverter; 28 | import org.springframework.web.filter.ShallowEtagHeaderFilter; 29 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 30 | 31 | @ComponentScan 32 | @EnableAutoConfiguration 33 | public class Application extends WebMvcConfigurerAdapter { 34 | 35 | public static void main(String[] args) { 36 | ApplicationContext ctx = SpringApplication.run(Application.class, args); 37 | TodoRepository repository = ctx.getBean(TodoRepository.class); 38 | repository.save(new Todo(1L, "a", false)); 39 | repository.save(new Todo(2L, "b", false)); 40 | repository.save(new Todo(3L, "c", false)); 41 | } 42 | 43 | @Bean 44 | public ShallowEtagHeaderFilter etagFilter() { 45 | return new ShallowEtagHeaderFilter(); 46 | } 47 | 48 | @Override 49 | public void configureMessageConverters(List> converters) { 50 | converters.add(new JsonPatchHttpMessageConverter()); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/hello/DiffSyncConfig.java: -------------------------------------------------------------------------------- 1 | package hello; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.data.repository.PagingAndSortingRepository; 6 | import org.springframework.sync.diffsync.PersistenceCallbackRegistry; 7 | import org.springframework.sync.diffsync.config.DiffSyncConfigurerAdapter; 8 | import org.springframework.sync.diffsync.config.EnableDifferentialSynchronization; 9 | 10 | @Configuration 11 | @EnableDifferentialSynchronization 12 | public class DiffSyncConfig extends DiffSyncConfigurerAdapter { 13 | 14 | @Autowired 15 | private PagingAndSortingRepository repo; 16 | 17 | @Override 18 | public void addPersistenceCallbacks(PersistenceCallbackRegistry registry) { 19 | registry.addPersistenceCallback(new JpaPersistenceCallback(repo, Todo.class)); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/hello/JpaPersistenceCallback.java: -------------------------------------------------------------------------------- 1 | package hello; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.data.domain.Sort; 6 | import org.springframework.data.repository.PagingAndSortingRepository; 7 | import org.springframework.sync.diffsync.PersistenceCallback; 8 | 9 | class JpaPersistenceCallback implements PersistenceCallback { 10 | 11 | private final PagingAndSortingRepository repo; 12 | private Class entityType; 13 | 14 | public JpaPersistenceCallback(PagingAndSortingRepository repo, Class entityType) { 15 | this.repo = repo; 16 | this.entityType = entityType; 17 | } 18 | 19 | @Override 20 | public List findAll() { 21 | return (List) repo.findAll(new Sort("id")); 22 | } 23 | 24 | @Override 25 | public T findOne(String id) { 26 | return repo.findOne(Long.valueOf(id)); 27 | } 28 | 29 | @Override 30 | public void persistChange(T itemToSave) { 31 | repo.save(itemToSave); 32 | } 33 | 34 | @Override 35 | public void persistChanges(List itemsToSave, List itemsToDelete) { 36 | repo.save(itemsToSave); 37 | repo.delete(itemsToDelete); 38 | } 39 | 40 | @Override 41 | public Class getEntityType() { 42 | return entityType; 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /src/main/java/hello/Todo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 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 hello; 18 | 19 | import java.io.Serializable; 20 | 21 | import javax.persistence.Entity; 22 | import javax.persistence.GeneratedValue; 23 | import javax.persistence.GenerationType; 24 | import javax.persistence.Id; 25 | 26 | import org.apache.commons.lang.builder.EqualsBuilder; 27 | import org.apache.commons.lang.builder.HashCodeBuilder; 28 | 29 | /** 30 | * @author Roy Clarkson 31 | * @author Craig Walls 32 | */ 33 | @Entity 34 | public class Todo implements Serializable { 35 | 36 | private static final long serialVersionUID = 1L; 37 | 38 | @Id 39 | @GeneratedValue(strategy = GenerationType.AUTO) 40 | private Long id; 41 | 42 | private String description; 43 | 44 | private boolean complete; 45 | 46 | public void setId(Long id) { 47 | this.id = id; 48 | } 49 | 50 | public Long getId() { 51 | return id; 52 | } 53 | 54 | public String getDescription() { 55 | return description; 56 | } 57 | 58 | public void setDescription(String description) { 59 | this.description = description; 60 | } 61 | 62 | public boolean isComplete() { 63 | return complete; 64 | } 65 | 66 | public void setComplete(boolean complete) { 67 | this.complete = complete; 68 | } 69 | 70 | public Todo() { 71 | } 72 | 73 | public Todo(Long id, String description, boolean complete) { 74 | this.id = id; 75 | this.description = description; 76 | this.complete = complete; 77 | } 78 | 79 | @Override 80 | public String toString() { 81 | return "[ id=" + this.id + ", description=" + this.description + ", complete=" + this.complete + " ]"; 82 | } 83 | 84 | @Override 85 | public boolean equals(Object other) { 86 | return EqualsBuilder.reflectionEquals(this, other); 87 | } 88 | 89 | @Override 90 | public int hashCode() { 91 | return HashCodeBuilder.reflectionHashCode(this); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/main/java/hello/TodoController.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 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 hello; 18 | 19 | import java.io.IOException; 20 | 21 | import org.springframework.beans.factory.annotation.Autowired; 22 | import org.springframework.http.HttpHeaders; 23 | import org.springframework.http.HttpStatus; 24 | import org.springframework.http.ResponseEntity; 25 | import org.springframework.transaction.annotation.Transactional; 26 | import org.springframework.web.bind.annotation.PathVariable; 27 | import org.springframework.web.bind.annotation.RequestBody; 28 | import org.springframework.web.bind.annotation.RequestMapping; 29 | import org.springframework.web.bind.annotation.RequestMethod; 30 | import org.springframework.web.bind.annotation.ResponseStatus; 31 | import org.springframework.web.bind.annotation.RestController; 32 | 33 | /** 34 | * @author Roy Clarkson 35 | * @author Craig Walls 36 | * @author Greg L. Turnquist 37 | */ 38 | @RestController 39 | @RequestMapping("/todos") 40 | public class TodoController { 41 | 42 | private TodoRepository repository; 43 | 44 | @Autowired 45 | public TodoController(TodoRepository repository) { 46 | this.repository = repository; 47 | } 48 | 49 | @RequestMapping(method = RequestMethod.GET, produces = "application/json") 50 | public ResponseEntity> list() { 51 | HttpHeaders headers = new HttpHeaders(); 52 | headers.add("Accept-Patch", "application/json-patch+json"); 53 | return new ResponseEntity>(repository.findAll(), headers, HttpStatus.OK); 54 | } 55 | 56 | @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") 57 | public Todo create(@RequestBody Todo todo) { 58 | return repository.save(todo); 59 | } 60 | 61 | @RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = "application/json") 62 | @ResponseStatus(HttpStatus.NO_CONTENT) 63 | @Transactional 64 | public void update(@RequestBody Todo updatedTodo, @PathVariable("id") long id) throws IOException { 65 | if (id != updatedTodo.getId()) { 66 | repository.delete(id); 67 | } 68 | repository.save(updatedTodo); 69 | } 70 | 71 | @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) 72 | @ResponseStatus(HttpStatus.NO_CONTENT) 73 | public void delete(@PathVariable("id") long id) { 74 | repository.delete(id); 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/hello/TodoRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 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 hello; 18 | 19 | import org.springframework.data.repository.PagingAndSortingRepository; 20 | 21 | /** 22 | * @author Craig Walls 23 | * @author Greg L. Turnquist 24 | */ 25 | public interface TodoRepository extends PagingAndSortingRepository {} 26 | -------------------------------------------------------------------------------- /src/main/java/hello/WebInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 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 hello; 18 | 19 | import org.springframework.boot.builder.SpringApplicationBuilder; 20 | import org.springframework.boot.context.web.SpringBootServletInitializer; 21 | 22 | public class WebInitializer extends SpringBootServletInitializer { 23 | 24 | @Override 25 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 26 | return application.sources(Application.class); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.diffsync.path=/sync 2 | -------------------------------------------------------------------------------- /src/main/resources/public/.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules/ 2 | /bower_components/ 3 | /.idea/ 4 | -------------------------------------------------------------------------------- /src/main/resources/public/TodosController.js: -------------------------------------------------------------------------------- 1 | module.exports = TodosController; 2 | 3 | //var counter = 1; 4 | //var base = '' + Date.now() + Math.floor(Math.random() * 1000); 5 | 6 | function TodosController(todos) { 7 | this.todos = todos; 8 | } 9 | 10 | TodosController.prototype.add = function(todo) { 11 | // todo.id = base + (counter++); 12 | this.todos.push(todo); 13 | }; 14 | 15 | TodosController.prototype.remove = function(todo) { 16 | this.todos.some(function(t, i, todos) { 17 | if(todo.id === t.id) { 18 | todos.splice(i, 1); 19 | return true; 20 | } 21 | }); 22 | }; 23 | 24 | TodosController.prototype.removeCompleted = function() { 25 | this.todos = this.todos.filter(function(todo) { 26 | return !todo.complete; 27 | }); 28 | }; 29 | 30 | TodosController.prototype.completeAll = function() { 31 | this.todos.forEach(function(todo) { 32 | todo.complete = true; 33 | }); 34 | }; 35 | -------------------------------------------------------------------------------- /src/main/resources/public/base.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; 3 | font-size: 1.2em; 4 | padding: 0; 5 | margin: 0; 6 | } 7 | ul { 8 | list-style: none; 9 | margin: 0; 10 | padding: 0; 11 | } 12 | fieldset { 13 | border: none; 14 | margin: 0; 15 | display: inline-block; 16 | } 17 | input { 18 | font-size: 1em; 19 | outline: none; 20 | } 21 | input[type="text"] { 22 | font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; 23 | border: none; 24 | margin: .25em; 25 | padding: .25em .5em; 26 | background: transparent; 27 | } 28 | 29 | ::-webkit-input-placeholder { color: white; opacity: .2; } 30 | :-moz-placeholder { color: white; opacity: .2; } 31 | ::-moz-placeholder { color: white; opacity: .2; } 32 | :-ms-input-placeholder { color: white; opacity: .2; } 33 | 34 | input[type="checkbox"] { 35 | margin: 0; 36 | padding: 0; 37 | } 38 | button { 39 | font-size: inherit; 40 | padding: 0; 41 | margin: 0; 42 | border: none; 43 | background: transparent; 44 | } 45 | 46 | .todo-app input, .todo-app button { 47 | padding: .5em; 48 | } 49 | 50 | .todo-app { 51 | margin: auto; 52 | width: 100%; 53 | } 54 | 55 | .create-todo { 56 | background: #48f; 57 | padding: .5em 1em; 58 | } 59 | .create-todo fieldset { 60 | float: right; 61 | padding: .25em 0; 62 | } 63 | .create-todo input { 64 | color: white; 65 | width: 40%; 66 | } 67 | .create-todo button { 68 | color: #fff; 69 | } 70 | .create-todo .toggle { 71 | float: none; 72 | margin: 0; 73 | } 74 | 75 | .todo-app .toggle { 76 | text-align: center; 77 | height: auto; 78 | margin: auto 0; 79 | /* Mobile Safari */ 80 | border: none; 81 | -webkit-appearance: none; 82 | -ms-appearance: none; 83 | -o-appearance: none; 84 | appearance: none; 85 | } 86 | 87 | .toggle:after { 88 | content: '✓'; 89 | } 90 | 91 | .todo-list .toggle:after { 92 | color: #ddd; 93 | } 94 | 95 | .todo-app .toggle:checked:after { 96 | color: #4c6; 97 | } 98 | 99 | .todo-item { 100 | padding: .5em 1em; 101 | } 102 | .todo-item input[type="text"] { 103 | width: 60%; 104 | } 105 | .todo-item .remove { 106 | color: #ddd; 107 | float: right; 108 | margin: .5em; 109 | } 110 | .todo-item:hover .remove { 111 | cursor: pointer; 112 | } 113 | 114 | @media only screen and (min-width : 651px) { 115 | body { 116 | font-size: 1.5em; 117 | } 118 | .create-todo input { 119 | width: 50%; 120 | } 121 | } 122 | 123 | @media only screen and (min-width : 801px) { 124 | .todo-app { 125 | width: 70%; 126 | } 127 | } 128 | 129 | @media only screen and (min-width : 1025px) { 130 | .todo-app { 131 | width: 60%; 132 | } 133 | .create-todo input { 134 | width: 60%; 135 | } 136 | } 137 | 138 | @media only screen and (min-width : 1281px) { 139 | .todo-app { 140 | width: 50%; 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /src/main/resources/public/bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "spring-rest-todos", 3 | "version": "0.0.0", 4 | "description": "", 5 | "main": "main.js", 6 | "moduleType": ["node"], 7 | "scripts": { 8 | "test": "echo \"Error: no test specified\" && exit 1" 9 | }, 10 | "author": "brian@hovercraftstudios.com", 11 | "license": "MIT", 12 | "dependencies": { 13 | "fabulous": "briancavalier/fabulous#master", 14 | "jiff": "~0.6", 15 | "rave": "~0.4", 16 | "rest": "^1.2", 17 | "when": "~3.5" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/resources/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Fabulous Spring REST Todos 7 | 8 | 9 | 10 | 11 | 12 |
13 |
14 | 15 | 16 | 17 |
18 | 19 | 20 |
21 |
22 | 23 |
    24 |
  • 25 | 26 | 27 | 28 | × 29 |
  • 30 |
31 | 32 |
33 | 34 | 35 | -------------------------------------------------------------------------------- /src/main/resources/public/main.js: -------------------------------------------------------------------------------- 1 | var fab = require('fabulous'); 2 | var rest = require('fabulous/rest'); 3 | var Document = require('fabulous/Document'); 4 | 5 | var TodosController = require('./TodosController'); 6 | 7 | exports.main = fab.run(todosApp); 8 | 9 | function todosApp(node, context) { 10 | context.controller = new TodosController([]); 11 | 12 | var todosClient = rest.at('/todos'); 13 | var patchClient = rest.at('/sync/todos'); 14 | 15 | Document.sync([ 16 | Document.fromPatchSyncRemote(function(patch) { 17 | return patchClient.patch({ entity: patch }).entity(); 18 | }, todosClient.get().entity()), 19 | Document.fromProperty('todos', context.controller) 20 | ]); 21 | } 22 | 23 | -------------------------------------------------------------------------------- /src/test/java/hello/EmbeddedDataSourceConfig.java: -------------------------------------------------------------------------------- 1 | package hello; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import javax.sql.DataSource; 7 | 8 | import org.hibernate.dialect.H2Dialect; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 12 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; 13 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; 14 | import org.springframework.orm.jpa.JpaTransactionManager; 15 | import org.springframework.orm.jpa.JpaVendorAdapter; 16 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; 17 | import org.springframework.orm.jpa.vendor.Database; 18 | import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; 19 | import org.springframework.transaction.PlatformTransactionManager; 20 | 21 | @Configuration 22 | @EnableJpaRepositories(basePackages="hello") 23 | public class EmbeddedDataSourceConfig { 24 | 25 | @Bean 26 | public DataSource dataSource() { 27 | return new EmbeddedDatabaseBuilder() 28 | .setType(EmbeddedDatabaseType.H2) 29 | .addScript("classpath:/hello/testdb.sql").build(); 30 | } 31 | 32 | 33 | @Bean 34 | public Map jpaProperties() { 35 | Map props = new HashMap(); 36 | props.put("hibernate.dialect", H2Dialect.class.getName()); 37 | return props; 38 | } 39 | 40 | @Bean 41 | public JpaVendorAdapter jpaVendorAdapter() { 42 | HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter(); 43 | hibernateJpaVendorAdapter.setShowSql(false); 44 | hibernateJpaVendorAdapter.setGenerateDdl(true); 45 | hibernateJpaVendorAdapter.setDatabase(Database.H2); 46 | return hibernateJpaVendorAdapter; 47 | } 48 | 49 | @Bean 50 | public PlatformTransactionManager transactionManager() { 51 | return new JpaTransactionManager( entityManagerFactory().getObject() ); 52 | } 53 | 54 | @Bean 55 | public LocalContainerEntityManagerFactoryBean entityManagerFactory() { 56 | LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean(); 57 | lef.setDataSource(dataSource()); 58 | lef.setJpaPropertyMap(this.jpaProperties()); 59 | lef.setJpaVendorAdapter(this.jpaVendorAdapter()); 60 | lef.setPackagesToScan("hello"); 61 | return lef; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/test/java/hello/MainControllerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 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 hello; 18 | 19 | import static org.hamcrest.Matchers.*; 20 | import static org.mockito.Mockito.*; 21 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; 22 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; 23 | 24 | import java.util.Arrays; 25 | 26 | import org.junit.Before; 27 | import org.junit.Ignore; 28 | import org.junit.Test; 29 | import org.junit.runner.RunWith; 30 | import org.mockito.InjectMocks; 31 | import org.mockito.Mock; 32 | import org.mockito.Mockito; 33 | import org.mockito.MockitoAnnotations; 34 | import org.springframework.beans.factory.annotation.Autowired; 35 | import org.springframework.http.MediaType; 36 | import org.springframework.test.context.ContextConfiguration; 37 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 38 | import org.springframework.test.context.web.WebAppConfiguration; 39 | import org.springframework.test.web.servlet.MockMvc; 40 | import org.springframework.test.web.servlet.setup.MockMvcBuilders; 41 | import org.springframework.web.context.WebApplicationContext; 42 | 43 | import com.fasterxml.jackson.databind.ObjectMapper; 44 | 45 | /** 46 | * @author Roy Clarkson 47 | */ 48 | @RunWith(SpringJUnit4ClassRunner.class) 49 | @WebAppConfiguration 50 | @ContextConfiguration(classes = Application.class) 51 | @Ignore 52 | public class MainControllerTest { 53 | 54 | @Autowired 55 | private WebApplicationContext context; 56 | 57 | @Mock 58 | private TodoRepository repository; 59 | 60 | @InjectMocks 61 | TodoController mainController; 62 | 63 | private MockMvc mvc; 64 | 65 | @Before 66 | public void setUp() { 67 | MockitoAnnotations.initMocks(this); 68 | mvc = MockMvcBuilders.standaloneSetup(mainController).build(); 69 | } 70 | 71 | @Test 72 | public void testList() throws Exception { 73 | final Todo a = new Todo(1L, "a", false); 74 | final Todo b = new Todo(2L, "b", false); 75 | final Todo c = new Todo(3L, "c", false); 76 | when(repository.findAll()).thenReturn(Arrays.asList(a, b, c)); 77 | 78 | mvc.perform(get("/todos") 79 | .accept(MediaType.APPLICATION_JSON)) 80 | .andExpect(status().isOk()) 81 | .andExpect(jsonPath("$", hasSize(3))) 82 | .andExpect(jsonPath("$[0].id", is(1))) 83 | .andExpect(jsonPath("$[0].description", is("a"))) 84 | .andExpect(jsonPath("$[0].complete", is(false))) 85 | .andExpect(jsonPath("$[1].id", is(2))) 86 | .andExpect(jsonPath("$[1].description", is("b"))) 87 | .andExpect(jsonPath("$[1].complete", is(false))) 88 | .andExpect(jsonPath("$[2].id", is(3))) 89 | .andExpect(jsonPath("$[2].description", is("c"))) 90 | .andExpect(jsonPath("$[2].complete", is(false))); 91 | 92 | verify(repository, times(1)).findAll(); 93 | verifyNoMoreInteractions(repository); 94 | } 95 | 96 | @Ignore 97 | @Test 98 | public void testPatch() throws Exception { 99 | 100 | } 101 | 102 | @Test 103 | public void testCreate() throws Exception { 104 | final Todo todo = new Todo(1L, "a", false); 105 | ObjectMapper objectMapper = new ObjectMapper(); 106 | final byte[] bytes = objectMapper.writeValueAsBytes(todo); 107 | 108 | when(repository.save(Mockito.any(Todo.class))).thenReturn(todo); 109 | 110 | mvc.perform(post("/todos") 111 | .accept(MediaType.APPLICATION_JSON) 112 | .contentType(MediaType.APPLICATION_JSON) 113 | .content(bytes)) 114 | .andExpect(status().isOk()) 115 | .andExpect(jsonPath("$.id", is(1))) 116 | .andExpect(jsonPath("$.description", is("a"))) 117 | .andExpect(jsonPath("$.complete", is(false))); 118 | 119 | verify(repository, times(1)).save(Mockito.any(Todo.class)); 120 | verifyNoMoreInteractions(repository); 121 | } 122 | 123 | @Test 124 | public void testUpdateSameIds() throws Exception { 125 | final Todo updatedTodo = new Todo(1L, "z", true); 126 | ObjectMapper objectMapper = new ObjectMapper(); 127 | byte[] bytes = objectMapper.writeValueAsBytes(updatedTodo); 128 | 129 | when(repository.save(Mockito.any(Todo.class))).thenReturn(updatedTodo); 130 | 131 | mvc.perform(put("/todos/{id}", 1L) 132 | .contentType(MediaType.APPLICATION_JSON) 133 | .content(bytes)) 134 | .andExpect(status().isNoContent()); 135 | 136 | verify(repository, times(0)).delete(1L); 137 | verify(repository, times(1)).save(Mockito.any(Todo.class)); 138 | verifyNoMoreInteractions(repository); 139 | } 140 | 141 | @Test 142 | public void testUpdateDifferentIds() throws Exception { 143 | final Todo updatedTodo = new Todo(99L, "z", true); 144 | ObjectMapper objectMapper = new ObjectMapper(); 145 | byte[] bytes = objectMapper.writeValueAsBytes(updatedTodo); 146 | 147 | when(repository.save(Mockito.any(Todo.class))).thenReturn(updatedTodo); 148 | 149 | mvc.perform(put("/todos/{id}", 1L) 150 | .contentType(MediaType.APPLICATION_JSON) 151 | .content(bytes)) 152 | .andExpect(status().isNoContent()); 153 | 154 | verify(repository, times(1)).delete(1L); 155 | verify(repository, times(1)).save(Mockito.any(Todo.class)); 156 | verifyNoMoreInteractions(repository); 157 | } 158 | 159 | @Test 160 | public void testDelete() throws Exception { 161 | // this is how to test a void method with Mockito 162 | // doThrow(new IllegalArgumentException()).when(repository).delete(null); 163 | 164 | mvc.perform(delete("/todos/{id}", 1L)) 165 | .andExpect(status().isNoContent()); 166 | } 167 | 168 | } -------------------------------------------------------------------------------- /src/test/resources/hello/patch-add-new-item.json: -------------------------------------------------------------------------------- 1 | [{"op":"add","path":"/3","value":{"description":"D","complete":false}}] -------------------------------------------------------------------------------- /src/test/resources/hello/patch-change-single-status-and-desc.json: -------------------------------------------------------------------------------- 1 | [{"op":"test", "path":"/1/complete", "value":false}, {"op":"replace", "path":"/1/complete", "value":true}, {"op":"replace", "path":"/1/description", "value":"BBB"}] 2 | -------------------------------------------------------------------------------- /src/test/resources/hello/patch-change-single-status.json: -------------------------------------------------------------------------------- 1 | [{"op":"test", "path":"/1/complete", "value":false}, {"op":"replace", "path":"/1/complete", "value":true}] 2 | -------------------------------------------------------------------------------- /src/test/resources/hello/patch-change-status-and-delete-two-items.json: -------------------------------------------------------------------------------- 1 | [{"op":"test", "path":"/0/complete", "value":false}, {"op":"replace", "path":"/0/complete", "value":true},{"op":"test","path":"/1","value":{"id":2,"description":"B","complete":false}},{"op":"remove","path":"/1"},{"op":"test","path":"/1","value":{"id":3,"description":"C","complete":false}},{"op":"remove","path":"/1"}] -------------------------------------------------------------------------------- /src/test/resources/hello/patch-change-two-status-and-desc.json: -------------------------------------------------------------------------------- 1 | [{"op":"test", "path":"/1/complete", "value":false}, {"op":"replace", "path":"/1/complete", "value":true}, {"op":"replace", "path":"/0/description", "value":"AAA"}] 2 | -------------------------------------------------------------------------------- /src/test/resources/hello/patch-delete-twoitems-and-change-status-on-another.json: -------------------------------------------------------------------------------- 1 | [ 2 | {"op":"test","path":"/0","value":{"id":1,"description":"A","complete":false}}, 3 | {"op":"remove","path":"/0"}, 4 | {"op":"test","path":"/0","value":{"id":2,"description":"B","complete":false}}, 5 | {"op":"remove","path":"/0"}, 6 | {"op":"test", "path":"/0/complete", "value":false}, 7 | {"op":"replace", "path":"/0/complete", "value":true} 8 | ] -------------------------------------------------------------------------------- /src/test/resources/hello/patch-failing-operation-first.json: -------------------------------------------------------------------------------- 1 | [ 2 | {"op":"test", "path":"/5/description", "value":"A"}, 3 | {"op":"remove", "path":"/5"}, 4 | {"op":"replace", "path":"/1/complete", "value":true}, 5 | {"op":"copy", "path":"/3/description", "from":"/2/description"}, 6 | {"op":"copy", "path":"/4", "from":"/0"} 7 | ] -------------------------------------------------------------------------------- /src/test/resources/hello/patch-failing-operation-in-middle.json: -------------------------------------------------------------------------------- 1 | [ 2 | {"op":"test", "path":"/5/description", "value":"A"}, 3 | {"op":"remove", "path":"/5"}, 4 | {"op":"replace", "path":"/1/complete", "value":true}, 5 | {"op":"test", "path":"/0/description", "value":"HUH"}, 6 | {"op":"copy", "path":"/3/description", "from":"/2/description"}, 7 | {"op":"copy", "path":"/4", "from":"/0"} 8 | ] -------------------------------------------------------------------------------- /src/test/resources/hello/patch-many-successful-operations.json: -------------------------------------------------------------------------------- 1 | [ 2 | {"op":"test", "path":"/0", "value":{"id":1,"description":"A","complete":true}}, 3 | {"op":"test", "path":"/5/description", "value":"F"}, 4 | {"op":"remove", "path":"/5"}, 5 | {"op":"replace", "path":"/1/complete", "value":true}, 6 | {"op":"copy", "path":"/3/description", "from":"/2/description"}, 7 | {"op":"copy", "path":"/4", "from":"/0"} 8 | ] -------------------------------------------------------------------------------- /src/test/resources/hello/patch-modify-then-remove-item.json: -------------------------------------------------------------------------------- 1 | [ 2 | {"op":"test", "path":"/1/complete", "value":false}, 3 | {"op":"replace", "path":"/1/complete", "value":true}, 4 | {"op":"remove", "path":"/1"} 5 | ] 6 | -------------------------------------------------------------------------------- /src/test/resources/hello/patch-remove-item.json: -------------------------------------------------------------------------------- 1 | [{"op":"test","path":"/1","value":{"id":2,"description":"B","complete":false}},{"op":"remove","path":"/1"}] -------------------------------------------------------------------------------- /src/test/resources/hello/patch-remove-two-items.json: -------------------------------------------------------------------------------- 1 | [{"op":"test","path":"/1","value":{"id":2,"description":"B","complete":false}},{"op":"remove","path":"/1"},{"op":"test","path":"/1","value":{"id":3,"description":"C","complete":false}},{"op":"remove","path":"/1"}] -------------------------------------------------------------------------------- /src/test/resources/hello/testdb.sql: -------------------------------------------------------------------------------- 1 | create table Todo ( 2 | id identity, 3 | description varchar(2000), 4 | complete boolean 5 | ); 6 | 7 | insert into Todo (description, complete) values ('A', false); 8 | insert into Todo (description, complete) values ('B', false); 9 | insert into Todo (description, complete) values ('C', false); 10 | --------------------------------------------------------------------------------