diff options
author | Mole Shang <[email protected]> | 2024-12-15 00:00:13 +0800 |
---|---|---|
committer | Mole Shang <[email protected]> | 2024-12-15 00:02:19 +0800 |
commit | d3f77ea51dd72b055307ac259c3caf8091307aa6 (patch) | |
tree | ba5e10e04d1c6e4ce281f7cf6e43abad407eac65 | |
download | se-intro-master.tar.gz se-intro-master.tar.bz2 se-intro-master.zip |
-rw-r--r-- | .gitattributes | 3 | ||||
-rw-r--r-- | .gitignore | 37 | ||||
-rw-r--r-- | build.gradle | 33 | ||||
-rw-r--r-- | gradle/wrapper/gradle-wrapper.jar | bin | 0 -> 43583 bytes | |||
-rw-r--r-- | gradle/wrapper/gradle-wrapper.properties | 7 | ||||
-rwxr-xr-x | gradlew | 252 | ||||
-rw-r--r-- | gradlew.bat | 94 | ||||
-rw-r--r-- | local.properties | 8 | ||||
-rw-r--r-- | settings.gradle | 1 | ||||
-rw-r--r-- | src/main/java/seu/se/ApiController.java | 370 | ||||
-rw-r--r-- | src/main/java/seu/se/Application.java | 102 | ||||
-rw-r--r-- | src/main/java/seu/se/Exercise.java | 125 | ||||
-rw-r--r-- | src/main/java/seu/se/TreeNode.java | 215 | ||||
-rw-r--r-- | src/main/java/seu/se/TreeNodeRepository.java | 8 | ||||
-rw-r--r-- | src/main/java/seu/se/User.java | 65 | ||||
-rw-r--r-- | src/main/java/seu/se/UserRepository.java | 11 | ||||
-rw-r--r-- | src/main/resources/application.properties | 9 | ||||
-rw-r--r-- | src/main/resources/treeNodes.json | 73 | ||||
-rw-r--r-- | src/main/resources/users.json | 6 |
19 files changed, 1419 insertions, 0 deletions
diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..73109dd --- /dev/null +++ b/build.gradle @@ -0,0 +1,33 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.2.0' + id 'io.spring.dependency-management' version '1.1.4' +} + +group = 'seu.se.Project' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-neo4j' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation group: 'org.springdoc', name: 'springdoc-openapi-starter-webmvc-ui', version: '2.0.3' + implementation "org.springframework.session:spring-session-core" + implementation "org.springframework.data:spring-data-jpa" + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'io.projectreactor:reactor-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +//tasks.named('test') { +// useJUnitPlatform() +//} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar Binary files differnew file mode 100644 index 0000000..a4b76b9 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.jar diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..df97d72 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/local.properties b/local.properties new file mode 100644 index 0000000..fa345d1 --- /dev/null +++ b/local.properties @@ -0,0 +1,8 @@ +## This file must *NOT* be checked into Version Control Systems, +# as it contains information specific to your local configuration. +# +# Location of the SDK. This is only used by Gradle. +# For customization when using a Version Control System, please read the +# header note. +#Tue Dec 03 16:37:46 CST 2024 +sdk.dir=/opt/android-sdk diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..aa0d9d6 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'Project' diff --git a/src/main/java/seu/se/ApiController.java b/src/main/java/seu/se/ApiController.java new file mode 100644 index 0000000..17a6702 --- /dev/null +++ b/src/main/java/seu/se/ApiController.java @@ -0,0 +1,370 @@ +package seu.se; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import java.util.HashSet; +import java.util.List; + +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; + +@RequestMapping("/api") +@RestController +public class ApiController { + public static abstract class DataObject { + public Boolean ok; + public String message; + public Object otherData; + } + + public static abstract class ReturnObject { + public String status; + public DataObject dataObj; + } + + @GetMapping(value = "/ping") + public String Ping() { + return "Pong!"; + } + + @RequestMapping("/api/user") + @RestController + static class UserController { + private final UserRepository uRepo; + + UserController(UserRepository uRepo) { + this.uRepo = uRepo; + } + + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Ok", content = + {@Content(mediaType = "application/json", schema = + @Schema(implementation = ReturnObject.class))}), + @ApiResponse(responseCode = "400", description = "Invalid userId supplied"), + @ApiResponse(responseCode = "500", description = "Internal server error")}) + @PostMapping("/login") + public JsonNode Login(@RequestBody com.fasterxml.jackson.databind.JsonNode body) { + var id = body.get("userId").asInt(); + var password = body.get("password").asText(); + var user = uRepo.findById(id); + var retObj = new ObjectMapper().createObjectNode(); + var dataObj = new ObjectMapper().createObjectNode(); + String message; + Boolean ok; + if (user != null) { + if (password.equals(user.getPassword())) { + ok = true; + message = "Login Success"; + // save session + ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); + attr.getRequest().getSession(true).setAttribute("SESSION", user); + + } else { + ok = false; + message = "Wrong password"; + } + dataObj = new ObjectMapper().valueToTree(user); + } else { + ok = false; + message = "User not found"; + } + dataObj.put("ok", ok); + dataObj.put("message", message); + retObj.set("data", dataObj); + retObj.put("status", "ok"); + return retObj; + } + + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Ok", content = + {@Content(mediaType = "application/json", schema = + @Schema(implementation = ReturnObject.class))}), + @ApiResponse(responseCode = "500", description = "Internal server error")}) + @PostMapping("/register") + public JsonNode Register(@RequestBody com.fasterxml.jackson.databind.JsonNode body) { + var username = body.get("username").asText(); + var password = body.get("password").asText(); + String message; + Boolean ok; + var retObj = new ObjectMapper().createObjectNode(); + var dataObj = new ObjectMapper().createObjectNode(); + try { + var user = uRepo.save(new User(username, password)); + ok = true; + message = "Registered"; + dataObj = new ObjectMapper().valueToTree(user); + } catch (User.UserException ue) { + ok = false; + message = ue.getMessage(); + } + dataObj.put("ok", ok); + dataObj.put("message", message); + retObj.set("data", dataObj); + retObj.put("status", "ok"); + return retObj; + } + } + + @RequestMapping("/api/node") + @RestController + static class TreeNodeController { + private final TreeNodeRepository tnRepo; + + TreeNodeController(TreeNodeRepository tnRepo) { + this.tnRepo = tnRepo; + } + + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Ok", content = + {@Content(mediaType = "application/json", schema = + @Schema(implementation = ReturnObject.class))}), + @ApiResponse(responseCode = "500", description = "Internal server error")}) + @GetMapping("/content/{nodeId}") + public JsonNode getContent(@PathVariable String nodeId) { + String message; + Boolean ok; + var retObj = new ObjectMapper().createObjectNode(); + var dataObj = new ObjectMapper().createObjectNode(); + var treeNode = tnRepo.findByNodeId(nodeId); + if (treeNode != null) { + ok = true; + message = "Success"; + dataObj.put("nodeId", treeNode.getNodeId()); + dataObj.put("content", treeNode.getContent()); + } else { + ok = false; + message = "Node not found"; + } + dataObj.put("ok", ok); + dataObj.put("message", message); + retObj.set("data", dataObj); + retObj.put("status", "ok"); + return retObj; + } + + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Ok", content = + {@Content(mediaType = "application/json", schema = + @Schema(implementation = ReturnObject.class))}), + @ApiResponse(responseCode = "500", description = "Internal server error")}) + @GetMapping("/exercises/{nodeId}") + public JsonNode getExercises(@PathVariable String nodeId) { + String message; + Boolean ok; + var retObj = new ObjectMapper().createObjectNode(); + var dataObj = new ObjectMapper().createObjectNode(); + var treeNode = tnRepo.findByNodeId(nodeId); + if (treeNode != null) { + ok = true; + message = "Success"; + dataObj.put("nodeId", treeNode.getNodeId()); + var exercisesObj = new ObjectMapper().createArrayNode(); + for (var i : treeNode.getExercises()) { + var exerciseObj = new ObjectMapper().valueToTree(i); + exercisesObj.add(exerciseObj); + } + dataObj.set("exercises", exercisesObj); + } else { + ok = false; + message = "Node not found"; + } + dataObj.put("ok", ok); + dataObj.put("message", message); + retObj.set("data", dataObj); + retObj.put("status", "ok"); + + ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); + System.out.println(attr.getRequest().getSession(true).getAttribute("SESSION")); + + return retObj; + } + + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Ok", content = + {@Content(mediaType = "application/json", schema = + @Schema(implementation = ReturnObject.class))}), + @ApiResponse(responseCode = "500", description = "Internal server error")}) + @PostMapping("/submit/{nodeId}") + public JsonNode Submit(@PathVariable String nodeId, @RequestBody com.fasterxml.jackson.databind.JsonNode body) { + String message; + Boolean ok; + var retObj = new ObjectMapper().createObjectNode(); + var dataObj = new ObjectMapper().createObjectNode(); + var treeNode = tnRepo.findByNodeId(nodeId); + ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); + var user = (User) attr.getRequest().getSession(true).getAttribute("SESSION"); + if (treeNode == null) { + ok = false; + message = "Node not found"; + } else if (user == null) { + ok = false; + message = "Login first"; + } else { + var score = body.get("score").asDouble(); + var usp = treeNode.getUserScorePair(user.getId(), nodeId); + if (usp != null) { + usp.getScores().add(score); + } else { + treeNode.getUserScores().add(new TreeNode.UserScorePair(treeNode.getNodeId(), user.getId(), List.of(score))); + } + tnRepo.save(treeNode); + ok = true; + message = "Success"; + dataObj.put("userId", user.getId()); + dataObj.put("nodeId", nodeId); + } + dataObj.put("ok", ok); + dataObj.put("message", message); + retObj.set("data", dataObj); + retObj.put("status", "ok"); + return retObj; + } + + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Ok", content = + {@Content(mediaType = "application/json", schema = + @Schema(implementation = ReturnObject.class))}), + @ApiResponse(responseCode = "500", description = "Internal server error")}) + @GetMapping("/history/{nodeId}") + public JsonNode History(@PathVariable String nodeId) { + String message; + Boolean ok; + var retObj = new ObjectMapper().createObjectNode(); + var dataObj = new ObjectMapper().createObjectNode(); + var treeNode = tnRepo.findByNodeId(nodeId); + ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); + var user = (User) attr.getRequest().getSession(true).getAttribute("SESSION"); + if (treeNode == null) { + ok = false; + message = "Node not found"; + } else if (user == null) { + ok = false; + message = "Login first"; + } else { + var usp = treeNode.getUserScorePair(user.getId(), nodeId); + if (usp != null) { + var uspObj = new ObjectMapper().valueToTree(usp); + ok = true; + message = "Success"; + dataObj.set("historyScores", uspObj); + } else { + ok = false; + message = "No score found"; + } + dataObj.put("userId", user.getId()); + } + dataObj.put("ok", ok); + dataObj.put("message", message); + retObj.set("data", dataObj); + retObj.put("status", "ok"); + return retObj; + } + + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Ok", content = + {@Content(mediaType = "application/json", schema = + @Schema(implementation = ReturnObject.class))}), + @ApiResponse(responseCode = "500", description = "Internal server error")}) + @GetMapping("/home") + public JsonNode Home() { + var retObj = new ObjectMapper().createObjectNode(); + var dataObj = new ObjectMapper().createObjectNode(); + String message; + Boolean ok; + var nodes = tnRepo.findAll(); + var roots = new HashSet<TreeNode>(); + for (var n : nodes) { + if (n.getLevel() == 1) roots.add(n); + } + if (roots.isEmpty()) { + ok = false; + message = "No root found"; + } else { + class RecursiveHelper { + public final List<TreeNode> nodes; + + public RecursiveHelper(List<TreeNode> nodes) { + this.nodes = nodes; + } + + public ObjectNode RecursiveConstruct(TreeNode tn) { + ObjectNode graphNodesObj = new ObjectMapper().valueToTree(tn); + ArrayNode graphNodesIterateArr = new ObjectMapper().createArrayNode(); + var children = tn.getChildren(nodes); + if (!children.isEmpty()) { + children.forEach(e -> { + graphNodesIterateArr.add(RecursiveConstruct(e)); + }); + graphNodesObj.set("children", graphNodesIterateArr); + } + return graphNodesObj; + } + } + ArrayNode graphNodesIterateArr = new ObjectMapper().createArrayNode(); + for (var root : roots) { + graphNodesIterateArr.add(new RecursiveHelper(nodes).RecursiveConstruct(root)); + } + dataObj.set("graphNodes", graphNodesIterateArr); + ok = true; + message = "Success"; + } + dataObj.put("ok", ok); + dataObj.put("message", message); + retObj.set("data", dataObj); + retObj.put("status", "ok"); + return retObj; + } + + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Ok", content = + {@Content(mediaType = "application/json", schema = + @Schema(implementation = ReturnObject.class))}), + @ApiResponse(responseCode = "500", description = "Internal server error")}) + @GetMapping("/review-suggestion") + public JsonNode ReviewSuggestion() { + String message; + Boolean ok; + var retObj = new ObjectMapper().createObjectNode(); + var dataObj = new ObjectMapper().createObjectNode(); + ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); + var user = (User) attr.getRequest().getSession(true).getAttribute("SESSION"); + if (user == null) { + ok = false; + message = "Login first"; + } else { + var reviewSuggestionsArr = new ObjectMapper().createArrayNode(); + var nodes = tnRepo.findAll(); + for (var node : nodes) { + var usp = node.getUserScorePair(user.getId(), node.getNodeId()); + if (usp == null) continue; + var msl = TreeNode.UserScorePair.MasteryLevel.getMasteryLevel(usp.getAverageScore()); + if (msl.equals(TreeNode.UserScorePair.MasteryLevel.Average) || msl.equals(TreeNode.UserScorePair.MasteryLevel.Bad)) + reviewSuggestionsArr.add(node.getNodeId()); + } + ok = true; + message = "Success"; + dataObj.put("userId", user.getId()); + dataObj.set("reviewSuggestions", reviewSuggestionsArr); + } + dataObj.put("ok", ok); + dataObj.put("message", message); + retObj.set("data", dataObj); + retObj.put("status", "ok"); + return retObj; + } + } +} diff --git a/src/main/java/seu/se/Application.java b/src/main/java/seu/se/Application.java new file mode 100644 index 0000000..928bc28 --- /dev/null +++ b/src/main/java/seu/se/Application.java @@ -0,0 +1,102 @@ +package seu.se; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.session.MapSessionRepository; +import org.springframework.session.config.annotation.web.http.EnableSpringHttpSession; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.servlet.NoHandlerFoundException; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +@EnableTransactionManagement +@EnableNeo4jRepositories +@SpringBootApplication +public class Application { + private static final Logger log = LoggerFactory.getLogger(Application.class); + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @ControllerAdvice + public static class ExHandler { + @ExceptionHandler(Exception.class) + public ResponseEntity<Object> handle(Exception ex, HttpServletRequest request, HttpServletResponse response) { + HttpStatus code = HttpStatus.INTERNAL_SERVER_ERROR; + String status = "internal server error"; + if (ex instanceof NullPointerException) { + code = HttpStatus.BAD_REQUEST; + status = "bad request"; + } + if (ex instanceof NoHandlerFoundException) { + code = HttpStatus.NOT_FOUND; + status = "not found"; + } + var retObj = new ObjectMapper().createObjectNode(); + retObj.put("status", status); + retObj.put("message", ex.getMessage()); + return ResponseEntity.status(code).body(retObj); + } + } + + // in-mem session + @EnableSpringHttpSession + @Configuration(proxyBeanMethods = false) + public static class SpringHttpSessionConfig { + @Bean + public MapSessionRepository sessionRepository() { + return new MapSessionRepository(new ConcurrentHashMap<>()); + } + } + + @Bean + public CommandLineRunner init(UserRepository ur, TreeNodeRepository tnr) { + return (args) -> { + // Load users + try { + List<User> users = new ObjectMapper().readValue( + new ClassPathResource("users.json").getFile(), + new TypeReference<>() { + } + ); + ur.saveAll(users); + } catch (IOException e) { + log.error("Error loading users from JSON file", e); + } + + // Load tree nodes + TreeNode.tnRepo = tnr; + try { + List<TreeNode> treeNodes = new ObjectMapper().readValue( + new ClassPathResource("treeNodes.json").getFile(), + new TypeReference<>() { + } + ); + tnr.saveAll(treeNodes); + } catch (IOException e) { + log.error("Error loading tree nodes from JSON file", e); + } + }; + } + +} diff --git a/src/main/java/seu/se/Exercise.java b/src/main/java/seu/se/Exercise.java new file mode 100644 index 0000000..6df9212 --- /dev/null +++ b/src/main/java/seu/se/Exercise.java @@ -0,0 +1,125 @@ +package seu.se; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.annotation.PersistenceCreator; +import org.springframework.data.neo4j.core.schema.Id; +import org.springframework.data.neo4j.core.schema.Node; + +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +@Node +public class Exercise { + @Id + private String questionId; + private String question; + private List<OptionPair> options; + private String answer; + + public interface Choice { + String A = "A"; + String B = "B"; + String C = "C"; + String D = "D"; + } + + @Node + @JsonSerialize(using = OptionPair.OptionPairSerializer.class) + public static class OptionPair { + @Id + private final String id; + private final String key; + private final String value; + + public static class OptionPairSerializer extends StdSerializer<OptionPair> { + public OptionPairSerializer() { + this(null); + } + + public OptionPairSerializer(Class<OptionPair> t) { + super(t); + } + + @Override + public void serialize(OptionPair value, JsonGenerator gen, SerializerProvider provider) throws IOException { + gen.writeStartObject(); + gen.writeStringField(value.key, value.value); + gen.writeEndObject(); + } + } + + public OptionPair(String id, String key, String value) { + this.id = id; + this.key = key; + this.value = value; + } + + public String value() { + return value; + } + + public String key() { + return key; + } + + public String getId() { + return id; + } + } + + @JsonCreator + public Exercise(@JsonProperty("questionId") String questionId, @JsonProperty("question") String question, @JsonProperty("options") Map<String, String> options, @JsonProperty("answer") String answer) { + this.questionId = questionId; + this.question = question; + this.options = new LinkedList<OptionPair>(); + options.forEach((k, v) -> this.options.add(new OptionPair(String.format("%s.%s", questionId, k), k, v))); + this.answer = answer; + } + + @Autowired + @PersistenceCreator + // https://stackoverflow.com/questions/55827640/how-to-fix-failed-to-instantiate-classname-using-constructor-no-constructor + public Exercise(String questionId, String question, List<OptionPair> options, String answer) { + this.questionId = questionId; + this.question = question; + this.options = options; + this.answer = answer; + } + + public String getQuestion() { + return question; + } + + public void setQuestion(String question) { + this.question = question; + } + + public String getQuestionId() { + return questionId; + } + + public List<OptionPair> getOptions() { + return options; + } + + public void setOptions(List<OptionPair> options) { + this.options = options; + } + + public String getAnswer() { + return answer; + } + + public void setAnswer(String answer) { + this.answer = answer; + } +} diff --git a/src/main/java/seu/se/TreeNode.java b/src/main/java/seu/se/TreeNode.java new file mode 100644 index 0000000..f6e28b2 --- /dev/null +++ b/src/main/java/seu/se/TreeNode.java @@ -0,0 +1,215 @@ +package seu.se; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.annotation.PersistenceCreator; +import org.springframework.data.neo4j.core.schema.Id; +import org.springframework.data.neo4j.core.schema.Node; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; + + +@Node +@JsonInclude(JsonInclude.Include.NON_NULL) +public class TreeNode { + @Id + final private String nodeId; + final private String label; + @JsonIgnore + final private String content; + final private String relation; + @JsonIgnore + final private TreeNode father; + @JsonIgnore + private List<Exercise> exercises; + @JsonIgnore + private List<UserScorePair> userScores; + public static TreeNodeRepository tnRepo; + + @Node + public static class UserScorePair { + @Id + private final String id; + private final String nodeId; + private final Long userId; + private List<Double> scores; + + public interface MasteryLevel { + String Excellent = "完美"; + String Good = "很好"; + String Average = "一般"; + String Bad = "差"; + + static String getMasteryLevel(double averageScore) { + if (averageScore > 95) + return Excellent; + else if (averageScore > 80) + return Good; + else if (averageScore > 60) + return Average; + else + return Bad; + } + } + + public static class UserScoreSerializer extends StdSerializer<UserScorePair> { + public UserScoreSerializer() { + this(null); + } + + public UserScoreSerializer(Class<UserScorePair> t) { + super(t); + } + + @Override + public void serialize(UserScorePair value, JsonGenerator gen, SerializerProvider provider) throws IOException { + gen.writeStartObject(); + gen.writeStringField("nodeId", value.nodeId); + var avg = value.getAverageScore(); + gen.writeNumberField("averageScore", avg); + gen.writeNumberField("lastScore", value.getLastScore()); + gen.writeStringField("masteryLevel", MasteryLevel.getMasteryLevel(avg)); + gen.writeEndObject(); + } + } + + public UserScorePair(String nodeId, Long userId, List<Double> scores) { + this(String.format("%s.%d", nodeId, userId), nodeId, userId, scores); + } + + @Autowired + @PersistenceCreator + public UserScorePair(String id, String nodeId, Long userId, List<Double> scores) { + this.id = id; + this.nodeId = nodeId; + this.userId = userId; + this.scores = scores; + } + + public String getId() { + return id; + } + + public String getNodeId() { + return nodeId; + } + + public Long getUserId() { + return userId; + } + + public List<Double> getScores() { + return scores; + } + + public Double getLastScore() { + return scores.getLast(); + } + + public Double getAverageScore() { + Double sum = 0.0; + for (var i : scores) + sum += i; + return scores.isEmpty() ? sum : sum / scores.size(); + } + + public void setScores(List<Double> scores) { + this.scores = scores; + } + } + + // MUST only be called during deserialization!! + @JsonCreator + public TreeNode(@JsonProperty("nodeId") String nodeId, @JsonProperty("label") String label, @JsonProperty("content") String content, @JsonProperty("relation") String relation, @JsonProperty("fatherId") String fatherId, @JsonProperty("exercises") List<Exercise> exercises) { + this(nodeId, label, content, relation, tnRepo.findByNodeId(fatherId), exercises, new ArrayList<>()); + } + + public TreeNode(String nodeId, String label, String content, String relation, TreeNode father, List<Exercise> exercises) { + this(nodeId, label, content, relation, father, exercises, new ArrayList<>()); + } + + @Autowired + @PersistenceCreator + public TreeNode(String nodeId, String label, String content, String relation, TreeNode father, List<Exercise> exercises, List<UserScorePair> userScores) { + this.nodeId = nodeId; + this.label = label; + this.content = content; + this.relation = relation; + this.father = father; + this.exercises = exercises; + this.userScores = userScores; + } + + public String getLabel() { + return label; + } + + public String getNodeId() { + return nodeId; + } + + public String getContent() { + return content; + } + + public TreeNode getFather() { + return father; + } + + public String getRelation() { + return relation; + } + + public List<Exercise> getExercises() { + return exercises; + } + + public void setExercises(List<Exercise> exercises) { + this.exercises = exercises; + } + + public List<UserScorePair> getUserScores() { + return userScores; + } + + public UserScorePair getUserScorePair(Long userId, String nodeId) { + var usp = userScores.stream().filter(e -> Objects.equals(e.getUserId(), userId) && e.getNodeId().equals(nodeId)).findFirst(); + return usp.orElse(null); + } + + public void setUserScores(List<UserScorePair> userScores) { + this.userScores = userScores; + } + + public int getLevel() { + var tmp = this; + var level = 1; + while (tmp.father != null) { + tmp = tmp.father; + level++; + } + return level; + } + + public Set<TreeNode> getChildren(List<TreeNode> nodes) { + var children = new HashSet<TreeNode>(); + for (var n : nodes) { + if (n.getFather() == this) { + children.add(n); + } + } + return children; + } +} diff --git a/src/main/java/seu/se/TreeNodeRepository.java b/src/main/java/seu/se/TreeNodeRepository.java new file mode 100644 index 0000000..d7aff83 --- /dev/null +++ b/src/main/java/seu/se/TreeNodeRepository.java @@ -0,0 +1,8 @@ +package seu.se; + +import org.springframework.data.repository.ListCrudRepository; +import org.springframework.data.repository.PagingAndSortingRepository; + +public interface TreeNodeRepository extends PagingAndSortingRepository<TreeNode, String>, ListCrudRepository<TreeNode, String> { + TreeNode findByNodeId(String nodeId); +} diff --git a/src/main/java/seu/se/User.java b/src/main/java/seu/se/User.java new file mode 100644 index 0000000..aa33038 --- /dev/null +++ b/src/main/java/seu/se/User.java @@ -0,0 +1,65 @@ +package seu.se; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; + +import org.springframework.data.neo4j.core.schema.GeneratedValue; +import org.springframework.data.neo4j.core.schema.Id; +import org.springframework.data.neo4j.core.schema.Node; + +@Node +public class User { + @Id + @GeneratedValue + private Long id; + private String name; + @JsonIgnore + private String password; + + @JsonCreator + public User(@JsonProperty("name") String name, @JsonProperty("password") String password) throws UserException { + setName(name); + setPassword(password); + } + + static public class UserException extends Exception { + public UserException() { + } + + public UserException(String message) { + super(message); + } + } + + public String getName() { + return name; + } + + public Long getId() { + return id; + } + + public String getPassword() { + return password; + } + + @Override + public String toString() { + return String.format("User id: %d, name: %s", id, name); + } + + public void setName(String name) throws UserException { + if (name.length() > 22) + throw new UserException("Username too long!"); + this.name = name; + } + + public void setPassword(String password) throws UserException { + if (password.length() < 8) + throw new UserException("Password too short!"); + this.password = password; + } +} + diff --git a/src/main/java/seu/se/UserRepository.java b/src/main/java/seu/se/UserRepository.java new file mode 100644 index 0000000..6e55754 --- /dev/null +++ b/src/main/java/seu/se/UserRepository.java @@ -0,0 +1,11 @@ +package seu.se; + +import org.springframework.data.repository.ListCrudRepository; +import org.springframework.data.repository.PagingAndSortingRepository; + +import java.util.List; + +public interface UserRepository extends PagingAndSortingRepository<User, Long>, ListCrudRepository<User, Long> { + List<User> findByName(String name); + User findById(long id); +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..1c74f98 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,9 @@ +spring.application.name=Neo4j SpringBoot Application + +springdoc.swagger-ui.path=/18f4f672-f9f4-4e8f-92ec-935e514be8ae/swagger-ui +swagger-ui.operationsSorter=method + +spring.neo4j.uri=bolt://localhost:7687 +spring.data.neo4j.database = neo4j +spring.neo4j.authentication.username=neo4j +spring.neo4j.authentication.password=neo4j-admin
\ No newline at end of file diff --git a/src/main/resources/treeNodes.json b/src/main/resources/treeNodes.json new file mode 100644 index 0000000..d1fdb0a --- /dev/null +++ b/src/main/resources/treeNodes.json @@ -0,0 +1,73 @@ +[ + { + "nodeId": "node1", + "label": "Node 1", + "content": "Content node 1", + "relation": "", + "exercises": [ + { + "questionId": "question1.1", + "question": "Test Question 1", + "options": { + "A": "Node 1 Choice A", + "C": "Node 2 Choice C" + }, + "answer": "A" + } + ] + }, + { + "nodeId": "node2", + "label": "Node 2", + "content": "Content node 2", + "relation": "Son", + "fatherId": "node1", + "exercises": [ + { + "questionId": "question2.1", + "question": "Test Question 2", + "options": { + "A": "Node 2 Choice A", + "B": "Node 2 Choice B" + }, + "answer": "A" + } + ] + }, + { + "nodeId": "node3", + "label": "Node 3", + "content": "Content node 3", + "relation": "Sonson", + "fatherId": "node2", + "exercises": [ + { + "questionId": "question3.1", + "question": "Test Question 3", + "options": { + "A": "Node 3 Choice A", + "D": "Node 3 Choice D" + }, + "answer": "A" + } + ] + }, + { + "nodeId": "node4", + "label": "Node 4", + "content": "Content node 4", + "relation": "Sonsonson", + "fatherId": "node2", + "exercises": [ + { + "questionId": "question4.1", + "question": "Test Question 4", + "options": { + "A": "Node 4 Choice A", + "B": "Node 4 Choice B" + }, + "answer": "A" + } + ] + } +] diff --git a/src/main/resources/users.json b/src/main/resources/users.json new file mode 100644 index 0000000..033ed5b --- /dev/null +++ b/src/main/resources/users.json @@ -0,0 +1,6 @@ +[ + { + "name": "Jason", + "password": "suckless" + } +] |