register api

This commit is contained in:
aisensiy 2017-08-08 11:01:06 +08:00
commit ee946e371b
28 changed files with 1011 additions and 0 deletions

25
.gitignore vendored Normal file
View File

@ -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/

38
build.gradle Normal file
View File

@ -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')
}

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -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

172
gradlew vendored Executable file
View File

@ -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" "$@"

84
gradlew.bat vendored Normal file
View File

@ -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

View File

@ -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);
}
}

View File

@ -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;
}

View File

@ -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<Object> handleInvalidRequest(RuntimeException e, WebRequest request) {
InvalidRequestException ire = (InvalidRequestException) e;
List<FieldErrorResource> 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);
}
}

View File

@ -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<FieldErrorResource> fieldErrors;
public ErrorResource(List<FieldErrorResource> fieldErrorResources) {
this.fieldErrors = fieldErrorResources;
}
}

View File

@ -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<ErrorResource> {
@Override
public void serialize(ErrorResource value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
Map<String, List<String>> json = new HashMap<>();
for (FieldErrorResource fieldErrorResource : value.getFieldErrors()) {
if (!json.containsKey(fieldErrorResource.getField())) {
json.put(fieldErrorResource.getField(), new ArrayList<String>());
}
json.get(fieldErrorResource.getField()).add(fieldErrorResource.getMessage());
}
gen.writeStartObject();
for (Map.Entry<String, List<String>> pair : json.entrySet()) {
gen.writeArrayFieldStart(pair.getKey());
pair.getValue().forEach(content -> {
try {
gen.writeString(content);
} catch (IOException e) {
e.printStackTrace();
}
});
gen.writeEndArray();
}
gen.writeEndObject();
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,7 @@
package io.spring.application;
import io.spring.application.user.UserData;
public interface JwtService {
String toToken(UserData userData);
}

View File

@ -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;
}

View File

@ -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;
}
}

View File

@ -0,0 +1,8 @@
package io.spring.application.user;
import org.springframework.data.repository.CrudRepository;
public interface UserReadService extends CrudRepository<UserData, String> {
}

View File

@ -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;
}
}

View File

@ -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<User> findByUsername(String username);
Optional<User> findByEmail(String email);
}

View File

@ -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<User> findByUsername(String username) {
return Optional.ofNullable(userMapper.findByUsername(username));
}
@Override
public Optional<User> findByEmail(String email) {
return Optional.ofNullable(userMapper.findByEmail(email));
}
}

View File

@ -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);
}

View File

@ -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

View File

@ -0,0 +1,7 @@
create table users (
username varchar(255) primary key,
password varchar(255),
email varchar(255) UNIQUE,
bio text,
image varchar(511)
);

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="io.spring.infrastructure.user.UserMapper">
<insert id="save">
insert into users (username, email, password, bio, image) values(
#{user.username},
#{user.email},
#{user.password},
#{user.bio},
#{user.image}
)
</insert>
<select id="findByUsername" resultMap="user">
select * from users where username = #{username}
</select>
<select id="findByEmail" resultMap="user">
select username, email, password, bio, image from users where email = #{email}
</select>
<resultMap id="user" type="io.spring.core.user.User" >
<id column="username" property="username"/>
<result column="email" property="email"/>
<result column="password" property="password"/>
<result column="bio" property="bio"/>
<result column="image" property="image"/>
</resultMap>
</mapper>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- Globally enables or disables any caches configured in any mapper under this configuration -->
<setting name="cacheEnabled" value="true"/>
<!-- Sets the number of seconds the driver will wait for a response from the database -->
<setting name="defaultStatementTimeout" value="3000"/>
<!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- Allows JDBC support for generated keys. A compatible driver is required.
This setting forces generated keys to be used if set to true,
as some drivers deny compatibility but still work -->
<setting name="useGeneratedKeys" value="true"/>
</settings>
<!-- Continue going here -->
</configuration>

View File

@ -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() {
}
}

View File

@ -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<String, Object> param = new HashMap<String, Object>() {{
put("user", new HashMap<String, Object>() {{
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<String, Object> param = new HashMap<String, Object>() {{
put("user", new HashMap<String, Object>() {{
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<String, Object> param = new HashMap<String, Object>() {{
put("user", new HashMap<String, Object>() {{
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<String, Object> param = new HashMap<String, Object>() {{
put("user", new HashMap<String, Object>() {{
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<String, Object> param = new HashMap<String, Object>() {{
put("user", new HashMap<String, Object>() {{
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"));
}
}

View File

@ -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<User> userOptional = userRepository.findByUsername("aisensiy");
assertThat(userOptional.get(), is(user));
Optional<User> userOptional2 = userRepository.findByEmail("aisensiy@163.com");
assertThat(userOptional2.get(), is(user));
}
}