├── README.md ├── scores ├── .gitignore ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src │ ├── main │ ├── java │ │ └── scores │ │ │ ├── Application.java │ │ │ ├── Game.java │ │ │ ├── GameDayService.java │ │ │ ├── GameDayServiceImpl.java │ │ │ ├── MapBasedScoreRepository.java │ │ │ ├── ScoreRepository.java │ │ │ ├── ScoresController.java │ │ │ ├── UpdatePublicationAspect.java │ │ │ └── WebSocketStompConfig.java │ └── resources │ │ ├── application.properties │ │ ├── public │ │ ├── bower.json │ │ ├── main.css │ │ └── main.js │ │ └── templates │ │ └── scores.html │ └── test │ └── java │ └── scores │ └── ApplicationTests.java └── spring-rest-todos ├── .gitignore ├── LICENSE ├── NOTICE ├── README.md ├── build.gradle ├── ci.sh ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src ├── main ├── java │ └── todos │ │ ├── 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 └── todos │ ├── EmbeddedDataSourceConfig.java │ └── MainControllerTest.java └── resources └── todos ├── 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 /README.md: -------------------------------------------------------------------------------- 1 | spring-sync-samples 2 | =================== 3 | 4 | Samples demonstrating the use of Spring Sync 5 | -------------------------------------------------------------------------------- /scores/.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 | .gradle/** 15 | build/ 16 | target/ 17 | bin/ 18 | manifest.yml 19 | 20 | # Eclipse Project Files 21 | 22 | .classpath 23 | .project 24 | .settings/ 25 | 26 | # IntelliJ IDEA Files 27 | 28 | *.iml 29 | *.ipr 30 | *.iws 31 | *.idea 32 | 33 | # Client Files 34 | bower_components/ -------------------------------------------------------------------------------- /scores/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext { 3 | springBootVersion = '1.1.4.RELEASE' 4 | } 5 | repositories { 6 | mavenCentral() 7 | } 8 | dependencies { 9 | classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") 10 | } 11 | } 12 | 13 | apply plugin: 'java' 14 | apply plugin: 'eclipse' 15 | apply plugin: 'idea' 16 | apply plugin: 'spring-boot' 17 | 18 | jar { 19 | baseName = 'scores' 20 | version = '0.0.1-SNAPSHOT' 21 | } 22 | sourceCompatibility = 1.7 23 | targetCompatibility = 1.7 24 | 25 | repositories { 26 | mavenLocal() 27 | maven { url "http://repo.spring.io/libs-milestone" } 28 | maven { url "http://repo.spring.io/libs-release" } 29 | mavenCentral() 30 | } 31 | 32 | 33 | dependencies { 34 | compile("org.springframework.boot:spring-boot-starter-web") 35 | compile("org.springframework.boot:spring-boot-starter-websocket") 36 | compile("org.springframework.boot:spring-boot-starter-thymeleaf") 37 | compile("org.springframework.sync:spring-sync-core:1.0.0.BUILD-SNAPSHOT") 38 | compile("org.springframework:spring-messaging") 39 | 40 | compile("org.aspectj:aspectjweaver:1.8.1") 41 | 42 | testCompile("org.springframework.boot:spring-boot-starter-test") 43 | 44 | compile("org.webjars:jquery:2.0.3-1") 45 | compile("org.webjars:sockjs-client:0.3.4") 46 | compile("org.webjars:stomp-websocket:2.3.0") 47 | 48 | } 49 | 50 | eclipse { 51 | classpath { 52 | containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER') 53 | containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7' 54 | } 55 | } 56 | 57 | task wrapper(type: Wrapper) { 58 | gradleVersion = '2.0' 59 | } 60 | 61 | task clientInstall(type:Exec) { 62 | logging.captureStandardOutput LogLevel.INFO 63 | logging.captureStandardError LogLevel.LIFECYCLE 64 | workingDir './src/main/resources/public' 65 | commandLine 'bower', 'install' 66 | } 67 | 68 | build.dependsOn clientInstall 69 | bootRun.dependsOn clientInstall 70 | 71 | 72 | -------------------------------------------------------------------------------- /scores/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spring-attic/spring-sync-samples/548850ddccdc009c116eae453daabea16e934ae1/scores/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /scores/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Jul 31 16:10:39 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 | -------------------------------------------------------------------------------- /scores/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 | -------------------------------------------------------------------------------- /scores/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 | -------------------------------------------------------------------------------- /scores/src/main/java/scores/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 | package scores; 17 | 18 | import org.springframework.boot.SpringApplication; 19 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 20 | import org.springframework.context.annotation.ComponentScan; 21 | import org.springframework.context.annotation.Configuration; 22 | import org.springframework.scheduling.annotation.EnableScheduling; 23 | import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; 24 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 25 | 26 | @Configuration 27 | @ComponentScan 28 | @EnableScheduling 29 | @EnableAutoConfiguration 30 | public class Application extends WebMvcConfigurerAdapter { 31 | 32 | public static void main(String[] args) { 33 | SpringApplication.run(Application.class, args); 34 | } 35 | 36 | @Override 37 | public void addViewControllers(ViewControllerRegistry registry) { 38 | registry.addViewController("/").setViewName("scores"); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /scores/src/main/java/scores/Game.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 | package scores; 17 | 18 | import java.io.Serializable; 19 | 20 | public class Game implements Serializable { 21 | 22 | private static final long serialVersionUID = 1L; 23 | 24 | private Long id = null; 25 | 26 | private final String homeTeam; 27 | private final String awayTeam; 28 | private int homeTeamScore = 0; 29 | private int awayTeamScore = 0; 30 | 31 | public Game(String homeTeam, String awayTeam) { 32 | this.homeTeam = homeTeam; 33 | this.awayTeam = awayTeam; 34 | } 35 | 36 | public void setId(long id) { 37 | this.id = id; 38 | } 39 | 40 | public Long getId() { 41 | return id; 42 | } 43 | 44 | public String getHomeTeam() { 45 | return homeTeam; 46 | } 47 | 48 | public int getHomeTeamScore() { 49 | return homeTeamScore; 50 | } 51 | 52 | public void incrementHomeTeamScore(int points) { 53 | this.homeTeamScore += points; 54 | } 55 | 56 | public String getAwayTeam() { 57 | return awayTeam; 58 | } 59 | 60 | public int getAwayTeamScore() { 61 | return awayTeamScore; 62 | } 63 | 64 | public void incrementAwayTeamScore(int points) { 65 | this.awayTeamScore += points; 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /scores/src/main/java/scores/GameDayService.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 | package scores; 17 | 18 | import java.util.List; 19 | 20 | public interface GameDayService { 21 | 22 | public abstract List getScores(); 23 | 24 | } -------------------------------------------------------------------------------- /scores/src/main/java/scores/GameDayServiceImpl.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 | package scores; 17 | 18 | import java.util.List; 19 | 20 | import org.slf4j.Logger; 21 | import org.slf4j.LoggerFactory; 22 | import org.springframework.beans.factory.annotation.Autowired; 23 | import org.springframework.scheduling.annotation.Scheduled; 24 | import org.springframework.stereotype.Service; 25 | 26 | @Service 27 | public class GameDayServiceImpl implements GameDayService { 28 | 29 | private Logger logger = LoggerFactory.getLogger(GameDayServiceImpl.class); 30 | 31 | private ScoreRepository scoreRepo; 32 | 33 | @Autowired 34 | public GameDayServiceImpl(ScoreRepository scoreRepo) { 35 | this.scoreRepo = scoreRepo; 36 | } 37 | 38 | @Override 39 | public List getScores() { 40 | return scoreRepo.findAll(); 41 | } 42 | 43 | @Scheduled(fixedRate=5000) 44 | public void updateScores() { 45 | List scores = getScores(); // fetch data 46 | randomlyUpdate(scores); // update data 47 | scoreRepo.save(scores); // save data 48 | } 49 | 50 | // private helpers 51 | 52 | /* 53 | * The code in this method was extracted so that updateScoresRandomly could focus on the basics of 54 | * updating some data and saving it. This method is entirely focused on the task of updating the 55 | * data and is largely filled with random number generation. Its function is only passively 56 | * relevant to the concern of differential synchronization. 57 | */ 58 | private void randomlyUpdate(List scores) { 59 | // choose a game to update 60 | int gameIndex = (int)(Math.random() * scores.size()); 61 | 62 | // choose either a touchdown or a field goal 63 | int points = Math.random() > 0.6 ? 7 : 3; 64 | String pointType = points == 3 ? "field goal" : "touchdown"; 65 | 66 | // choose either home or away team 67 | double homeOrAway = Math.random(); 68 | 69 | // adjust score 70 | Game game = scores.get(gameIndex); 71 | if (homeOrAway > 0.5) { 72 | logger.info("The " + game.getHomeTeam() + " scored a " + pointType + " against the " + game.getAwayTeam()); 73 | game.incrementHomeTeamScore(points); 74 | } else { 75 | logger.info("The " + game.getAwayTeam() + " scored a " + pointType + " against the " + game.getHomeTeam()); 76 | game.incrementAwayTeamScore(points); 77 | } 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /scores/src/main/java/scores/MapBasedScoreRepository.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 | package scores; 17 | 18 | import java.io.Serializable; 19 | import java.util.ArrayList; 20 | import java.util.Arrays; 21 | import java.util.HashMap; 22 | import java.util.List; 23 | import java.util.Map; 24 | import java.util.concurrent.atomic.AtomicLong; 25 | 26 | import org.apache.commons.lang.SerializationUtils; 27 | import org.springframework.stereotype.Repository; 28 | 29 | @Repository 30 | public class MapBasedScoreRepository implements ScoreRepository { 31 | 32 | private AtomicLong nextId = new AtomicLong(1L); 33 | 34 | private Map games = new HashMap(); 35 | 36 | public MapBasedScoreRepository() { 37 | initializeGames(); 38 | } 39 | 40 | public List findAll() { 41 | return deepCloneList(new ArrayList(games.values())); 42 | } 43 | 44 | public Game findOne(Long id) { 45 | return games.get(id); 46 | } 47 | 48 | public void save(List games) { 49 | for (Game game : games) { 50 | save(game); 51 | } 52 | } 53 | 54 | public Game save(Game game) { 55 | if (game.getId() == null) { 56 | game.setId(nextId.incrementAndGet()); 57 | } 58 | 59 | games.put(game.getId(), game); 60 | 61 | return game; 62 | } 63 | 64 | // private helpers 65 | 66 | private void initializeGames() { 67 | List teamPool = new ArrayList(Arrays.asList(ALL_TEAMS)); 68 | while(!teamPool.isEmpty()) { 69 | String homeTeam = teamPool.get((int)(Math.random() * teamPool.size())); 70 | teamPool.remove(homeTeam); 71 | String awayTeam = teamPool.get((int)(Math.random() * teamPool.size())); 72 | teamPool.remove(awayTeam); 73 | save(new Game(homeTeam, awayTeam)); 74 | } 75 | } 76 | 77 | private List deepCloneList(List original) { 78 | List copy = new ArrayList(original.size()); 79 | for(Game t : original) { 80 | copy.add((Game) SerializationUtils.clone((Serializable) t)); 81 | } 82 | return copy; 83 | } 84 | 85 | private static final String[] ALL_TEAMS = { 86 | "Ravens", "Bengals", "Browns", "Steelers", 87 | "Texans", "Colts", "Jaguars", "Titans", 88 | "Bills", "Dolphins", "Patriots", "Jets", 89 | "Broncos", "Chiefs", "Raiders", "Chargers", 90 | "Bears", "Lions", "Packers", "Vikings", 91 | "Falcons", "Panthers", "Saints", "Buccaneers", 92 | "Cowboys", "Giants", "Eagles", "Redskins", 93 | "Cardinals", "49ers", "Seahawks", "Rams" 94 | }; 95 | 96 | } 97 | -------------------------------------------------------------------------------- /scores/src/main/java/scores/ScoreRepository.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 | package scores; 17 | 18 | import java.util.List; 19 | 20 | public interface ScoreRepository { 21 | 22 | List findAll(); 23 | 24 | Game findOne(Long id); 25 | 26 | void save(List games); 27 | 28 | Game save(Game game); 29 | 30 | } 31 | -------------------------------------------------------------------------------- /scores/src/main/java/scores/ScoresController.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 | package scores; 17 | 18 | import java.util.List; 19 | 20 | import org.springframework.beans.factory.annotation.Autowired; 21 | import org.springframework.messaging.simp.annotation.SubscribeMapping; 22 | import org.springframework.stereotype.Controller; 23 | 24 | @Controller 25 | public class ScoresController { 26 | 27 | private GameDayService service; 28 | 29 | @Autowired 30 | public ScoresController(GameDayService service) { 31 | this.service = service; 32 | } 33 | 34 | /* 35 | * For the client to get an initial list of game scores without waiting on the next update. 36 | * Could also have been done via a GET request, but where's the fun in that? 37 | */ 38 | @SubscribeMapping("/scores") 39 | public List scores() { 40 | return service.getScores(); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /scores/src/main/java/scores/UpdatePublicationAspect.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 | package scores; 17 | 18 | import java.util.List; 19 | 20 | import org.aspectj.lang.ProceedingJoinPoint; 21 | import org.aspectj.lang.annotation.Around; 22 | import org.aspectj.lang.annotation.Aspect; 23 | import org.springframework.beans.factory.annotation.Autowired; 24 | import org.springframework.messaging.simp.SimpMessagingTemplate; 25 | import org.springframework.stereotype.Component; 26 | import org.springframework.sync.Diff; 27 | import org.springframework.sync.Patch; 28 | import org.springframework.sync.json.JsonPatchPatchConverter; 29 | 30 | @Aspect 31 | @Component 32 | public class UpdatePublicationAspect { 33 | 34 | // TODO: Reconsider this aspect. Instead have GameDayService publish a score update via Reactor. 35 | // Rework this aspect into a handler for the update that sends to the client. 36 | 37 | private GameDayService service; 38 | private SimpMessagingTemplate messaging; 39 | 40 | @Autowired 41 | public UpdatePublicationAspect(GameDayService service, SimpMessagingTemplate messaging) { 42 | this.service = service; 43 | this.messaging = messaging; 44 | } 45 | 46 | @Around("execution(* save(..)) && args(updated)") 47 | public void publishChange(ProceedingJoinPoint jp, Object updated) throws Throwable { 48 | List original = service.getScores(); 49 | 50 | jp.proceed(); 51 | 52 | Patch diff = Diff.diff(original, updated); 53 | messaging.convertAndSend("/topic/scores", new JsonPatchPatchConverter().convert(diff)); 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /scores/src/main/java/scores/WebSocketStompConfig.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 | package scores; 17 | 18 | import org.springframework.context.annotation.Configuration; 19 | import org.springframework.messaging.simp.config.MessageBrokerRegistry; 20 | import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; 21 | import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; 22 | import org.springframework.web.socket.config.annotation.StompEndpointRegistry; 23 | 24 | @Configuration 25 | @EnableWebSocketMessageBroker 26 | public class WebSocketStompConfig extends AbstractWebSocketMessageBrokerConfigurer { 27 | 28 | @Override 29 | public void registerStompEndpoints(StompEndpointRegistry registry) { 30 | registry.addEndpoint("/scores").withSockJS(); 31 | } 32 | 33 | @Override 34 | public void configureMessageBroker(MessageBrokerRegistry registry) { 35 | registry.enableSimpleBroker("/queue", "/topic"); 36 | registry.setApplicationDestinationPrefixes("/app"); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /scores/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spring-attic/spring-sync-samples/548850ddccdc009c116eae453daabea16e934ae1/scores/src/main/resources/application.properties -------------------------------------------------------------------------------- /scores/src/main/resources/public/bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "scores", 3 | "version": "0.0.0", 4 | "homepage": "https://github.com/briancavalier/scores", 5 | "authors": [ 6 | "Brian Cavalier " 7 | ], 8 | "main": "main.js", 9 | "rave": { 10 | "overrides": { 11 | "stomp-websocket": { 12 | "main": "lib/stomp.min.js" 13 | }, 14 | "sockjs-client": { 15 | "moduleType": ["amd"] 16 | } 17 | } 18 | }, 19 | "moduleType": [ 20 | "node" 21 | ], 22 | "license": "MIT", 23 | "ignore": [ 24 | "**/.*", 25 | "node_modules", 26 | "bower_components", 27 | "test", 28 | "tests" 29 | ], 30 | "dependencies": { 31 | "rave": "~0.3", 32 | "fabulous": "briancavalier/fabulous", 33 | "sockjs-client": "bower-sockjs-client#~0.3.4", 34 | "stomp-websocket": "~2.3.3" 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /scores/src/main/resources/public/main.css: -------------------------------------------------------------------------------- 1 | body, html { 2 | margin: 0; 3 | padding: 0; 4 | } 5 | 6 | body { 7 | font-size: 2em; 8 | font-family: "Helvetica Neue", Helvetica, sans-serif; 9 | } 10 | 11 | div { 12 | margin: 0; 13 | padding: 0; 14 | } 15 | 16 | .scoreboard { 17 | font-weight: bold; 18 | text-align: center; 19 | } 20 | 21 | .scoreboard h2 { 22 | margin: 0; 23 | padding: .25em 0; 24 | background: black; 25 | color: white; 26 | text-align: center; 27 | width: auto; 28 | } 29 | 30 | .scoreboard ul { 31 | margin: 0; 32 | padding: 0; 33 | } 34 | 35 | .scoreboard li { 36 | list-style-type: none; 37 | } 38 | 39 | .game { 40 | border-top: 1px solid black; 41 | margin: 0; 42 | padding: 0; 43 | width: 100%; 44 | text-align: center; 45 | } 46 | 47 | .name, .score { 48 | margin: 0; 49 | padding: .5em; 50 | display: inline-block; 51 | text-align: right; 52 | } 53 | 54 | .name { 55 | width: 6em; 56 | } 57 | 58 | .score { 59 | text-align: left; 60 | } 61 | 62 | @media only screen and (min-width: 801px) { 63 | .game { 64 | border: none; 65 | display: inline-block; 66 | width: auto; 67 | margin: 0.5em; 68 | } 69 | .name { 70 | width: 5em; 71 | } 72 | .score { 73 | background: black; 74 | color: white; 75 | width: 2em; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /scores/src/main/resources/public/main.js: -------------------------------------------------------------------------------- 1 | var fab = require('fabulous'); 2 | var jiff = require('jiff'); 3 | var stomp = require('stomp-websocket'); 4 | var SockJS = require('sockjs-client'); 5 | 6 | module.exports = fab.runAt(document.querySelector('.scoreboard'), gameDayView); 7 | 8 | function gameDayView(node, context) { 9 | var stomp = Stomp.over(new SockJS('/scores')); 10 | 11 | stomp.connect('guest', 'guest', function() { 12 | stomp.subscribe("/app/scores", initialScores); 13 | stomp.subscribe("/topic/scores", updateScores); 14 | }); 15 | 16 | function initialScores(message) { 17 | context.games = JSON.parse(message.body); 18 | } 19 | 20 | function updateScores(message) { 21 | context.games = jiff.patch(JSON.parse(message.body), context.games); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /scores/src/main/resources/templates/scores.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Home 4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 |

Scoreboard

12 | 13 |
    14 |
  • 15 |
    16 | {{homeTeam}} 17 | {{homeTeamScore}} 18 |
    19 |
    20 | {{awayTeam}} 21 | {{awayTeamScore}} 22 |
    23 |
  • 24 |
25 |
26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /scores/src/test/java/scores/ApplicationTests.java: -------------------------------------------------------------------------------- 1 | package scores; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.test.context.web.WebAppConfiguration; 6 | import org.springframework.boot.test.SpringApplicationConfiguration; 7 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 8 | 9 | @RunWith(SpringJUnit4ClassRunner.class) 10 | @SpringApplicationConfiguration(classes = Application.class) 11 | @WebAppConfiguration 12 | public class ApplicationTests { 13 | 14 | @Test 15 | public void contextLoads() { 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /spring-rest-todos/.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/ -------------------------------------------------------------------------------- /spring-rest-todos/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 | -------------------------------------------------------------------------------- /spring-rest-todos/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 | -------------------------------------------------------------------------------- /spring-rest-todos/README.md: -------------------------------------------------------------------------------- 1 | # Spring REST Todos 2 | 3 | A simple todo list sample application built with Spring 4 | 5 | ## Prerequisites 6 | 7 | This sample app requires the [Bower](http://bower.io) package manager. Use npm to install Bower: 8 | 9 | ```sh 10 | npm install -g bower 11 | ``` 12 | 13 | Use Bower to install the required packages: 14 | 15 | ```sh 16 | cd src/main/resources/public 17 | bower install 18 | ``` 19 | 20 | ## Build and Run 21 | 22 | Use Gradle to build the Spring app: 23 | 24 | ```sh 25 | ./gradlew clean build bootRun 26 | ``` 27 | 28 | Open the following URL in your browser: 29 | 30 | http://localhost:8080/index.html 31 | 32 | ## Test 33 | 34 | The following curl commands can be used to test the API. 35 | 36 | Request the list of todos: 37 | 38 | ```sh 39 | curl -X "GET" -v localhost:8080/todos 40 | ``` 41 | 42 | Add a new todo: 43 | 44 | ```sh 45 | curl -X "POST" -v localhost:8080/todos -H "Content-Type: application/json" -d '{"description":"A Todo","complete":false}' 46 | ``` 47 | 48 | Modify an existing todo: 49 | 50 | ```sh 51 | curl -X "PUT" -v localhost:8080/todos/0 -H "Content-Type: application/json" -d '{"description":"Modified Todo","complete":false}' 52 | ``` 53 | 54 | Delete a todo: 55 | 56 | ```sh 57 | curl -X "DELETE" -v localhost:8080/todos/0 58 | ``` 59 | 60 | Apply a JSON PATCH to the todo list: 61 | 62 | ```sh 63 | curl -X "PATCH" -v localhost:8080/todos -H "Content-Type: application/json" -d '[{"op":"replace","path":"/0/description","value":"go go go!"}]' 64 | ``` 65 | 66 | Generate a JSON PATCH from a modified todo list: 67 | 68 | ```sh 69 | curl -X "POST" -v localhost:8080/todos/diff -H "Content-Type: application/json" -d '[{"description":"go go go!","complete":false},{"description":"b","complete":false}]' 70 | ``` 71 | -------------------------------------------------------------------------------- /spring-rest-todos/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | maven { url "https://repo.spring.io/plugins-release" } 4 | } 5 | dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.1.8.RELEASE") } 6 | } 7 | 8 | apply plugin: "java" 9 | apply plugin: "eclipse" 10 | apply plugin: "eclipse-wtp" 11 | apply plugin: "idea" 12 | apply plugin: "spring-boot" 13 | apply plugin: "war" 14 | 15 | sourceCompatibility = 1.7 16 | targetCompatibility = 1.7 17 | 18 | jar { 19 | baseName = "spring-rest-todos" 20 | version = "0.1.0" 21 | } 22 | 23 | repositories { 24 | mavenLocal() 25 | mavenCentral() 26 | maven { url "https://repo.spring.io/libs-snapshot" } 27 | } 28 | 29 | dependencies { 30 | compile("org.springframework.boot:spring-boot-starter-web") 31 | compile("org.springframework.boot:spring-boot-starter-data-jpa") 32 | compile("org.springframework.sync:spring-sync-config:1.0.0.BUILD-SNAPSHOT") 33 | compile("org.springframework.sync:spring-sync-core:1.0.0.BUILD-SNAPSHOT") 34 | compile("org.springframework.sync:spring-sync-web: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 | compile("com.googlecode.java-diff-utils:diffutils:1.2.1") 41 | testCompile("org.springframework.boot:spring-boot-starter-test") 42 | testCompile("com.jayway.jsonpath:json-path:0.8.1") 43 | testCompile("com.jayway.jsonpath:json-path-assert:0.8.1") 44 | } 45 | 46 | task wrapper(type: Wrapper) { gradleVersion = "2.1" } 47 | 48 | task clientInstall(type:Exec) { 49 | logging.captureStandardOutput LogLevel.INFO 50 | logging.captureStandardError LogLevel.LIFECYCLE 51 | workingDir './src/main/resources/public' 52 | commandLine 'bower', 'install' 53 | } 54 | 55 | build.dependsOn clientInstall 56 | 57 | -------------------------------------------------------------------------------- /spring-rest-todos/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 | -------------------------------------------------------------------------------- /spring-rest-todos/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spring-attic/spring-sync-samples/548850ddccdc009c116eae453daabea16e934ae1/spring-rest-todos/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /spring-rest-todos/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue Nov 04 13:22:07 CST 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.1-bin.zip 7 | -------------------------------------------------------------------------------- /spring-rest-todos/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 | -------------------------------------------------------------------------------- /spring-rest-todos/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 | -------------------------------------------------------------------------------- /spring-rest-todos/src/main/java/todos/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 todos; 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 | -------------------------------------------------------------------------------- /spring-rest-todos/src/main/java/todos/DiffSyncConfig.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 | package todos; 17 | 18 | import org.springframework.beans.factory.annotation.Autowired; 19 | import org.springframework.context.annotation.Configuration; 20 | import org.springframework.data.repository.PagingAndSortingRepository; 21 | import org.springframework.sync.diffsync.PersistenceCallbackRegistry; 22 | import org.springframework.sync.diffsync.config.DiffSyncConfigurerAdapter; 23 | import org.springframework.sync.diffsync.config.EnableDifferentialSynchronization; 24 | 25 | @Configuration 26 | @EnableDifferentialSynchronization 27 | public class DiffSyncConfig extends DiffSyncConfigurerAdapter { 28 | 29 | @Autowired 30 | private PagingAndSortingRepository repo; 31 | 32 | @Override 33 | public void addPersistenceCallbacks(PersistenceCallbackRegistry registry) { 34 | registry.addPersistenceCallback(new JpaPersistenceCallback(repo, Todo.class)); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /spring-rest-todos/src/main/java/todos/JpaPersistenceCallback.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 | package todos; 17 | 18 | import java.util.List; 19 | 20 | import org.springframework.data.domain.Sort; 21 | import org.springframework.data.repository.PagingAndSortingRepository; 22 | import org.springframework.sync.diffsync.PersistenceCallback; 23 | 24 | class JpaPersistenceCallback implements PersistenceCallback { 25 | 26 | private final PagingAndSortingRepository repo; 27 | private Class entityType; 28 | 29 | public JpaPersistenceCallback(PagingAndSortingRepository repo, Class entityType) { 30 | this.repo = repo; 31 | this.entityType = entityType; 32 | } 33 | 34 | @Override 35 | public List findAll() { 36 | return (List) repo.findAll(new Sort("id")); 37 | } 38 | 39 | @Override 40 | public T findOne(String id) { 41 | return repo.findOne(Long.valueOf(id)); 42 | } 43 | 44 | @Override 45 | public void persistChange(T itemToSave) { 46 | repo.save(itemToSave); 47 | } 48 | 49 | @Override 50 | public void persistChanges(List itemsToSave, List itemsToDelete) { 51 | repo.save(itemsToSave); 52 | repo.delete(itemsToDelete); 53 | } 54 | 55 | @Override 56 | public Class getEntityType() { 57 | return entityType; 58 | } 59 | 60 | } -------------------------------------------------------------------------------- /spring-rest-todos/src/main/java/todos/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 todos; 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 | -------------------------------------------------------------------------------- /spring-rest-todos/src/main/java/todos/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 todos; 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 | -------------------------------------------------------------------------------- /spring-rest-todos/src/main/java/todos/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 todos; 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 | -------------------------------------------------------------------------------- /spring-rest-todos/src/main/java/todos/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 todos; 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 | -------------------------------------------------------------------------------- /spring-rest-todos/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.diffsync.path=/sync 2 | -------------------------------------------------------------------------------- /spring-rest-todos/src/main/resources/public/.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules/ 2 | /bower_components/ 3 | /.idea/ 4 | -------------------------------------------------------------------------------- /spring-rest-todos/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 | -------------------------------------------------------------------------------- /spring-rest-todos/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 | -------------------------------------------------------------------------------- /spring-rest-todos/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 | -------------------------------------------------------------------------------- /spring-rest-todos/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 | -------------------------------------------------------------------------------- /spring-rest-todos/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 | -------------------------------------------------------------------------------- /spring-rest-todos/src/test/java/todos/EmbeddedDataSourceConfig.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 todos; 18 | 19 | import java.util.HashMap; 20 | import java.util.Map; 21 | 22 | import javax.sql.DataSource; 23 | 24 | import org.hibernate.dialect.H2Dialect; 25 | import org.springframework.context.annotation.Bean; 26 | import org.springframework.context.annotation.Configuration; 27 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 28 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; 29 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; 30 | import org.springframework.orm.jpa.JpaTransactionManager; 31 | import org.springframework.orm.jpa.JpaVendorAdapter; 32 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; 33 | import org.springframework.orm.jpa.vendor.Database; 34 | import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; 35 | import org.springframework.transaction.PlatformTransactionManager; 36 | 37 | @Configuration 38 | @EnableJpaRepositories(basePackages="hello") 39 | public class EmbeddedDataSourceConfig { 40 | 41 | @Bean 42 | public DataSource dataSource() { 43 | return new EmbeddedDatabaseBuilder() 44 | .setType(EmbeddedDatabaseType.H2) 45 | .addScript("classpath:/hello/testdb.sql").build(); 46 | } 47 | 48 | 49 | @Bean 50 | public Map jpaProperties() { 51 | Map props = new HashMap(); 52 | props.put("hibernate.dialect", H2Dialect.class.getName()); 53 | return props; 54 | } 55 | 56 | @Bean 57 | public JpaVendorAdapter jpaVendorAdapter() { 58 | HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter(); 59 | hibernateJpaVendorAdapter.setShowSql(false); 60 | hibernateJpaVendorAdapter.setGenerateDdl(true); 61 | hibernateJpaVendorAdapter.setDatabase(Database.H2); 62 | return hibernateJpaVendorAdapter; 63 | } 64 | 65 | @Bean 66 | public PlatformTransactionManager transactionManager() { 67 | return new JpaTransactionManager( entityManagerFactory().getObject() ); 68 | } 69 | 70 | @Bean 71 | public LocalContainerEntityManagerFactoryBean entityManagerFactory() { 72 | LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean(); 73 | lef.setDataSource(dataSource()); 74 | lef.setJpaPropertyMap(this.jpaProperties()); 75 | lef.setJpaVendorAdapter(this.jpaVendorAdapter()); 76 | lef.setPackagesToScan("hello"); 77 | return lef; 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /spring-rest-todos/src/test/java/todos/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 todos; 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 | } -------------------------------------------------------------------------------- /spring-rest-todos/src/test/resources/todos/patch-add-new-item.json: -------------------------------------------------------------------------------- 1 | [{"op":"add","path":"/3","value":{"description":"D","complete":false}}] -------------------------------------------------------------------------------- /spring-rest-todos/src/test/resources/todos/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 | -------------------------------------------------------------------------------- /spring-rest-todos/src/test/resources/todos/patch-change-single-status.json: -------------------------------------------------------------------------------- 1 | [{"op":"test", "path":"/1/complete", "value":false}, {"op":"replace", "path":"/1/complete", "value":true}] 2 | -------------------------------------------------------------------------------- /spring-rest-todos/src/test/resources/todos/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"}] -------------------------------------------------------------------------------- /spring-rest-todos/src/test/resources/todos/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 | -------------------------------------------------------------------------------- /spring-rest-todos/src/test/resources/todos/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 | ] -------------------------------------------------------------------------------- /spring-rest-todos/src/test/resources/todos/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 | ] -------------------------------------------------------------------------------- /spring-rest-todos/src/test/resources/todos/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 | ] -------------------------------------------------------------------------------- /spring-rest-todos/src/test/resources/todos/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 | ] -------------------------------------------------------------------------------- /spring-rest-todos/src/test/resources/todos/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 | -------------------------------------------------------------------------------- /spring-rest-todos/src/test/resources/todos/patch-remove-item.json: -------------------------------------------------------------------------------- 1 | [{"op":"test","path":"/1","value":{"id":2,"description":"B","complete":false}},{"op":"remove","path":"/1"}] -------------------------------------------------------------------------------- /spring-rest-todos/src/test/resources/todos/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"}] -------------------------------------------------------------------------------- /spring-rest-todos/src/test/resources/todos/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 | --------------------------------------------------------------------------------