commit ee946e371b7a1ebb67b3704ce2ac5fe77281bfe1 Author: aisensiy Date: Tue Aug 8 11:01:06 2017 +0800 register api diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c9f7010 --- /dev/null +++ b/.gitignore @@ -0,0 +1,25 @@ +.gradle +/build/ +!gradle/wrapper/gradle-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..8756d43 --- /dev/null +++ b/build.gradle @@ -0,0 +1,38 @@ +buildscript { + ext { + springBootVersion = '1.5.6.RELEASE' + } + repositories { + mavenCentral() + } + dependencies { + classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") + } +} + +apply plugin: 'java' +apply plugin: 'eclipse' +apply plugin: 'idea' +apply plugin: 'org.springframework.boot' + +version = '0.0.1-SNAPSHOT' +sourceCompatibility = 1.8 + +repositories { + mavenCentral() +} + + +dependencies { + compile('org.springframework.boot:spring-boot-starter-data-jpa') + compile('org.flywaydb:flyway-core') + compile('org.springframework.boot:spring-boot-starter-hateoas') + compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.0') + compile('org.springframework.boot:spring-boot-starter-web') + compileOnly('org.projectlombok:lombok') + runtime('com.h2database:h2') + testCompile 'io.rest-assured:rest-assured:3.0.2' + testCompile('org.springframework.boot:spring-boot-starter-test') + testCompile('org.springframework.restdocs:spring-restdocs-mockmvc') + testCompile('org.mybatis.spring.boot:mybatis-spring-boot-starter-test:1.3.0') +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1a958be Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..8767f3b --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Aug 07 11:04:20 CST 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-3.5.1-all.zip diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..543c9aa --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# 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 + ;; + 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" + which java >/dev/null 2>&1 || 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 + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a userData-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save ( ) { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..e95643d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@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=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@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= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +: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 %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="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! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/main/java/io/spring/RealworldApplication.java b/src/main/java/io/spring/RealworldApplication.java new file mode 100644 index 0000000..65ea98f --- /dev/null +++ b/src/main/java/io/spring/RealworldApplication.java @@ -0,0 +1,12 @@ +package io.spring; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class RealworldApplication { + + public static void main(String[] args) { + SpringApplication.run(RealworldApplication.class, args); + } +} diff --git a/src/main/java/io/spring/api/UsersApi.java b/src/main/java/io/spring/api/UsersApi.java new file mode 100644 index 0000000..5e2dbae --- /dev/null +++ b/src/main/java/io/spring/api/UsersApi.java @@ -0,0 +1,73 @@ +package io.spring.api; + +import com.fasterxml.jackson.annotation.JsonRootName; +import io.spring.api.exception.InvalidRequestException; +import io.spring.application.user.UserQueryService; +import io.spring.core.user.User; +import io.spring.core.user.UserRepository; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.hibernate.validator.constraints.Email; +import org.hibernate.validator.constraints.NotBlank; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import javax.validation.Valid; + +@RestController +@RequestMapping("/users") +public class UsersApi { + private UserRepository userRepository; + private UserQueryService userQueryService; + private String defaultImage; + + @Autowired + public UsersApi(UserRepository userRepository, UserQueryService userQueryService, @Value("${image.default}") String defaultImage) { + this.userRepository = userRepository; + this.userQueryService = userQueryService; + this.defaultImage = defaultImage; + } + + @RequestMapping(method = RequestMethod.POST) + public ResponseEntity creeteUser(@Valid @RequestBody RegisterParam registerParam, BindingResult bindingResult) { + if (bindingResult.hasErrors()) { + throw new InvalidRequestException(bindingResult); + } + if (userRepository.findByUsername(registerParam.getUsername()).isPresent()) { + bindingResult.rejectValue("username", "DUPLICATED", "duplicated username"); + throw new InvalidRequestException(bindingResult); + } + + if (userRepository.findByEmail(registerParam.getEmail()).isPresent()) { + bindingResult.rejectValue("email", "DUPLICATED", "duplicated email"); + throw new InvalidRequestException(bindingResult); + } + User user = new User( + registerParam.getEmail(), + registerParam.getUsername(), + registerParam.getPassword(), + "", + defaultImage); + userRepository.save(user); + return ResponseEntity.status(201).body(userQueryService.fetchCreatedUser(user.getUsername())); + } +} + +@Getter +@JsonRootName("user") +@NoArgsConstructor +class RegisterParam { + @NotBlank(message = "can't be empty") + @Email(message = "should be an email") + private String email; + @NotBlank(message = "can't be empty") + private String username; + @NotBlank(message = "can't be empty") + private String password; +} diff --git a/src/main/java/io/spring/api/exception/CustomizeExceptionHandler.java b/src/main/java/io/spring/api/exception/CustomizeExceptionHandler.java new file mode 100644 index 0000000..c577eee --- /dev/null +++ b/src/main/java/io/spring/api/exception/CustomizeExceptionHandler.java @@ -0,0 +1,37 @@ +package io.spring.api.exception; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +import java.util.List; +import java.util.stream.Collectors; + +import static org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY; + +@RestControllerAdvice +public class CustomizeExceptionHandler extends ResponseEntityExceptionHandler { + + @ExceptionHandler({InvalidRequestException.class}) + public ResponseEntity handleInvalidRequest(RuntimeException e, WebRequest request) { + InvalidRequestException ire = (InvalidRequestException) e; + + List errorResources = ire.getErrors().getFieldErrors().stream().map(fieldError -> + new FieldErrorResource( + fieldError.getObjectName(), + fieldError.getField(), + fieldError.getCode(), + fieldError.getDefaultMessage())).collect(Collectors.toList()); + + ErrorResource error = new ErrorResource(errorResources); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + + return handleExceptionInternal(e, error, headers, UNPROCESSABLE_ENTITY, request); + } +} diff --git a/src/main/java/io/spring/api/exception/ErrorResource.java b/src/main/java/io/spring/api/exception/ErrorResource.java new file mode 100644 index 0000000..84c8256 --- /dev/null +++ b/src/main/java/io/spring/api/exception/ErrorResource.java @@ -0,0 +1,22 @@ +package io.spring.api.exception; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonRootName; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@JsonSerialize(using = ErrorResourceSerializer.class) +@JsonIgnoreProperties(ignoreUnknown = true) +@lombok.Getter +@JsonRootName("errors") +public class ErrorResource { + private List fieldErrors; + + public ErrorResource(List fieldErrorResources) { + this.fieldErrors = fieldErrorResources; + } +} diff --git a/src/main/java/io/spring/api/exception/ErrorResourceSerializer.java b/src/main/java/io/spring/api/exception/ErrorResourceSerializer.java new file mode 100644 index 0000000..01380d8 --- /dev/null +++ b/src/main/java/io/spring/api/exception/ErrorResourceSerializer.java @@ -0,0 +1,38 @@ +package io.spring.api.exception; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ErrorResourceSerializer extends JsonSerializer { + @Override + public void serialize(ErrorResource value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException { + Map> json = new HashMap<>(); + for (FieldErrorResource fieldErrorResource : value.getFieldErrors()) { + if (!json.containsKey(fieldErrorResource.getField())) { + json.put(fieldErrorResource.getField(), new ArrayList()); + } + json.get(fieldErrorResource.getField()).add(fieldErrorResource.getMessage()); + } + gen.writeStartObject(); + for (Map.Entry> pair : json.entrySet()) { + gen.writeArrayFieldStart(pair.getKey()); + pair.getValue().forEach(content -> { + try { + gen.writeString(content); + } catch (IOException e) { + e.printStackTrace(); + } + }); + gen.writeEndArray(); + } + gen.writeEndObject(); + } +} diff --git a/src/main/java/io/spring/api/exception/FieldErrorResource.java b/src/main/java/io/spring/api/exception/FieldErrorResource.java new file mode 100644 index 0000000..e0815a7 --- /dev/null +++ b/src/main/java/io/spring/api/exception/FieldErrorResource.java @@ -0,0 +1,21 @@ +package io.spring.api.exception; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Getter; + +@JsonIgnoreProperties(ignoreUnknown = true) +@Getter +public class FieldErrorResource { + private String resource; + private String field; + private String code; + private String message; + + public FieldErrorResource(String resource, String field, String code, String message) { + + this.resource = resource; + this.field = field; + this.code = code; + this.message = message; + } +} diff --git a/src/main/java/io/spring/api/exception/InvalidRequestException.java b/src/main/java/io/spring/api/exception/InvalidRequestException.java new file mode 100644 index 0000000..a2747c4 --- /dev/null +++ b/src/main/java/io/spring/api/exception/InvalidRequestException.java @@ -0,0 +1,20 @@ +package io.spring.api.exception; + +import com.fasterxml.jackson.annotation.JsonRootName; +import org.springframework.validation.BindingResult; +import org.springframework.validation.Errors; + +@SuppressWarnings("serial") +@JsonRootName("errors") +public class InvalidRequestException extends RuntimeException { + private final Errors errors; + + public InvalidRequestException(Errors errors) { + super(""); + this.errors = errors; + } + + public Errors getErrors() { + return errors; + } +} diff --git a/src/main/java/io/spring/application/JwtService.java b/src/main/java/io/spring/application/JwtService.java new file mode 100644 index 0000000..c67c05b --- /dev/null +++ b/src/main/java/io/spring/application/JwtService.java @@ -0,0 +1,7 @@ +package io.spring.application; + +import io.spring.application.user.UserData; + +public interface JwtService { + String toToken(UserData userData); +} diff --git a/src/main/java/io/spring/application/user/UserData.java b/src/main/java/io/spring/application/user/UserData.java new file mode 100644 index 0000000..6e87c79 --- /dev/null +++ b/src/main/java/io/spring/application/user/UserData.java @@ -0,0 +1,22 @@ +package io.spring.application.user; + +import com.fasterxml.jackson.annotation.JsonRootName; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +@JsonRootName("user") +public class UserData { + private String email; + @Id + private String username; + private String bio; + private String image; +} diff --git a/src/main/java/io/spring/application/user/UserQueryService.java b/src/main/java/io/spring/application/user/UserQueryService.java new file mode 100644 index 0000000..94aa18f --- /dev/null +++ b/src/main/java/io/spring/application/user/UserQueryService.java @@ -0,0 +1,42 @@ +package io.spring.application.user; + +import com.fasterxml.jackson.annotation.JsonRootName; +import io.spring.application.JwtService; +import lombok.Getter; +import org.springframework.stereotype.Service; + +@Service +public class UserQueryService { + private UserReadService userReadService; + private JwtService jwtService; + + public UserQueryService(UserReadService userReadService, JwtService jwtService) { + this.userReadService = userReadService; + this.jwtService = jwtService; + } + + public UserWithToken fetchCreatedUser(String username) { + UserData userData = userReadService.findOne(username); + return new UserWithToken(userData, jwtService.toToken(userData)); + } + +} + +@JsonRootName("user") +@Getter +class UserWithToken { + private String email; + private String username; + private String bio; + private String image; + private String token; + + public UserWithToken(UserData userData, String token) { + this.email = userData.getEmail(); + this.username = userData.getUsername(); + this.bio = userData.getBio(); + this.image = userData.getImage(); + this.token = token; + } + +} \ No newline at end of file diff --git a/src/main/java/io/spring/application/user/UserReadService.java b/src/main/java/io/spring/application/user/UserReadService.java new file mode 100644 index 0000000..37306b1 --- /dev/null +++ b/src/main/java/io/spring/application/user/UserReadService.java @@ -0,0 +1,8 @@ +package io.spring.application.user; + +import org.springframework.data.repository.CrudRepository; + +public interface UserReadService extends CrudRepository { + +} + diff --git a/src/main/java/io/spring/core/user/User.java b/src/main/java/io/spring/core/user/User.java new file mode 100644 index 0000000..aa2b1c9 --- /dev/null +++ b/src/main/java/io/spring/core/user/User.java @@ -0,0 +1,25 @@ +package io.spring.core.user; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor +@EqualsAndHashCode(of = {"username"}) +public class User { + private String email; + private String username; + private String password; + private String bio; + private String image; + + public User(String email, String username, String password, String bio, String image) { + this.email = email; + this.username = username; + this.password = password; + this.bio = bio; + this.image = image; + } +} diff --git a/src/main/java/io/spring/core/user/UserRepository.java b/src/main/java/io/spring/core/user/UserRepository.java new file mode 100644 index 0000000..82603fd --- /dev/null +++ b/src/main/java/io/spring/core/user/UserRepository.java @@ -0,0 +1,14 @@ +package io.spring.core.user; + +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface UserRepository { + void save(User user); + + Optional findByUsername(String username); + + Optional findByEmail(String email); +} diff --git a/src/main/java/io/spring/infrastructure/user/MyBatisUserRepository.java b/src/main/java/io/spring/infrastructure/user/MyBatisUserRepository.java new file mode 100644 index 0000000..83d8215 --- /dev/null +++ b/src/main/java/io/spring/infrastructure/user/MyBatisUserRepository.java @@ -0,0 +1,33 @@ +package io.spring.infrastructure.user; + +import io.spring.core.user.User; +import io.spring.core.user.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public class MyBatisUserRepository implements UserRepository { + private final UserMapper userMapper; + + @Autowired + public MyBatisUserRepository(UserMapper userMapper) { + this.userMapper = userMapper; + } + + @Override + public void save(User user) { + userMapper.save(user); + } + + @Override + public Optional findByUsername(String username) { + return Optional.ofNullable(userMapper.findByUsername(username)); + } + + @Override + public Optional findByEmail(String email) { + return Optional.ofNullable(userMapper.findByEmail(email)); + } +} diff --git a/src/main/java/io/spring/infrastructure/user/UserMapper.java b/src/main/java/io/spring/infrastructure/user/UserMapper.java new file mode 100644 index 0000000..6568443 --- /dev/null +++ b/src/main/java/io/spring/infrastructure/user/UserMapper.java @@ -0,0 +1,15 @@ +package io.spring.infrastructure.user; + +import io.spring.core.user.User; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.springframework.stereotype.Component; + +@Component +@Mapper +public interface UserMapper { + void save(@Param("user") User user); + + User findByUsername(@Param("username") String username); + User findByEmail(@Param("email") String email); +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..e10b0be --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,6 @@ +spring.jackson.deserialization.UNWRAP_ROOT_VALUE=true +spring.jackson.serialization.WRAP_ROOT_VALUE=true +image.default=https://static.productionready.io/images/smiley-cyrus.jpg + +mybatis.config-location=mybatis-config.xml +mybatis.mapper-locations=mapper/*Mapper.xml \ No newline at end of file diff --git a/src/main/resources/db/migration/V1__create_tables.sql b/src/main/resources/db/migration/V1__create_tables.sql new file mode 100644 index 0000000..edf79d7 --- /dev/null +++ b/src/main/resources/db/migration/V1__create_tables.sql @@ -0,0 +1,7 @@ +create table users ( + username varchar(255) primary key, + password varchar(255), + email varchar(255) UNIQUE, + bio text, + image varchar(511) +); diff --git a/src/main/resources/mapper/UserMapper.xml b/src/main/resources/mapper/UserMapper.xml new file mode 100644 index 0000000..f7a2cf9 --- /dev/null +++ b/src/main/resources/mapper/UserMapper.xml @@ -0,0 +1,27 @@ + + + + + insert into users (username, email, password, bio, image) values( + #{user.username}, + #{user.email}, + #{user.password}, + #{user.bio}, + #{user.image} + ) + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mybatis-config.xml b/src/main/resources/mybatis-config.xml new file mode 100644 index 0000000..946065f --- /dev/null +++ b/src/main/resources/mybatis-config.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + diff --git a/src/test/java/io/spring/RealworldApplicationTests.java b/src/test/java/io/spring/RealworldApplicationTests.java new file mode 100644 index 0000000..a3e8d49 --- /dev/null +++ b/src/test/java/io/spring/RealworldApplicationTests.java @@ -0,0 +1,16 @@ +package io.spring; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class RealworldApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/src/test/java/io/spring/api/UsersApiTest.java b/src/test/java/io/spring/api/UsersApiTest.java new file mode 100644 index 0000000..239f98c --- /dev/null +++ b/src/test/java/io/spring/api/UsersApiTest.java @@ -0,0 +1,186 @@ +package io.spring.api; + +import io.restassured.RestAssured; +import io.spring.application.JwtService; +import io.spring.application.user.UserData; +import io.spring.application.user.UserReadService; +import io.spring.core.user.User; +import io.spring.core.user.UserRepository; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.*; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@RunWith(SpringRunner.class) +public class UsersApiTest { + @LocalServerPort + private int port; + + @MockBean + private UserRepository userRepository; + + @MockBean + private JwtService jwtService; + + @MockBean + private UserReadService userReadService; + + + @Before + public void setUp() throws Exception { + RestAssured.port = port; + } + + @Test + public void should_create_user_success() throws Exception { + String email = "john@jacob.com"; + String username = "johnjacob"; + + when(jwtService.toToken(any())).thenReturn("123"); + UserData userData = new UserData(email, username, "", "https://static.productionready.io/images/smiley-cyrus.jpg"); + when(userReadService.findOne(eq(username))).thenReturn(userData); + + Map param = new HashMap() {{ + put("user", new HashMap() {{ + put("email", email); + put("password", "johnnyjacob"); + put("username", username); + }}); + }}; + + given() + .contentType("application/json") + .body(param) + .when() + .post("/users") + .then() + .statusCode(201) + .body("user.email", equalTo(email)) + .body("user.username", equalTo(username)) + .body("user.bio", equalTo("")) + .body("user.image", equalTo("https://static.productionready.io/images/smiley-cyrus.jpg")) + .body("user.token", equalTo("123")); + + verify(userRepository).save(any()); + } + + @Test + public void should_show_error_message_for_blank_username() throws Exception { + + String email = "john@jacob.com"; + String username = ""; + + Map param = new HashMap() {{ + put("user", new HashMap() {{ + put("email", email); + put("password", "johnnyjacob"); + put("username", username); + }}); + }}; + + given() + .contentType("application/json") + .body(param) + .when() + .post("/users") + .then() + .statusCode(422) + .body("errors.username[0]", equalTo("can't be empty")); + } + + @Test + public void should_show_error_message_for_invalid_email() throws Exception { + String email = "johnxjacob.com"; + String username = "johnjacob"; + + Map param = new HashMap() {{ + put("user", new HashMap() {{ + put("email", email); + put("password", "johnnyjacob"); + put("username", username); + }}); + }}; + + given() + .contentType("application/json") + .body(param) + .when() + .post("/users") + .then() + .statusCode(422) + .body("errors.email[0]", equalTo("should be an email")); + + } + + @Test + public void should_show_error_for_duplicated_username() throws Exception { + String email = "john@jacob.com"; + String username = "johnjacob"; + + when(userRepository.findByUsername(eq(username))).thenReturn(Optional.of(new User( + email, username, "123", "bio", "" + ))); + + Map param = new HashMap() {{ + put("user", new HashMap() {{ + put("email", email); + put("password", "johnnyjacob"); + put("username", username); + }}); + }}; + + given() + .contentType("application/json") + .body(param) + .when() + .post("/users") + .then() + .statusCode(422) + .body("errors.username[0]", equalTo("duplicated username")); + } + + @Test + public void should_show_error_for_duplicated_email() throws Exception { + String email = "john@jacob.com"; + String username = "johnjacob2"; + + when(userRepository.findByEmail(eq(email))).thenReturn(Optional.of(new User( + email, username, "123", "bio", "" + ))); + + when(userRepository.findByUsername(eq(username))).thenReturn(Optional.empty()); + + Map param = new HashMap() {{ + put("user", new HashMap() {{ + put("email", email); + put("password", "johnnyjacob"); + put("username", username); + }}); + }}; + + given() + .contentType("application/json") + .body(param) + .when() + .post("/users") + .then() + .statusCode(422) + .body("errors.email[0]", equalTo("duplicated email")); + } +} \ No newline at end of file diff --git a/src/test/java/io/spring/infrastructure/user/MyBatisUserRepositoryTest.java b/src/test/java/io/spring/infrastructure/user/MyBatisUserRepositoryTest.java new file mode 100644 index 0000000..96205ed --- /dev/null +++ b/src/test/java/io/spring/infrastructure/user/MyBatisUserRepositoryTest.java @@ -0,0 +1,33 @@ +package io.spring.infrastructure.user; + +import io.spring.core.user.User; +import io.spring.core.user.UserRepository; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mybatis.spring.boot.test.autoconfigure.MybatisTest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.Optional; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.*; + +@RunWith(SpringRunner.class) +@MybatisTest +@Import(MyBatisUserRepository.class) +public class MyBatisUserRepositoryTest { + @Autowired + private UserRepository userRepository; + + @Test + public void should_save_and_fetch_user_success() throws Exception { + User user = new User("aisensiy@163.com", "aisensiy", "123", "", "default"); + userRepository.save(user); + Optional userOptional = userRepository.findByUsername("aisensiy"); + assertThat(userOptional.get(), is(user)); + Optional userOptional2 = userRepository.findByEmail("aisensiy@163.com"); + assertThat(userOptional2.get(), is(user)); + } +} \ No newline at end of file