├── .gitignore ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src ├── main ├── java │ └── com │ │ └── questionmarks │ │ ├── ServerApplication.java │ │ ├── WebMvcConfig.java │ │ ├── controller │ │ └── ExamRestController.java │ │ ├── model │ │ ├── Alternative.java │ │ ├── Attempt.java │ │ ├── Exam.java │ │ ├── Question.java │ │ ├── User.java │ │ └── dto │ │ │ ├── ExamCreationDTO.java │ │ │ └── ExamUpdateDTO.java │ │ ├── persistence │ │ └── ExamRepository.java │ │ └── util │ │ ├── DTO.java │ │ └── DTOModelMapper.java └── resources │ ├── application.properties │ └── db │ └── changelog │ ├── changes │ ├── v0001.sql │ └── v0002.sql │ └── db.changelog-master.yaml └── test └── java └── com └── questionmarks ├── ServerApplicationTests.java └── model └── ExamUT.java /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /build/ 3 | !gradle/wrapper/gradle-wrapper.jar 4 | 5 | ### STS ### 6 | .apt_generated 7 | .classpath 8 | .factorypath 9 | .project 10 | .settings 11 | .springBeans 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | nbproject/private/ 21 | build/ 22 | nbbuild/ 23 | dist/ 24 | nbdist/ 25 | .nb-gradle/ -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ```bash 2 | curl http://localhost:8080/exams 3 | 4 | curl -X POST -H "Content-Type: application/json" -d '{ 5 | "title": "First exam" 6 | }' http://localhost:8080/exams 7 | 8 | curl -X POST -H "Content-Type: application/json" -d '{ 9 | "title": "Another show exam", 10 | "description": "Another show exam desc" 11 | }' http://localhost:8080/exams 12 | 13 | curl -X POST -H "Content-Type: application/json" -d '{ 14 | "title": "First exam", 15 | "description": "Just a test", 16 | "url": "trying-to-hack", 17 | "published": true 18 | }' http://localhost:8080/exams 19 | 20 | curl -X PUT -H "Content-Type: application/json" -d '{ 21 | "title": "First exam", 22 | "description": "Just a test", 23 | "url": "trying-to-hack", 24 | "published": true 25 | }' http://localhost:8080/exams 26 | 27 | curl -X PUT -H "Content-Type: application/json" -d '{ 28 | "id": 1, 29 | "title": "First exam", 30 | "description": "Just a test" 31 | }' http://localhost:8080/exams 32 | 33 | curl -X PUT -H "Content-Type: application/json" -d '{ 34 | "id": 2, 35 | "title": "The third exam is amazing", 36 | "description": "Just a test" 37 | }' http://localhost:8080/exams 38 | ``` -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext { 3 | springBootVersion = '1.5.6.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: 'org.springframework.boot' 16 | 17 | version = '0.0.1-SNAPSHOT' 18 | sourceCompatibility = 1.8 19 | 20 | repositories { 21 | mavenCentral() 22 | } 23 | 24 | dependencies { 25 | compileOnly('org.projectlombok:lombok:1.16.18') 26 | compile('org.springframework.boot:spring-boot-starter') 27 | compile('org.springframework.boot:spring-boot-starter-web') 28 | compile('org.springframework.boot:spring-boot-starter-data-jpa') 29 | compile('org.hibernate:hibernate-java8:5.1.0.Final') 30 | compile('org.liquibase:liquibase-core') 31 | compile('org.modelmapper:modelmapper:1.1.0') 32 | runtime('org.postgresql:postgresql:42.1.4') 33 | testCompile('org.springframework.boot:spring-boot-starter-test') 34 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/auth0-blog/questionmarks-server/6e2534f4e794a737e9bbf21a7247b9c8842e12ed/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | zipStoreBase=GRADLE_USER_HOME 4 | zipStorePath=wrapper/dists 5 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.5.1-bin.zip 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save ( ) { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /src/main/java/com/questionmarks/ServerApplication.java: -------------------------------------------------------------------------------- 1 | package com.questionmarks; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class ServerApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(ServerApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/questionmarks/WebMvcConfig.java: -------------------------------------------------------------------------------- 1 | package com.questionmarks; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.questionmarks.util.DTOModelMapper; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.context.ApplicationContext; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; 9 | import org.springframework.web.method.support.HandlerMethodArgumentResolver; 10 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 11 | 12 | import javax.persistence.EntityManager; 13 | import java.util.List; 14 | 15 | @Configuration 16 | public class WebMvcConfig extends WebMvcConfigurerAdapter { 17 | private final ApplicationContext applicationContext; 18 | private final EntityManager entityManager; 19 | 20 | @Autowired 21 | public WebMvcConfig(ApplicationContext applicationContext, EntityManager entityManager) { 22 | this.applicationContext = applicationContext; 23 | this.entityManager = entityManager; 24 | } 25 | 26 | @Override 27 | public void addArgumentResolvers(List argumentResolvers) { 28 | super.addArgumentResolvers(argumentResolvers); 29 | ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().applicationContext(this.applicationContext).build(); 30 | argumentResolvers.add(new DTOModelMapper(objectMapper, entityManager)); 31 | } 32 | } -------------------------------------------------------------------------------- /src/main/java/com/questionmarks/controller/ExamRestController.java: -------------------------------------------------------------------------------- 1 | package com.questionmarks.controller; 2 | 3 | import com.questionmarks.model.Exam; 4 | import com.questionmarks.model.dto.ExamCreationDTO; 5 | import com.questionmarks.model.dto.ExamUpdateDTO; 6 | import com.questionmarks.persistence.ExamRepository; 7 | import com.questionmarks.util.DTO; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.PostMapping; 11 | import org.springframework.web.bind.annotation.PutMapping; 12 | import org.springframework.web.bind.annotation.RequestMapping; 13 | import org.springframework.web.bind.annotation.ResponseStatus; 14 | import org.springframework.web.bind.annotation.RestController; 15 | 16 | import java.util.List; 17 | 18 | @RestController 19 | @RequestMapping("/exams") 20 | public class ExamRestController { 21 | private ExamRepository examRepository; 22 | 23 | public ExamRestController(ExamRepository examRepository) { 24 | this.examRepository = examRepository; 25 | } 26 | 27 | @GetMapping 28 | public List getExams() { 29 | return examRepository.findAll(); 30 | } 31 | 32 | @PostMapping 33 | public void newExam(@DTO(ExamCreationDTO.class) Exam exam) { 34 | examRepository.save(exam); 35 | } 36 | 37 | @PutMapping 38 | @ResponseStatus(HttpStatus.OK) 39 | public void editExam(@DTO(ExamUpdateDTO.class) Exam exam) { 40 | examRepository.save(exam); 41 | } 42 | } -------------------------------------------------------------------------------- /src/main/java/com/questionmarks/model/Alternative.java: -------------------------------------------------------------------------------- 1 | package com.questionmarks.model; 2 | 3 | import lombok.Data; 4 | 5 | import javax.persistence.Entity; 6 | import javax.persistence.GeneratedValue; 7 | import javax.persistence.GenerationType; 8 | import javax.persistence.Id; 9 | import javax.persistence.JoinColumn; 10 | import javax.persistence.ManyToOne; 11 | import javax.validation.constraints.NotNull; 12 | 13 | @Data 14 | @Entity 15 | public class Alternative { 16 | @Id 17 | @GeneratedValue(strategy = GenerationType.IDENTITY) 18 | private long id; 19 | 20 | @NotNull 21 | @ManyToOne 22 | @JoinColumn(name = "question_id") 23 | private Question question; 24 | 25 | private long order; 26 | 27 | @NotNull 28 | private String description; 29 | 30 | private boolean correct; 31 | } -------------------------------------------------------------------------------- /src/main/java/com/questionmarks/model/Attempt.java: -------------------------------------------------------------------------------- 1 | package com.questionmarks.model; 2 | 3 | import lombok.Data; 4 | 5 | import javax.persistence.Entity; 6 | import javax.persistence.GeneratedValue; 7 | import javax.persistence.GenerationType; 8 | import javax.persistence.Id; 9 | import javax.persistence.JoinColumn; 10 | import javax.persistence.ManyToOne; 11 | import javax.validation.constraints.NotNull; 12 | import java.util.Date; 13 | 14 | @Data 15 | @Entity 16 | public class Attempt { 17 | @Id 18 | @GeneratedValue(strategy = GenerationType.IDENTITY) 19 | private long id; 20 | 21 | @NotNull 22 | @ManyToOne 23 | @JoinColumn(name = "user_id") 24 | private User user; 25 | 26 | @NotNull 27 | @ManyToOne 28 | @JoinColumn (name = "alternative_id") 29 | private Alternative alternative; 30 | 31 | @NotNull 32 | private Date date; 33 | 34 | private boolean correct; 35 | } -------------------------------------------------------------------------------- /src/main/java/com/questionmarks/model/Exam.java: -------------------------------------------------------------------------------- 1 | package com.questionmarks.model; 2 | 3 | import lombok.Data; 4 | 5 | import javax.persistence.Entity; 6 | import javax.persistence.GeneratedValue; 7 | import javax.persistence.GenerationType; 8 | import javax.persistence.Id; 9 | import javax.validation.constraints.NotNull; 10 | import java.time.LocalDateTime; 11 | 12 | @Data 13 | @Entity 14 | public class Exam { 15 | @Id 16 | @GeneratedValue(strategy = GenerationType.IDENTITY) 17 | private long id; 18 | 19 | @NotNull 20 | private String title; 21 | 22 | @NotNull 23 | private String description; 24 | 25 | @NotNull 26 | private LocalDateTime createdAt; 27 | 28 | @NotNull 29 | private LocalDateTime editedAt; 30 | 31 | @NotNull 32 | private boolean published; 33 | } -------------------------------------------------------------------------------- /src/main/java/com/questionmarks/model/Question.java: -------------------------------------------------------------------------------- 1 | package com.questionmarks.model; 2 | 3 | import lombok.Data; 4 | 5 | import javax.persistence.Entity; 6 | import javax.persistence.GeneratedValue; 7 | import javax.persistence.GenerationType; 8 | import javax.persistence.Id; 9 | import javax.persistence.JoinColumn; 10 | import javax.persistence.ManyToOne; 11 | import javax.validation.constraints.NotNull; 12 | 13 | @Data 14 | @Entity 15 | public class Question { 16 | @Id 17 | @GeneratedValue(strategy = GenerationType.IDENTITY) 18 | private long id; 19 | 20 | @NotNull 21 | @ManyToOne 22 | @JoinColumn(name = "exam_id") 23 | private Exam exam; 24 | 25 | private long order; 26 | 27 | @NotNull 28 | private String description; 29 | } -------------------------------------------------------------------------------- /src/main/java/com/questionmarks/model/User.java: -------------------------------------------------------------------------------- 1 | package com.questionmarks.model; 2 | 3 | import lombok.Data; 4 | 5 | import javax.persistence.Entity; 6 | import javax.persistence.Id; 7 | 8 | @Data 9 | @Entity 10 | public class User { 11 | @Id 12 | private String id; 13 | } -------------------------------------------------------------------------------- /src/main/java/com/questionmarks/model/dto/ExamCreationDTO.java: -------------------------------------------------------------------------------- 1 | package com.questionmarks.model.dto; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | 7 | import javax.validation.constraints.NotNull; 8 | import java.time.LocalDateTime; 9 | 10 | @Getter 11 | @Setter 12 | public class ExamCreationDTO { 13 | @NotNull 14 | private String title; 15 | 16 | @NotNull 17 | private String description; 18 | 19 | @JsonIgnore 20 | private final LocalDateTime createdAt = LocalDateTime.now(); 21 | 22 | @JsonIgnore 23 | private final LocalDateTime editedAt = LocalDateTime.now(); 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/questionmarks/model/dto/ExamUpdateDTO.java: -------------------------------------------------------------------------------- 1 | package com.questionmarks.model.dto; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | 7 | import javax.persistence.Id; 8 | import javax.validation.constraints.NotNull; 9 | import java.time.LocalDateTime; 10 | 11 | @Getter 12 | @Setter 13 | public class ExamUpdateDTO { 14 | @Id 15 | @NotNull 16 | private Long id; 17 | 18 | @NotNull 19 | private String title; 20 | 21 | @NotNull 22 | private String description; 23 | 24 | @JsonIgnore 25 | private final LocalDateTime editedAt = LocalDateTime.now(); 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/questionmarks/persistence/ExamRepository.java: -------------------------------------------------------------------------------- 1 | package com.questionmarks.persistence; 2 | 3 | import com.questionmarks.model.Exam; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface ExamRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/questionmarks/util/DTO.java: -------------------------------------------------------------------------------- 1 | package com.questionmarks.util; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Target(ElementType.PARAMETER) 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface DTO { 11 | Class value(); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/questionmarks/util/DTOModelMapper.java: -------------------------------------------------------------------------------- 1 | package com.questionmarks.util; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import org.modelmapper.ModelMapper; 5 | import org.springframework.core.MethodParameter; 6 | import org.springframework.core.annotation.AnnotationUtils; 7 | import org.springframework.http.HttpInputMessage; 8 | import org.springframework.http.converter.HttpMessageNotReadableException; 9 | import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; 10 | import org.springframework.web.HttpMediaTypeNotSupportedException; 11 | import org.springframework.web.bind.WebDataBinder; 12 | import org.springframework.web.bind.support.WebDataBinderFactory; 13 | import org.springframework.web.context.request.NativeWebRequest; 14 | import org.springframework.web.method.support.ModelAndViewContainer; 15 | import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor; 16 | 17 | import javax.persistence.EntityManager; 18 | import javax.persistence.Id; 19 | import javax.validation.constraints.NotNull; 20 | import java.io.IOException; 21 | import java.lang.annotation.Annotation; 22 | import java.lang.reflect.Field; 23 | import java.lang.reflect.Type; 24 | import java.util.Collections; 25 | 26 | public class DTOModelMapper extends RequestResponseBodyMethodProcessor { 27 | private static final ModelMapper modelMapper = new ModelMapper(); 28 | 29 | private EntityManager entityManager; 30 | 31 | public DTOModelMapper(ObjectMapper objectMapper, EntityManager entityManager) { 32 | super(Collections.singletonList(new MappingJackson2HttpMessageConverter(objectMapper))); 33 | this.entityManager = entityManager; 34 | } 35 | 36 | @Override 37 | public boolean supportsParameter(MethodParameter parameter) { 38 | return parameter.hasParameterAnnotation(DTO.class); 39 | } 40 | 41 | @Override 42 | protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) { 43 | binder.validate(); 44 | } 45 | 46 | @Override 47 | public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { 48 | Object dto = super.resolveArgument(parameter, mavContainer, webRequest, binderFactory); 49 | Object id = getEntityId(dto); 50 | if (id == null) { 51 | return modelMapper.map(dto, parameter.getParameterType()); 52 | } else { 53 | Object persistedObject = entityManager.find(parameter.getParameterType(), id); 54 | modelMapper.map(dto, persistedObject); 55 | return persistedObject; 56 | } 57 | } 58 | 59 | @Override 60 | protected Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException { 61 | for (Annotation ann : parameter.getParameterAnnotations()) { 62 | DTO dtoType = AnnotationUtils.getAnnotation(ann, DTO.class); 63 | if (dtoType != null) { 64 | return super.readWithMessageConverters(inputMessage, parameter, dtoType.value()); 65 | } 66 | } 67 | throw new RuntimeException(); 68 | } 69 | 70 | private Object getEntityId(@NotNull Object dto) { 71 | for (Field field : dto.getClass().getDeclaredFields()) { 72 | if (field.getAnnotation(Id.class) != null) { 73 | try { 74 | field.setAccessible(true); 75 | return field.get(dto); 76 | } catch (IllegalAccessException e) { 77 | throw new RuntimeException(e); 78 | } 79 | } 80 | } 81 | return null; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=jdbc:postgresql://localhost/questionmarks 2 | spring.datasource.username=postgres 3 | spring.datasource.password=mysecretpassword 4 | spring.datasource.driver-class-name=org.postgresql.Driver -------------------------------------------------------------------------------- /src/main/resources/db/changelog/changes/v0001.sql: -------------------------------------------------------------------------------- 1 | create table "user" ( 2 | id varchar(255) not null, 3 | name varchar(50) not null, 4 | primary key (id) 5 | ); 6 | 7 | create table exam ( 8 | id bigserial not null, 9 | title varchar(50) not null, 10 | description varchar(512) not null, 11 | primary key (id) 12 | ); 13 | 14 | create table question ( 15 | id bigserial not null, 16 | exam_id bigint not null references exam (id), 17 | question_order bigint not null, 18 | description text not null, 19 | primary key (id) 20 | ); 21 | 22 | create table alternative ( 23 | id bigserial not null, 24 | question_id bigint not null references question (id), 25 | alternative_order bigint not null, 26 | description text not null, 27 | correct boolean not null, 28 | primary key (id) 29 | ); 30 | 31 | create table attempt ( 32 | id bigserial not null, 33 | user_id varchar(255) not null references "user" (id), 34 | alternative_id bigint not null references alternative (id), 35 | correct boolean not null, 36 | date timestamp without time zone not null, 37 | primary key (id) 38 | ); -------------------------------------------------------------------------------- /src/main/resources/db/changelog/changes/v0002.sql: -------------------------------------------------------------------------------- 1 | alter table exam 2 | add column created_at timestamp without time zone not null default now(), 3 | add column edited_at timestamp without time zone not null default now(), 4 | add column published boolean not null default false; -------------------------------------------------------------------------------- /src/main/resources/db/changelog/db.changelog-master.yaml: -------------------------------------------------------------------------------- 1 | databaseChangeLog: 2 | - includeAll: 3 | path: db/changelog/changes/ -------------------------------------------------------------------------------- /src/test/java/com/questionmarks/ServerApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.questionmarks; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class ServerApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/questionmarks/model/ExamUT.java: -------------------------------------------------------------------------------- 1 | package com.questionmarks.model; 2 | 3 | import com.questionmarks.model.dto.ExamCreationDTO; 4 | import com.questionmarks.model.dto.ExamUpdateDTO; 5 | import org.junit.Test; 6 | import org.modelmapper.ModelMapper; 7 | 8 | import static org.junit.Assert.assertEquals; 9 | 10 | public class ExamUT { 11 | private static final ModelMapper modelMapper = new ModelMapper(); 12 | 13 | @Test 14 | public void checkExamMapping() { 15 | ExamCreationDTO creation = new ExamCreationDTO(); 16 | creation.setTitle("Testing title"); 17 | creation.setDescription("Testing description"); 18 | 19 | Exam exam = modelMapper.map(creation, Exam.class); 20 | assertEquals(creation.getTitle(), exam.getTitle()); 21 | assertEquals(creation.getDescription(), exam.getDescription()); 22 | assertEquals(creation.getCreatedAt(), exam.getCreatedAt()); 23 | assertEquals(creation.getEditedAt(), exam.getEditedAt()); 24 | 25 | ExamUpdateDTO update = new ExamUpdateDTO(); 26 | update.setTitle("New title"); 27 | update.setDescription("New description"); 28 | 29 | modelMapper.map(update, exam); 30 | assertEquals(update.getTitle(), exam.getTitle()); 31 | assertEquals(update.getDescription(), exam.getDescription()); 32 | assertEquals(creation.getCreatedAt(), exam.getCreatedAt()); 33 | assertEquals(update.getEditedAt(), exam.getEditedAt()); 34 | } 35 | } 36 | --------------------------------------------------------------------------------