diff --git a/spring-boot-quick-start/.gitignore b/spring-boot-quick-start/.gitignore new file mode 100644 index 0000000..82eca33 --- /dev/null +++ b/spring-boot-quick-start/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/spring-boot-quick-start/.mvn/wrapper/maven-wrapper.jar b/spring-boot-quick-start/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..01e6799 Binary files /dev/null and b/spring-boot-quick-start/.mvn/wrapper/maven-wrapper.jar differ diff --git a/spring-boot-quick-start/.mvn/wrapper/maven-wrapper.properties b/spring-boot-quick-start/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..7179346 --- /dev/null +++ b/spring-boot-quick-start/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip diff --git a/spring-boot-quick-start/Java.gitattributes b/spring-boot-quick-start/Java.gitattributes new file mode 100644 index 0000000..583fe84 --- /dev/null +++ b/spring-boot-quick-start/Java.gitattributes @@ -0,0 +1 @@ +static/* linguist-vendored \ No newline at end of file diff --git a/spring-boot-quick-start/mvnw b/spring-boot-quick-start/mvnw new file mode 100644 index 0000000..5551fde --- /dev/null +++ b/spring-boot-quick-start/mvnw @@ -0,0 +1,286 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 +# +# http://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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + 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 + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + 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 + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + wget "$jarUrl" -O "$wrapperJarPath" + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + curl -o "$wrapperJarPath" "$jarUrl" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/spring-boot-quick-start/mvnw.cmd b/spring-boot-quick-start/mvnw.cmd new file mode 100644 index 0000000..e5cfb0a --- /dev/null +++ b/spring-boot-quick-start/mvnw.cmd @@ -0,0 +1,161 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" +FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + echo Found %WRAPPER_JAR% +) else ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" + echo Finished downloading %WRAPPER_JAR% +) +@REM End of extension + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/spring-boot-quick-start/pom.xml b/spring-boot-quick-start/pom.xml new file mode 100644 index 0000000..00916a6 --- /dev/null +++ b/spring-boot-quick-start/pom.xml @@ -0,0 +1,132 @@ + + + 4.0.0 + + com.springboot + QuickStart + 0.0.1-SNAPSHOT + jar + + QuickStart + QuickStart project in spring boot + + + org.springframework.boot + spring-boot-starter-parent + 1.5.14.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-jdbc + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + runtime + + + org.postgresql + postgresql + runtime + + + org.apache.logging.log4j + log4j-core + + + org.slf4j + slf4j-api + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + + + io.springfox + springfox-swagger-ui + 2.1.0 + compile + + + + io.springfox + springfox-swagger2 + 2.1.0 + compile + + + + com.mangofactory + swagger-springmvc + 1.0.2 + + + io.jsonwebtoken + jjwt + 0.7.0 + + + + com.nimbusds + nimbus-jose-jwt + 4.23 + + + com.googlecode.json-simple + json-simple + + + com.sun.jersey + jersey-client + 1.8 + + + ma.glasnost.orika + orika-core + 1.4.5 + + + + + org.apache.httpcomponents + httpclient + 4.5.3 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/QuickStartApplication.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/QuickStartApplication.java new file mode 100644 index 0000000..4fe06a2 --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/QuickStartApplication.java @@ -0,0 +1,35 @@ +package com.springboot.quickstart; + +import static springfox.documentation.builders.PathSelectors.regex; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@SpringBootApplication +@EnableSwagger2 +public class QuickStartApplication { + + public static void main(String[] args) { + SpringApplication.run(QuickStartApplication.class, args); + } + + @Bean + public Docket newsApi() { + return new Docket(DocumentationType.SWAGGER_2).groupName("springboot").apiInfo(apiInfo()).select() + .paths(regex("/.*")).build(); + } + + private ApiInfo apiInfo() { + return new ApiInfoBuilder().title("SpringBoot REST API with Swagger") + .description("SpringBoot REST API with Swagger").termsOfServiceUrl("") + .license("Apache License Version 2.0").licenseUrl("StudentProject").version("2.0").build(); + } + +} diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/ApiError.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/ApiError.java new file mode 100644 index 0000000..8b192e9 --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/ApiError.java @@ -0,0 +1,83 @@ +package com.springboot.quickstart.common; + +import java.util.Date; + +import org.springframework.http.HttpStatus; + +public class ApiError { + + public HttpStatus error; + public String message; + public Integer status; + public String path; + public Date timestamp; + public String response; + + public ApiError() { + + } + + public ApiError(HttpStatus error, String message, int status, String path, Date timestamp) { + super(); + this.error = error; + this.message = message; + this.status = status; + this.path = path; + this.timestamp = timestamp; + } + + public ApiError(HttpStatus error, Integer HttpStatus) { + super(); + this.error = error; + this.message = "No message available"; + } + + public HttpStatus getError() { + return error; + } + + public void setError(HttpStatus error) { + this.error = error; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public Date getTimestamp() { + return timestamp; + } + + public void setTimestamp(Date timestamp) { + this.timestamp = timestamp; + } + + public String getResponse() { + return response; + } + + public void setResponse(String response) { + this.response = response; + } + +} \ No newline at end of file diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/CommonResponse.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/CommonResponse.java new file mode 100644 index 0000000..a2e2324 --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/CommonResponse.java @@ -0,0 +1,40 @@ +package com.springboot.quickstart.common; + +public class CommonResponse { + + private Long id; + private String message; + + public CommonResponse() { + super(); + // TODO Auto-generated constructor stub + } + + public CommonResponse(Long id, String message) { + super(); + this.id = id; + this.message = message; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @Override + public String toString() { + return "CommonResponse [id=" + id + ", message=" + message + "]"; + } + +} diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/DatabaseOperations.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/DatabaseOperations.java new file mode 100644 index 0000000..b3d5fc1 --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/DatabaseOperations.java @@ -0,0 +1,17 @@ +package com.springboot.quickstart.common; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Component; + +@Component +public class DatabaseOperations { + + @Autowired + JdbcTemplate jdbcTemplate; + + public Long getNextVal() { + return Long.valueOf(jdbcTemplate.queryForObject("select nextval('quickstart.sequence_id')", String.class)); + } + +} diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/ErrorCode.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/ErrorCode.java new file mode 100644 index 0000000..0172a5a --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/ErrorCode.java @@ -0,0 +1,30 @@ +package com.springboot.quickstart.common; + +public enum ErrorCode { + + INPUT_INVALID_PAYLOAD("invalid.request.payload"), INVALID_QUERY_PARAM_VALUE( + "input.query.param.value"), INVALID_REQUEST_PAYLOAD_DATATYPE( + "invalid.request.payload.datatype"), RESOURCE_NOT_FOUND("resource.not.found"), MISC_CLIENT_ERROR( + "misc.client.error"), MISC_SERVER_ERROR("misc.server.error"), AUTHORIZATION_ERROR( + "authorization.error"), AUTHENTICATION_ERROR( + "authentication.error"), FORBIDDEN_ERROR( + "forbidden.error"), REPOSITORY_ERROR( + "repository.error"), EXTERNAL_SYSTEM_ERROR( + "external.system.error"), INVALID_FILE_EXTENSION_ERROR( + "invalid.file.extension"), INVALID_FILE_COLUMN( + "invalid.file.column.error"), INVALID_FILE( + "invalid.file"), ELASTIC_SEARCH_INDEX_ERROR( + "elastic.search.index.error"), INVALID_REQUEST_VALUE( + "input.request.value"); + + private String resourceBundleProperty; + + private ErrorCode(String resourceBundleProperty) { + this.resourceBundleProperty = resourceBundleProperty; + } + + public String getResourceBundlePropertyName() { + return resourceBundleProperty; + } + +} diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/ErrorMessage.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/ErrorMessage.java new file mode 100644 index 0000000..516504e --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/ErrorMessage.java @@ -0,0 +1,10 @@ +package com.springboot.quickstart.common; + +public class ErrorMessage { + + public static String BAD_REQUEST = "Bad Request"; + public static final String NULL_POINTER_EXCEPTION = "Null pointer exception occured"; + public static final String SQL_EXCEPTION = "Error raised due to sql exception"; + public static final String INVALID_TOKEN = "Invalid access token supplied"; + +} diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/IPValidator.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/IPValidator.java new file mode 100644 index 0000000..67bbe4e --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/IPValidator.java @@ -0,0 +1,36 @@ +package com.springboot.quickstart.common; + +import java.util.UUID; + +import org.springframework.stereotype.Service; + +@Service +public class IPValidator { + + public boolean isValidString(final String input) { + if (input == null || input.trim().isEmpty()) { + return false; + } + return true; + } + + public boolean isNullOrEmpty(final Object input) { + if (input == null) { + return true; + } + if (input instanceof String) { + String checkEmpty = (String) input; + if (checkEmpty.trim().isEmpty()) { + return true; + } + } + return false; + } + + public boolean isValidUUID(UUID input) { + if (input == null) { + return false; + } + return true; + } +} diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/JWTAuthentication.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/JWTAuthentication.java new file mode 100644 index 0000000..3084364 --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/JWTAuthentication.java @@ -0,0 +1,75 @@ +package com.springboot.quickstart.common; + +import java.io.UnsupportedEncodingException; +import java.util.Date; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Component; + +import com.springboot.quickstart.exceptions.InvalidTokenException; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.ExpiredJwtException; +import io.jsonwebtoken.Jws; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.MalformedJwtException; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.SignatureException; +import io.jsonwebtoken.UnsupportedJwtException; + +@Component +public class JWTAuthentication { + private static final Logger LOGGER = LoggerFactory.getLogger(JWTAuthentication.class); + @Autowired + JdbcTemplate jdbcTemplate; + + public String getToken(Long userId) { + String jwt = null; + try { + long time = System.currentTimeMillis(); + jwt = Jwts.builder().setSubject("users/TzMUocMF4p").setExpiration(new Date(time + time / 3)) + .claim("user_id", userId).signWith(SignatureAlgorithm.HS256, "praveenSecretKey".getBytes("UTF-8")) + .compact(); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return jwt; + + } + + public Long verifyToken(String authToken) { + Jws claims = null; + try { + claims = Jwts.parser().setSigningKey("praveenSecretKey".getBytes("UTF-8")).parseClaimsJws(authToken); + } catch (ExpiredJwtException e) { + e.printStackTrace(); + throw new InvalidTokenException(ErrorCode.AUTHORIZATION_ERROR, authToken); + } catch (UnsupportedJwtException e) { + e.printStackTrace(); + throw new InvalidTokenException(ErrorCode.AUTHORIZATION_ERROR, authToken); + } catch (MalformedJwtException e) { + System.out.println("iam excep"); + e.printStackTrace(); + throw new InvalidTokenException(ErrorCode.AUTHORIZATION_ERROR, authToken); + } catch (SignatureException e) { + e.printStackTrace(); + throw new InvalidTokenException(ErrorCode.AUTHORIZATION_ERROR, authToken); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + throw new InvalidTokenException(ErrorCode.AUTHORIZATION_ERROR, authToken); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + throw new InvalidTokenException(ErrorCode.AUTHORIZATION_ERROR, authToken); + } + if (claims == null) { + throw new InvalidTokenException(ErrorCode.AUTHORIZATION_ERROR, authToken); + } + String id; + id = (String) claims.getBody().get("user_id").toString(); + Long userId = Long.valueOf(id); + return userId; + } +} diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/UriConstants.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/UriConstants.java new file mode 100644 index 0000000..18cff0f --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/common/UriConstants.java @@ -0,0 +1,10 @@ +package com.springboot.quickstart.common; + +public class UriConstants { + + public static final String LOGIN = "login"; + public static final String REGISTER = "register"; + public static final String QUICKSTART = "quickstart"; + public static final String USERS = "getAllUsers"; + +} diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/controller/LoginController.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/controller/LoginController.java new file mode 100644 index 0000000..9b664e4 --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/controller/LoginController.java @@ -0,0 +1,45 @@ +package com.springboot.quickstart.controller; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +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 com.springboot.quickstart.common.UriConstants; +import com.springboot.quickstart.dataTransfer.Login; +import com.springboot.quickstart.dataTransfer.LoginResponse; +import com.springboot.quickstart.exceptions.CommonException; +import com.springboot.quickstart.handler.LoginHandler; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; + +@Api(value = "login-api", description = "Login") +@RequestMapping(value = "/quickStart") +@RestController +public class LoginController { + + @Autowired + LoginHandler handler; + public static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class); + + @ApiOperation(value = "User Login Verify") + @ApiResponse(code = 200, message = "Successfully Verified the User") + @RequestMapping(value = UriConstants.LOGIN, method = RequestMethod.POST) + public ResponseEntity userLogin(@RequestBody Login login) { + try { + LoginResponse response = handler.userLogin(login); + return new ResponseEntity(response, HttpStatus.OK); + } catch (Exception exception) { + return CommonException.returnException(exception, LoginResponse.class, + UriConstants.QUICKSTART + "/" + UriConstants.LOGIN); + } + + } +} \ No newline at end of file diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/controller/RegisterController.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/controller/RegisterController.java new file mode 100644 index 0000000..0af94e1 --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/controller/RegisterController.java @@ -0,0 +1,63 @@ +package com.springboot.quickstart.controller; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import com.springboot.quickstart.common.CommonResponse; +import com.springboot.quickstart.common.UriConstants; +import com.springboot.quickstart.exceptions.CommonException; +import com.springboot.quickstart.handler.RegisterHandler; +import com.springboot.quickstart.model.Register; +import com.springboot.quickstart.model.UsersList; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; + +@Api(value = "register-api", description = "Register") +@RequestMapping(value = "/quickstart") +@RestController +public class RegisterController { + + @Autowired + RegisterHandler handler; + + public static final Logger LOGGER = LoggerFactory.getLogger(RegisterController.class); + + @ApiOperation(value = "User Register") + @ApiResponse(code = 200, message = "Successfully Registered the User") + @RequestMapping(value = UriConstants.REGISTER, method = RequestMethod.POST) + public ResponseEntity registerUser(@RequestBody Register register) { + try { + CommonResponse response = handler.registerUser(register); + return new ResponseEntity(response, HttpStatus.OK); + } catch (Exception exception) { + return CommonException.returnException(exception, CommonResponse.class, + UriConstants.QUICKSTART + "/" + UriConstants.REGISTER); + } + + } + + @ApiOperation(value = "GetAll Users") + @ApiResponse(code = 200, message = "Successfully retrieving the Users") + @RequestMapping(value = UriConstants.USERS, method = RequestMethod.POST) + public ResponseEntity getAllUsers(@RequestHeader String authToken) { + try { + UsersList response = handler.getAllUsers(authToken); + return new ResponseEntity(response, HttpStatus.OK); + } catch (Exception exception) { + return CommonException.returnException(exception, UsersList.class, + UriConstants.QUICKSTART + "/" + UriConstants.USERS); + } + + } + +} diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/dataTransfer/Login.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/dataTransfer/Login.java new file mode 100644 index 0000000..3b4f4be --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/dataTransfer/Login.java @@ -0,0 +1,40 @@ +package com.springboot.quickstart.dataTransfer; + +public class Login { + + private String email; + private String password; + + public Login() { + super(); + // TODO Auto-generated constructor stub + } + + public Login(String email, String password) { + super(); + this.email = email; + this.password = password; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public String toString() { + return "Login [email=" + email + ", password=" + password + "]"; + } + +} diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/dataTransfer/LoginResponse.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/dataTransfer/LoginResponse.java new file mode 100644 index 0000000..8ef7acf --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/dataTransfer/LoginResponse.java @@ -0,0 +1,50 @@ +package com.springboot.quickstart.dataTransfer; + +public class LoginResponse { + + private String firstName; + private String lastName; + private String authToken; + + public LoginResponse() { + super(); + // TODO Auto-generated constructor stub + } + + public LoginResponse(String firstName, String lastName, String authToken) { + super(); + this.firstName = firstName; + this.lastName = lastName; + this.authToken = authToken; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getAuthToken() { + return authToken; + } + + public void setAuthToken(String authToken) { + this.authToken = authToken; + } + + @Override + public String toString() { + return "LoginResponse [firstName=" + firstName + ", lastName=" + lastName + ", authToken=" + authToken + "]"; + } + +} diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/exceptions/CommonException.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/exceptions/CommonException.java new file mode 100644 index 0000000..dfb85d2 --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/exceptions/CommonException.java @@ -0,0 +1,58 @@ +package com.springboot.quickstart.exceptions; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Date; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; + +import com.springboot.quickstart.common.ApiError; +import com.springboot.quickstart.common.ErrorMessage; + +@SuppressWarnings("unchecked") +@Component +public class CommonException { + private static final Logger LOGGER = LoggerFactory.getLogger(CommonException.class); + + public static ResponseEntity returnException(Exception exception, Class classType, String path) { + ApiError response = null; + + if (exception instanceof InvalidRequestException) { + response = new ApiError(HttpStatus.BAD_REQUEST, ErrorMessage.BAD_REQUEST, HttpStatus.BAD_REQUEST.value(), + path, new Date()); + return (ResponseEntity) new ResponseEntity(response, HttpStatus.BAD_REQUEST); + } + + if (exception instanceof InvalidTokenException) { + response = new ApiError(HttpStatus.UNAUTHORIZED, ErrorMessage.INVALID_TOKEN, + HttpStatus.UNAUTHORIZED.value(), path, new Date()); + return (ResponseEntity) new ResponseEntity(response, HttpStatus.UNAUTHORIZED); + } + + return null; + } + + public void printNullPointerException(String info, NullPointerException nullPointerException) { + StringWriter sw = new StringWriter(); + nullPointerException.printStackTrace(new PrintWriter(sw)); + String exceptionAsString = sw.toString(); + LOGGER.error("Threw a nullPointerException while " + info + nullPointerException.getMessage()); + LOGGER.error("Exception StackTrace : "); + LOGGER.error(exceptionAsString); + throw new MainRestException(HttpStatus.INTERNAL_SERVER_ERROR.value(), ErrorMessage.NULL_POINTER_EXCEPTION); + } + + public void printException(String info, Exception exception) { + StringWriter sw = new StringWriter(); + exception.printStackTrace(new PrintWriter(sw)); + String exceptionAsString = sw.toString(); + LOGGER.error("Threw an SqlException while " + info); + LOGGER.error("Exception StackTrace : "); + LOGGER.error(exceptionAsString); + throw new MainRestException(HttpStatus.INTERNAL_SERVER_ERROR.value(), ErrorMessage.SQL_EXCEPTION); + } +} \ No newline at end of file diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/exceptions/InvalidRequestException.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/exceptions/InvalidRequestException.java new file mode 100644 index 0000000..2744fee --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/exceptions/InvalidRequestException.java @@ -0,0 +1,17 @@ +package com.springboot.quickstart.exceptions; + +import com.springboot.quickstart.common.ErrorCode; + +public class InvalidRequestException extends MainRestException { + + private static final long serialVersionUID = 1L; + + public InvalidRequestException(ErrorCode errorCode, Object... args) { + super(errorCode, args); + } + + public InvalidRequestException(ErrorCode errorCode, Throwable underlyingException, Object... args) { + super(errorCode, underlyingException, args); + } + +} \ No newline at end of file diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/exceptions/InvalidTokenException.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/exceptions/InvalidTokenException.java new file mode 100644 index 0000000..41d2070 --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/exceptions/InvalidTokenException.java @@ -0,0 +1,12 @@ +package com.springboot.quickstart.exceptions; + +import com.springboot.quickstart.common.ErrorCode; + +public class InvalidTokenException extends MainRestException { + + private static final long serialVersionUID = 1L; + + public InvalidTokenException(ErrorCode errorCode, Object... args) { + super(errorCode, args); + } +} diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/exceptions/MainRestException.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/exceptions/MainRestException.java new file mode 100644 index 0000000..d562efc --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/exceptions/MainRestException.java @@ -0,0 +1,43 @@ +package com.springboot.quickstart.exceptions; + +import com.springboot.quickstart.common.ErrorCode; + +public class MainRestException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + private ErrorCode errorCode; + + private Object[] messagePositionalArgs; + + private int errorCodes; + + public MainRestException(ErrorCode errorCode, Object... messagePositionalArgs) { + this.errorCode = errorCode; + this.messagePositionalArgs = messagePositionalArgs; + } + + public MainRestException(ErrorCode errorCode, Throwable underlyingException, Object... messagePositionalArgs) { + super(underlyingException); + this.errorCode = errorCode; + this.messagePositionalArgs = messagePositionalArgs; + } + + public MainRestException(int errorCodes, Object... messagePositionalArgs) { + this.errorCodes = errorCodes; + this.messagePositionalArgs = messagePositionalArgs; + } + + public ErrorCode getErrorCode() { + return errorCode; + } + + public int getErrorCodes() { + return errorCodes; + } + + public Object[] getMessagePositionalArgs() { + return messagePositionalArgs; + } + +} \ No newline at end of file diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/handler/LoginHandler.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/handler/LoginHandler.java new file mode 100644 index 0000000..0437407 --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/handler/LoginHandler.java @@ -0,0 +1,10 @@ +package com.springboot.quickstart.handler; + +import com.springboot.quickstart.dataTransfer.Login; +import com.springboot.quickstart.dataTransfer.LoginResponse; + +public interface LoginHandler { + + public LoginResponse userLogin(Login login); + +} diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/handler/LoginHandlerImpl.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/handler/LoginHandlerImpl.java new file mode 100644 index 0000000..07f2d44 --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/handler/LoginHandlerImpl.java @@ -0,0 +1,27 @@ +package com.springboot.quickstart.handler; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.springboot.quickstart.dataTransfer.Login; +import com.springboot.quickstart.dataTransfer.LoginResponse; +import com.springboot.quickstart.service.LoginService; + +@Service +public class LoginHandlerImpl implements LoginHandler { + + @Autowired + LoginService loginService; + + @Override + public LoginResponse userLogin(Login login) { + LoginResponse response = null; + try { + response = loginService.userLogin(login); + } catch (Exception exception) { + throw exception; + } + return response; + } + +} diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/handler/RegisterHandler.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/handler/RegisterHandler.java new file mode 100644 index 0000000..74f56f7 --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/handler/RegisterHandler.java @@ -0,0 +1,13 @@ +package com.springboot.quickstart.handler; + +import com.springboot.quickstart.common.CommonResponse; +import com.springboot.quickstart.model.Register; +import com.springboot.quickstart.model.UsersList; + +public interface RegisterHandler { + + public CommonResponse registerUser(Register register); + + public UsersList getAllUsers(String authToken); + +} diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/handler/RegisterHandlerImpl.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/handler/RegisterHandlerImpl.java new file mode 100644 index 0000000..b204f15 --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/handler/RegisterHandlerImpl.java @@ -0,0 +1,66 @@ +package com.springboot.quickstart.handler; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.springboot.quickstart.common.CommonResponse; +import com.springboot.quickstart.common.ErrorCode; +import com.springboot.quickstart.common.IPValidator; +import com.springboot.quickstart.common.JWTAuthentication; +import com.springboot.quickstart.exceptions.InvalidRequestException; +import com.springboot.quickstart.exceptions.InvalidTokenException; +import com.springboot.quickstart.model.Register; +import com.springboot.quickstart.model.UsersList; +import com.springboot.quickstart.service.RegisterService; + +@Service +public class RegisterHandlerImpl implements RegisterHandler { + + private static final Logger LOGGER = LoggerFactory.getLogger(RegisterHandlerImpl.class); + + @Autowired + IPValidator validator; + + @Autowired + RegisterService service; + + @Autowired + JWTAuthentication jwtAuthentication; + + @Override + public CommonResponse registerUser(Register register) { + CommonResponse response = null; + try { + if (validator.isNullOrEmpty(register)) { + throw new InvalidRequestException(ErrorCode.INPUT_INVALID_PAYLOAD, "register"); + } + response = service.registerUser(register); + + } catch (Exception exception) { + throw exception; + } + return response; + } + + @Override + public UsersList getAllUsers(String authToken) { + UsersList response = null; + try { + Long userId = jwtAuthentication.verifyToken(authToken); + if (userId == null) { + throw new InvalidTokenException(ErrorCode.AUTHORIZATION_ERROR, authToken); + } + response = service.getAllUsers(); + + } catch (InvalidTokenException e) { + System.out.println("iam here..."); + throw e; + } catch (Exception e) { + throw e; + } + return response; + } + +} diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/model/Register.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/model/Register.java new file mode 100644 index 0000000..1274842 --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/model/Register.java @@ -0,0 +1,71 @@ +package com.springboot.quickstart.model; + +public class Register { + + private Long userId; + private String firstname; + private String lastname; + private String email; + private String password; + + public Register() { + super(); + // TODO Auto-generated constructor stub + } + + public Register(Long userId, String firstname, String lastname, String email, String password) { + super(); + this.userId = userId; + this.firstname = firstname; + this.lastname = lastname; + this.email = email; + this.password = password; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getFirstname() { + return firstname; + } + + public void setFirstname(String firstname) { + this.firstname = firstname; + } + + public String getLastname() { + return lastname; + } + + public void setLastname(String lastname) { + this.lastname = lastname; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public String toString() { + return "Register [userId=" + userId + ", firstname=" + firstname + ", lastname=" + lastname + ", email=" + email + + ", password=" + password + "]"; + } + +} diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/model/UsersList.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/model/UsersList.java new file mode 100644 index 0000000..bfdf078 --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/model/UsersList.java @@ -0,0 +1,42 @@ +package com.springboot.quickstart.model; + +import java.util.List; + +public class UsersList { + + private List users; + private Long count; + + public UsersList() { + super(); + // TODO Auto-generated constructor stub + } + + public UsersList(List users, Long count) { + super(); + this.users = users; + this.count = count; + } + + public List getUsers() { + return users; + } + + public void setUsers(List users) { + this.users = users; + } + + public Long getCount() { + return count; + } + + public void setCount(Long count) { + this.count = count; + } + + @Override + public String toString() { + return "UsersList [users=" + users + ", count=" + count + "]"; + } + +} diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/service/LoginService.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/service/LoginService.java new file mode 100644 index 0000000..d9e25a8 --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/service/LoginService.java @@ -0,0 +1,10 @@ +package com.springboot.quickstart.service; + +import com.springboot.quickstart.dataTransfer.Login; +import com.springboot.quickstart.dataTransfer.LoginResponse; + +public interface LoginService { + + public LoginResponse userLogin(Login login); + +} diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/service/LoginServiceImpl.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/service/LoginServiceImpl.java new file mode 100644 index 0000000..bf2819e --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/service/LoginServiceImpl.java @@ -0,0 +1,41 @@ +package com.springboot.quickstart.service; + +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; + +import com.springboot.quickstart.common.JWTAuthentication; +import com.springboot.quickstart.dataTransfer.Login; +import com.springboot.quickstart.dataTransfer.LoginResponse; + +@Service +public class LoginServiceImpl implements LoginService { + + @Autowired + JdbcTemplate jdbctemplate; + + @Autowired + JWTAuthentication jwtAuthentication; + + @Override + public LoginResponse userLogin(Login login) { + LoginResponse response = null; + try { + String sql = "select user_id as userId,firstname,lastname from quickstart.users where email = ? and password = ?"; + List> rows = jdbctemplate.queryForList(sql, login.getEmail(), login.getPassword()); + for (Map rs : rows) { + response = new LoginResponse(); + response.setFirstName((String) rs.get("firstname")); + response.setLastName((String) rs.get("lastname")); + response.setAuthToken(jwtAuthentication.getToken((Long) rs.get("userId"))); + } + + } catch (Exception e) { + } + return response; + } + +} diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/service/RegisterService.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/service/RegisterService.java new file mode 100644 index 0000000..87905b0 --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/service/RegisterService.java @@ -0,0 +1,13 @@ +package com.springboot.quickstart.service; + +import com.springboot.quickstart.common.CommonResponse; +import com.springboot.quickstart.model.Register; +import com.springboot.quickstart.model.UsersList; + +public interface RegisterService { + + public CommonResponse registerUser(Register register); + + public UsersList getAllUsers(); + +} diff --git a/spring-boot-quick-start/src/main/java/com/springboot/quickstart/service/RegisterServiceImpl.java b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/service/RegisterServiceImpl.java new file mode 100644 index 0000000..9810739 --- /dev/null +++ b/spring-boot-quick-start/src/main/java/com/springboot/quickstart/service/RegisterServiceImpl.java @@ -0,0 +1,69 @@ +package com.springboot.quickstart.service; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; + +import com.springboot.quickstart.common.CommonResponse; +import com.springboot.quickstart.common.DatabaseOperations; +import com.springboot.quickstart.model.Register; +import com.springboot.quickstart.model.UsersList; + +@Service +public class RegisterServiceImpl implements RegisterService { + + @Autowired + JdbcTemplate jdbctemplate; + + @Autowired + DatabaseOperations databaseOperations; + + @Override + public CommonResponse registerUser(Register register) { + CommonResponse response = null; + Long userId = databaseOperations.getNextVal(); + + String sql = "insert into quickstart.users(user_id,firstname,lastname,email,password) values(?,?,?,?,?) "; + int rs = jdbctemplate.update(sql, userId, register.getFirstname(), register.getLastname(), register.getEmail(), + register.getPassword()); + if (rs > 0) { + response = new CommonResponse(); + response.setId(userId); + response.setMessage("Successfully registered User"); + } + + return response; + } + + @Override + public UsersList getAllUsers() { + UsersList response = new UsersList(); + List usersList = new ArrayList<>(); + Register user = null; + Long count = null; + try { + String sql = "SELECT count(*) over() as count, user_id as userId, firstname, lastname, email FROM quickstart.users "; + List> rows = jdbctemplate.queryForList(sql); + count = (long) rows.size(); + for (Map rs : rows) { + user = new Register(); + user.setFirstname((String) rs.get("firstname")); + user.setLastname((String) rs.get("lastname")); + user.setUserId((Long) rs.get("userId")); + user.setEmail((String) rs.get("email")); + usersList.add(user); + } + + response.setUsers(usersList); + response.setCount(count); + } catch (Exception e) { + + } + return response; + } + +} diff --git a/spring-boot-quick-start/src/main/resources/application.properties b/spring-boot-quick-start/src/main/resources/application.properties new file mode 100644 index 0000000..4440eea --- /dev/null +++ b/spring-boot-quick-start/src/main/resources/application.properties @@ -0,0 +1,5 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/Praveen +spring.datasource.username=postgres +spring.datasource.password=praveen +spring.jackson.serialization.write-dates-as-timestamps:false +spring.jackson.date-format=yyyy-mm-dd \ No newline at end of file diff --git a/spring-boot-quick-start/src/test/java/com/springboot/quickstart/QuickStartApplicationTests.java b/spring-boot-quick-start/src/test/java/com/springboot/quickstart/QuickStartApplicationTests.java new file mode 100644 index 0000000..5378ea0 --- /dev/null +++ b/spring-boot-quick-start/src/test/java/com/springboot/quickstart/QuickStartApplicationTests.java @@ -0,0 +1,16 @@ +package com.springboot.quickstart; + +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 QuickStartApplicationTests { + + @Test + public void contextLoads() { + } + +}