├── .gitignore ├── .mvn └── wrapper │ ├── MavenWrapperDownloader.java │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── stacksimplify │ │ └── restservices │ │ ├── Hello │ │ ├── HelloWorldController.java │ │ └── UserDetails.java │ │ ├── SpringbootBuildingblocksApplication.java │ │ ├── config │ │ ├── AppConfig.java │ │ ├── MonitoringConfig.java │ │ └── SwaggerConfig.java │ │ ├── controllers │ │ ├── OrderController.java │ │ ├── OrderHateoasController.java │ │ ├── UserController.java │ │ ├── UserCustomHeaderVersioningController.java │ │ ├── UserHateoasController.java │ │ ├── UserJsonViewController.java │ │ ├── UserMapStructController.java │ │ ├── UserMappingJacksonController.java │ │ ├── UserMediaTypeVersioningController.java │ │ ├── UserModelMapperController.java │ │ ├── UserRequestParameterVersioningController.java │ │ └── UserUriVersioningController.java │ │ ├── dtos │ │ ├── UserDtoV1.java │ │ ├── UserDtoV2.java │ │ ├── UserMmDto.java │ │ └── UserMsDto.java │ │ ├── entities │ │ ├── Order.java │ │ ├── User.java │ │ └── Views.java │ │ ├── exceptions │ │ ├── CustomErrorDetails.java │ │ ├── CustomGlobalExceptionHandler.java │ │ ├── GlobalRestControllerAdviceExceptionHandler.java │ │ ├── UserExistsException.java │ │ ├── UserNameNotFoundException.java │ │ └── UserNotFoundException.java │ │ ├── mappers │ │ └── UserMapper.java │ │ ├── repositories │ │ ├── OrderRepository.java │ │ └── UserRepository.java │ │ └── services │ │ └── UserService.java └── resources │ ├── application.properties │ ├── data.sql │ ├── messages.properties │ └── messages_fr.properties └── test └── java └── com └── stacksimplify └── restservices └── SpringbootBuildingblocksApplicationTests.java /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | https://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | import java.io.File; 21 | import java.io.FileInputStream; 22 | import java.io.FileOutputStream; 23 | import java.io.IOException; 24 | import java.net.URL; 25 | import java.nio.channels.Channels; 26 | import java.nio.channels.ReadableByteChannel; 27 | import java.util.Properties; 28 | 29 | public class MavenWrapperDownloader { 30 | 31 | /** 32 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 33 | */ 34 | private static final String DEFAULT_DOWNLOAD_URL = 35 | "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; 36 | 37 | /** 38 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 39 | * use instead of the default one. 40 | */ 41 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 42 | ".mvn/wrapper/maven-wrapper.properties"; 43 | 44 | /** 45 | * Path where the maven-wrapper.jar will be saved to. 46 | */ 47 | private static final String MAVEN_WRAPPER_JAR_PATH = 48 | ".mvn/wrapper/maven-wrapper.jar"; 49 | 50 | /** 51 | * Name of the property which should be used to override the default download url for the wrapper. 52 | */ 53 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 54 | 55 | public static void main(String args[]) { 56 | System.out.println("- Downloader started"); 57 | File baseDirectory = new File(args[0]); 58 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 59 | 60 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 61 | // wrapperUrl parameter. 62 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 63 | String url = DEFAULT_DOWNLOAD_URL; 64 | if(mavenWrapperPropertyFile.exists()) { 65 | FileInputStream mavenWrapperPropertyFileInputStream = null; 66 | try { 67 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 68 | Properties mavenWrapperProperties = new Properties(); 69 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 70 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 71 | } catch (IOException e) { 72 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 73 | } finally { 74 | try { 75 | if(mavenWrapperPropertyFileInputStream != null) { 76 | mavenWrapperPropertyFileInputStream.close(); 77 | } 78 | } catch (IOException e) { 79 | // Ignore ... 80 | } 81 | } 82 | } 83 | System.out.println("- Downloading from: : " + url); 84 | 85 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 86 | if(!outputFile.getParentFile().exists()) { 87 | if(!outputFile.getParentFile().mkdirs()) { 88 | System.out.println( 89 | "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 90 | } 91 | } 92 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 93 | try { 94 | downloadFileFromURL(url, outputFile); 95 | System.out.println("Done"); 96 | System.exit(0); 97 | } catch (Throwable e) { 98 | System.out.println("- Error downloading"); 99 | e.printStackTrace(); 100 | System.exit(1); 101 | } 102 | } 103 | 104 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 105 | URL website = new URL(urlString); 106 | ReadableByteChannel rbc; 107 | rbc = Channels.newChannel(website.openStream()); 108 | FileOutputStream fos = new FileOutputStream(destination); 109 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 110 | fos.close(); 111 | rbc.close(); 112 | } 113 | 114 | } 115 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stacksimplify/springboot-buildingblocks/ec1ad43a4e5a5fef34e25b75d564e42d365a1b0d/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip 2 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | ########################################################################################## 204 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 205 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 206 | ########################################################################################## 207 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 208 | if [ "$MVNW_VERBOSE" = true ]; then 209 | echo "Found .mvn/wrapper/maven-wrapper.jar" 210 | fi 211 | else 212 | if [ "$MVNW_VERBOSE" = true ]; then 213 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 214 | fi 215 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" 216 | while IFS="=" read key value; do 217 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 218 | esac 219 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 220 | if [ "$MVNW_VERBOSE" = true ]; then 221 | echo "Downloading from: $jarUrl" 222 | fi 223 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 224 | 225 | if command -v wget > /dev/null; then 226 | if [ "$MVNW_VERBOSE" = true ]; then 227 | echo "Found wget ... using wget" 228 | fi 229 | wget "$jarUrl" -O "$wrapperJarPath" 230 | elif command -v curl > /dev/null; then 231 | if [ "$MVNW_VERBOSE" = true ]; then 232 | echo "Found curl ... using curl" 233 | fi 234 | curl -o "$wrapperJarPath" "$jarUrl" 235 | else 236 | if [ "$MVNW_VERBOSE" = true ]; then 237 | echo "Falling back to using Java to download" 238 | fi 239 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 240 | if [ -e "$javaClass" ]; then 241 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 242 | if [ "$MVNW_VERBOSE" = true ]; then 243 | echo " - Compiling MavenWrapperDownloader.java ..." 244 | fi 245 | # Compiling the Java class 246 | ("$JAVA_HOME/bin/javac" "$javaClass") 247 | fi 248 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 249 | # Running the downloader 250 | if [ "$MVNW_VERBOSE" = true ]; then 251 | echo " - Running MavenWrapperDownloader.java ..." 252 | fi 253 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 254 | fi 255 | fi 256 | fi 257 | fi 258 | ########################################################################################## 259 | # End of extension 260 | ########################################################################################## 261 | 262 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 263 | if [ "$MVNW_VERBOSE" = true ]; then 264 | echo $MAVEN_PROJECTBASEDIR 265 | fi 266 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 267 | 268 | # For Cygwin, switch paths to Windows format before running java 269 | if $cygwin; then 270 | [ -n "$M2_HOME" ] && 271 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 272 | [ -n "$JAVA_HOME" ] && 273 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 274 | [ -n "$CLASSPATH" ] && 275 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 276 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 277 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 278 | fi 279 | 280 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 281 | 282 | exec "$JAVACMD" \ 283 | $MAVEN_OPTS \ 284 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 285 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 286 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 287 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" 124 | FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( 125 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 126 | ) 127 | 128 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 129 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 130 | if exist %WRAPPER_JAR% ( 131 | echo Found %WRAPPER_JAR% 132 | ) else ( 133 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 134 | echo Downloading from: %DOWNLOAD_URL% 135 | powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" 136 | echo Finished downloading %WRAPPER_JAR% 137 | ) 138 | @REM End of extension 139 | 140 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 141 | if ERRORLEVEL 1 goto error 142 | goto end 143 | 144 | :error 145 | set ERROR_CODE=1 146 | 147 | :end 148 | @endlocal & set ERROR_CODE=%ERROR_CODE% 149 | 150 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 151 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 152 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 153 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 154 | :skipRcPost 155 | 156 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 157 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 158 | 159 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 160 | 161 | exit /B %ERROR_CODE% 162 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.1.6.RELEASE 9 | 10 | 11 | com.stacksimplify.restservices 12 | springboot-buildingblocks 13 | 0.0.1-SNAPSHOT 14 | springboot-buildingblocks 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 1.3.0.Final 20 | 3.8.1 21 | 22 | 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-data-jpa 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-web 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-actuator 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-hateoas 39 | 40 | 41 | 42 | org.springframework.boot 43 | spring-boot-devtools 44 | runtime 45 | true 46 | 47 | 48 | com.h2database 49 | h2 50 | runtime 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-starter-test 55 | test 56 | 57 | 58 | org.modelmapper 59 | modelmapper 60 | 2.3.5 61 | 62 | 63 | org.mapstruct 64 | mapstruct-jdk8 65 | ${org.mapstruct.version} 66 | 67 | 68 | com.fasterxml.jackson.dataformat 69 | jackson-dataformat-xml 70 | 71 | 72 | io.springfox 73 | springfox-swagger2 74 | 2.9.2 75 | 76 | 77 | io.springfox 78 | springfox-swagger-ui 79 |      2.9.2 80 | 81 | 82 | io.springfox 83 | springfox-bean-validators 84 | 2.9.2 85 | 86 | 87 | de.codecentric 88 | spring-boot-admin-starter-client 89 | 2.1.6 90 | 91 | 92 | io.micrometer 93 | micrometer-core 94 | 1.2.0 95 | 96 | 97 | io.micrometer 98 | micrometer-registry-jmx 99 | 1.2.0 100 | 101 | 102 | io.micrometer 103 | micrometer-registry-appoptics 104 | 1.2.0 105 | 106 | 107 | 108 | 109 | 110 | 111 | org.apache.maven.plugins 112 | maven-compiler-plugin 113 | 114 | ${java.version} 115 | ${java.version} 116 | 117 | 118 | org.mapstruct 119 | mapstruct-processor 120 | ${org.mapstruct.version} 121 | 122 | 123 | 124 | 125 | 126 | org.springframework.boot 127 | spring-boot-maven-plugin 128 | 129 | 130 | build-info 131 | 132 | build-info 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/Hello/HelloWorldController.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.Hello; 2 | 3 | import java.util.Locale; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.context.i18n.LocaleContextHolder; 7 | import org.springframework.context.support.ResourceBundleMessageSource; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.RequestHeader; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | //Controller 13 | @RestController 14 | public class HelloWorldController { 15 | 16 | @Autowired 17 | private ResourceBundleMessageSource messageSource; 18 | 19 | //Simple Method 20 | //URI - /helloworld 21 | //GET 22 | //@RequestMapping(method = RequestMethod.GET, path = "/helloworld") 23 | @GetMapping("/helloworld1") 24 | public String helloWorld() { 25 | return "Hello World1"; 26 | } 27 | 28 | @GetMapping("/helloworld-bean") 29 | public UserDetails helloWorldBean() { 30 | return new UserDetails("Kalyan", "Reddy", "Hyderabad"); 31 | } 32 | 33 | @GetMapping("/hello-int") 34 | public String getMessagesInI18NFormat(@RequestHeader(name = "Accept-Language", required=false) 35 | String locale) { 36 | return messageSource.getMessage("label.hello", null, new Locale(locale)); 37 | 38 | } 39 | 40 | 41 | @GetMapping("/hello-int2") 42 | public String getMessagesInI18NFormat2() { 43 | return messageSource.getMessage("label.hello", null, LocaleContextHolder.getLocale()); 44 | 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/Hello/UserDetails.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.Hello; 2 | 3 | public class UserDetails { 4 | 5 | private String firstname; 6 | private String lastname; 7 | private String city; 8 | 9 | 10 | //Fields Constructor 11 | public UserDetails(String firstname, String lastname, String city) { 12 | this.firstname = firstname; 13 | this.lastname = lastname; 14 | this.city = city; 15 | } 16 | //Getters and Setters 17 | public String getFirstname() { 18 | return firstname; 19 | } 20 | public void setFirstname(String firstname) { 21 | this.firstname = firstname; 22 | } 23 | public String getLastname() { 24 | return lastname; 25 | } 26 | public void setLastname(String lastname) { 27 | this.lastname = lastname; 28 | } 29 | public String getCity() { 30 | return city; 31 | } 32 | public void setCity(String city) { 33 | this.city = city; 34 | } 35 | 36 | //To String 37 | @Override 38 | public String toString() { 39 | return "UserDetails [firstname=" + firstname + ", lastname=" + lastname + ", city=" + city + "]"; 40 | } 41 | 42 | 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/SpringbootBuildingblocksApplication.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices; 2 | 3 | import java.util.Locale; 4 | 5 | import org.springframework.boot.SpringApplication; 6 | import org.springframework.boot.autoconfigure.SpringBootApplication; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.support.ResourceBundleMessageSource; 9 | import org.springframework.web.servlet.LocaleResolver; 10 | import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver; 11 | // 12 | @SpringBootApplication 13 | public class SpringbootBuildingblocksApplication { 14 | 15 | public static void main(String[] args) { 16 | SpringApplication.run(SpringbootBuildingblocksApplication.class, args); 17 | } 18 | 19 | @Bean 20 | public LocaleResolver localeResolver() { 21 | AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver(); 22 | localeResolver.setDefaultLocale(Locale.US); 23 | return localeResolver; 24 | } 25 | 26 | @Bean 27 | public ResourceBundleMessageSource messageSource() { 28 | ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); 29 | messageSource.setBasename("messages"); 30 | return messageSource; 31 | } 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/config/AppConfig.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.config; 2 | 3 | import org.modelmapper.ModelMapper; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | 7 | @Configuration 8 | public class AppConfig { 9 | 10 | @Bean 11 | public ModelMapper modelMapper() { 12 | return new ModelMapper(); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/config/MonitoringConfig.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | 5 | import io.micrometer.appoptics.AppOpticsConfig; 6 | import io.micrometer.appoptics.AppOpticsMeterRegistry; 7 | import io.micrometer.core.instrument.Clock; 8 | import io.micrometer.core.instrument.MeterRegistry; 9 | import io.micrometer.core.lang.Nullable; 10 | 11 | @Configuration 12 | public class MonitoringConfig { 13 | 14 | AppOpticsConfig appopticsConfig = new AppOpticsConfig() { 15 | @Override 16 | public String apiToken() { 17 | return "1477e14d2e9b27904decc48e97c077665ca393844d03f3a0fea6b68f37e7a3d8"; 18 | } 19 | 20 | @Override 21 | @Nullable 22 | public String get(String k) { 23 | return null; 24 | } 25 | }; 26 | MeterRegistry registry = new AppOpticsMeterRegistry(appopticsConfig, Clock.SYSTEM); 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/config/SwaggerConfig.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.context.annotation.Import; 6 | 7 | import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; 8 | import springfox.documentation.builders.ApiInfoBuilder; 9 | import springfox.documentation.builders.PathSelectors; 10 | import springfox.documentation.builders.RequestHandlerSelectors; 11 | import springfox.documentation.service.ApiInfo; 12 | import springfox.documentation.service.Contact; 13 | import springfox.documentation.spi.DocumentationType; 14 | import springfox.documentation.spring.web.plugins.Docket; 15 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 16 | 17 | @Configuration 18 | @EnableSwagger2 19 | @Import(BeanValidatorPluginsConfiguration.class) 20 | public class SwaggerConfig { 21 | 22 | @Bean 23 | public Docket api() { 24 | return new Docket(DocumentationType.SWAGGER_2) 25 | .apiInfo(getApiInfo()) 26 | .select() 27 | .apis(RequestHandlerSelectors.basePackage("com.stacksimplify.restservices")) 28 | .paths(PathSelectors.ant("/users/**")) 29 | .build(); 30 | } 31 | 32 | //Swagger Metadata: http://localhost:8080/v2/api-docs 33 | //Swagger UI URL: http://localhost:8080/swagger-ui.html 34 | 35 | private ApiInfo getApiInfo() { 36 | return new ApiInfoBuilder() 37 | .title("StackSimplify User Management Service") 38 | .description("This page lists all API's of User Management") 39 | .version("2.0") 40 | .contact(new Contact("Kalyan Reddy", "https://www.stacksimplify.com", "stacksimplify@gmail.com")) 41 | .license("License 2.0") 42 | .licenseUrl("https://www.stacksimplify.com/license.html") 43 | .build(); 44 | } 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/controllers/OrderController.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.controllers; 2 | 3 | import java.util.List; 4 | import java.util.Optional; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.PathVariable; 9 | import org.springframework.web.bind.annotation.PostMapping; 10 | import org.springframework.web.bind.annotation.RequestBody; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | import com.stacksimplify.restservices.entities.Order; 15 | import com.stacksimplify.restservices.entities.User; 16 | import com.stacksimplify.restservices.exceptions.UserNotFoundException; 17 | import com.stacksimplify.restservices.repositories.OrderRepository; 18 | import com.stacksimplify.restservices.repositories.UserRepository; 19 | 20 | @RestController 21 | @RequestMapping(value = "/users") 22 | public class OrderController { 23 | 24 | @Autowired 25 | private UserRepository userRepository; 26 | 27 | @Autowired 28 | private OrderRepository orderRepository; 29 | 30 | // get All Orders for a user 31 | 32 | @GetMapping("/{userid}/orders") 33 | public List getAllOrders(@PathVariable Long userid) throws UserNotFoundException { 34 | 35 | Optional userOptional = userRepository.findById(userid); 36 | if (!userOptional.isPresent()) 37 | throw new UserNotFoundException("User Not Found"); 38 | 39 | return userOptional.get().getOrders(); 40 | } 41 | 42 | // Create Order 43 | 44 | @PostMapping("{userid}/orders") 45 | public Order createOrder(@PathVariable Long userid, @RequestBody Order order) throws UserNotFoundException { 46 | Optional userOptional = userRepository.findById(userid); 47 | 48 | if (!userOptional.isPresent()) 49 | throw new UserNotFoundException("User Not Found"); 50 | 51 | User user = userOptional.get(); 52 | order.setUser(user); 53 | return orderRepository.save(order); 54 | 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/controllers/OrderHateoasController.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.controllers; 2 | 3 | import java.util.List; 4 | import java.util.Optional; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.hateoas.Resources; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.PathVariable; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RestController; 12 | 13 | import com.stacksimplify.restservices.entities.Order; 14 | import com.stacksimplify.restservices.entities.User; 15 | import com.stacksimplify.restservices.exceptions.UserNotFoundException; 16 | import com.stacksimplify.restservices.repositories.OrderRepository; 17 | import com.stacksimplify.restservices.repositories.UserRepository; 18 | 19 | @RestController 20 | @RequestMapping(value = "/hateoas/users") 21 | public class OrderHateoasController { 22 | 23 | @Autowired 24 | private UserRepository userRepository; 25 | 26 | @Autowired 27 | private OrderRepository orderRepository; 28 | 29 | // get All Orders for a user 30 | 31 | @GetMapping("/{userid}/orders") 32 | public Resources getAllOrders(@PathVariable Long userid) throws UserNotFoundException { 33 | 34 | Optional userOptional = userRepository.findById(userid); 35 | if (!userOptional.isPresent()) 36 | throw new UserNotFoundException("User Not Found"); 37 | 38 | List allorders = userOptional.get().getOrders(); 39 | Resources finalResources = new Resources(allorders); 40 | 41 | return finalResources; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/controllers/UserController.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.controllers; 2 | 3 | import java.util.List; 4 | import java.util.Optional; 5 | 6 | import javax.validation.Valid; 7 | import javax.validation.constraints.Min; 8 | 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.http.HttpHeaders; 11 | import org.springframework.http.HttpStatus; 12 | import org.springframework.http.MediaType; 13 | import org.springframework.http.ResponseEntity; 14 | import org.springframework.validation.annotation.Validated; 15 | import org.springframework.web.bind.annotation.DeleteMapping; 16 | import org.springframework.web.bind.annotation.GetMapping; 17 | import org.springframework.web.bind.annotation.PathVariable; 18 | import org.springframework.web.bind.annotation.PostMapping; 19 | import org.springframework.web.bind.annotation.PutMapping; 20 | import org.springframework.web.bind.annotation.RequestBody; 21 | import org.springframework.web.bind.annotation.RequestMapping; 22 | import org.springframework.web.bind.annotation.RestController; 23 | import org.springframework.web.server.ResponseStatusException; 24 | import org.springframework.web.util.UriComponentsBuilder; 25 | 26 | import com.stacksimplify.restservices.entities.User; 27 | import com.stacksimplify.restservices.exceptions.UserExistsException; 28 | import com.stacksimplify.restservices.exceptions.UserNameNotFoundException; 29 | import com.stacksimplify.restservices.exceptions.UserNotFoundException; 30 | import com.stacksimplify.restservices.services.UserService; 31 | 32 | import io.swagger.annotations.Api; 33 | import io.swagger.annotations.ApiOperation; 34 | import io.swagger.annotations.ApiParam; 35 | 36 | //Controller - 37 | @Api(tags = "User Management RESTful Services", value = "UserController", description = "Controller for User Management Service") 38 | @RestController 39 | @Validated 40 | @RequestMapping(value = "/users") 41 | public class UserController { 42 | 43 | // Autowire the UserService 44 | @Autowired 45 | private UserService userService; 46 | 47 | // getAllUsers Method 48 | @ApiOperation(value = "Retrieve list of users") 49 | @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) 50 | public List getAllUsers() { 51 | 52 | return userService.getAllUsers(); 53 | 54 | } 55 | 56 | // Create User Method 57 | // @RequestBody Annotation 58 | // @PostMapping Annotation 59 | @ApiOperation(value = "Creates a new user") 60 | @PostMapping 61 | public ResponseEntity createUser(@ApiParam("User information for a new user to be created.") @Valid @RequestBody User user, UriComponentsBuilder builder) { 62 | try { 63 | userService.createUser(user); 64 | HttpHeaders headers = new HttpHeaders(); 65 | headers.setLocation(builder.path("/users/{id}").buildAndExpand(user.getUserid()).toUri()); 66 | return new ResponseEntity(headers, HttpStatus.CREATED); 67 | 68 | } catch(UserExistsException ex) { 69 | throw new ResponseStatusException(HttpStatus.BAD_REQUEST, ex.getMessage()); 70 | } 71 | } 72 | 73 | // getUserById 74 | @GetMapping("/{id}") 75 | public User getUserById(@PathVariable("id") @Min(1) Long id) { 76 | 77 | try { 78 | Optional userOptional = userService.getUserById(id); 79 | return userOptional.get(); 80 | } catch (UserNotFoundException ex) { 81 | throw new ResponseStatusException(HttpStatus.NOT_FOUND, ex.getMessage()); 82 | } 83 | 84 | } 85 | 86 | // updateUserById 87 | @PutMapping("/{id}") 88 | public User updateUserById(@PathVariable("id") Long id, @RequestBody User user) { 89 | 90 | try { 91 | return userService.updateUserById(id, user); 92 | } catch (UserNotFoundException ex) { 93 | throw new ResponseStatusException(HttpStatus.BAD_REQUEST, ex.getMessage()); 94 | } 95 | 96 | } 97 | 98 | // deleteUserById 99 | @DeleteMapping("/{id}") 100 | public void deleteUserById(@PathVariable("id") Long id) { 101 | userService.deleteUserById(id); 102 | } 103 | 104 | // getUserByUsername 105 | @GetMapping("/byusername/{username}") 106 | public User getUserByUsername(@PathVariable("username") String username) throws UserNameNotFoundException { 107 | User user = userService.getUserByUsername(username); 108 | if(user == null) 109 | throw new UserNameNotFoundException("Username: '" + username + "' not found in User repository"); 110 | return user; 111 | 112 | } 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | } 134 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/controllers/UserCustomHeaderVersioningController.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.controllers; 2 | 3 | import java.util.Optional; 4 | 5 | import javax.validation.constraints.Min; 6 | 7 | import org.modelmapper.ModelMapper; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.PathVariable; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | import com.stacksimplify.restservices.dtos.UserDtoV1; 15 | import com.stacksimplify.restservices.dtos.UserDtoV2; 16 | import com.stacksimplify.restservices.entities.User; 17 | import com.stacksimplify.restservices.exceptions.UserNotFoundException; 18 | import com.stacksimplify.restservices.services.UserService; 19 | 20 | @RestController 21 | @RequestMapping("/versioning/header/users") 22 | public class UserCustomHeaderVersioningController { 23 | 24 | @Autowired 25 | private UserService userService; 26 | 27 | @Autowired 28 | private ModelMapper modelMapper; 29 | 30 | // Custom Header based Versioning - V1 31 | @GetMapping(value = "/{id}", headers = "API-VERSION=1") 32 | public UserDtoV1 getUserById(@PathVariable("id") @Min(1) Long id) throws UserNotFoundException { 33 | 34 | Optional userOptional = userService.getUserById(id); 35 | 36 | if (!userOptional.isPresent()) { 37 | throw new UserNotFoundException("user not found"); 38 | } 39 | 40 | User user = userOptional.get(); 41 | 42 | UserDtoV1 userDtoV1 = modelMapper.map(user, UserDtoV1.class); 43 | return userDtoV1; 44 | 45 | } 46 | 47 | // Custom Header based Versioning - V2 48 | @GetMapping(value = "/{id}", headers = "API-VERSION=2") 49 | public UserDtoV2 getUserById2(@PathVariable("id") @Min(1) Long id) throws UserNotFoundException { 50 | 51 | Optional userOptional = userService.getUserById(id); 52 | 53 | if (!userOptional.isPresent()) { 54 | throw new UserNotFoundException("user not found"); 55 | } 56 | 57 | User user = userOptional.get(); 58 | 59 | UserDtoV2 userDtoV2 = modelMapper.map(user, UserDtoV2.class); 60 | return userDtoV2; 61 | 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/controllers/UserHateoasController.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.controllers; 2 | 3 | import java.util.List; 4 | import java.util.Optional; 5 | 6 | import javax.validation.constraints.Min; 7 | 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.hateoas.Link; 10 | import org.springframework.hateoas.Resource; 11 | import org.springframework.hateoas.Resources; 12 | import org.springframework.hateoas.mvc.ControllerLinkBuilder; 13 | import org.springframework.http.HttpStatus; 14 | import org.springframework.validation.annotation.Validated; 15 | import org.springframework.web.bind.annotation.GetMapping; 16 | import org.springframework.web.bind.annotation.PathVariable; 17 | import org.springframework.web.bind.annotation.RequestMapping; 18 | import org.springframework.web.bind.annotation.RestController; 19 | import org.springframework.web.server.ResponseStatusException; 20 | 21 | import com.stacksimplify.restservices.entities.User; 22 | import com.stacksimplify.restservices.exceptions.UserNotFoundException; 23 | import com.stacksimplify.restservices.repositories.UserRepository; 24 | import com.stacksimplify.restservices.services.UserService; 25 | import com.stacksimplify.restservices.entities.Order; 26 | @RestController 27 | @RequestMapping(value = "/hateoas/users") 28 | @Validated 29 | public class UserHateoasController { 30 | 31 | @Autowired 32 | private UserRepository userRepository; 33 | 34 | @Autowired 35 | private UserService userService; 36 | 37 | // getUserById 38 | @GetMapping("/{id}") 39 | public Resource getUserById(@PathVariable("id") @Min(1) Long id) { 40 | 41 | try { 42 | Optional userOptional = userService.getUserById(id); 43 | User user = userOptional.get(); 44 | Long userid = user.getUserid(); 45 | Link selflink = ControllerLinkBuilder.linkTo(this.getClass()).slash(userid).withSelfRel(); 46 | user.add(selflink); 47 | Resource finalResource = new Resource(user); 48 | return finalResource; 49 | 50 | } catch (UserNotFoundException ex) { 51 | throw new ResponseStatusException(HttpStatus.NOT_FOUND, ex.getMessage()); 52 | } 53 | 54 | } 55 | 56 | // getAllUsers Method 57 | @GetMapping 58 | public Resources getAllUsers() throws UserNotFoundException { 59 | List allusers = userService.getAllUsers(); 60 | 61 | for(User user : allusers) { 62 | //Self Link 63 | Long userid = user.getUserid(); 64 | Link selflink = ControllerLinkBuilder.linkTo(this.getClass()).slash(userid).withSelfRel(); 65 | user.add(selflink); 66 | 67 | //Relationship link with getAllOrders 68 | Resources orders = ControllerLinkBuilder.methodOn(OrderHateoasController.class) 69 | .getAllOrders(userid); 70 | Link orderslink = ControllerLinkBuilder.linkTo(orders).withRel("all-orders"); 71 | user.add(orderslink); 72 | 73 | } 74 | //Self link for getAllUsers 75 | Link selflinkgetAllUsers = ControllerLinkBuilder.linkTo(this.getClass()).withSelfRel(); 76 | Resources finalResources = new Resources(allusers, selflinkgetAllUsers); 77 | return finalResources; 78 | 79 | } 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/controllers/UserJsonViewController.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.controllers; 2 | 3 | import java.util.Optional; 4 | 5 | import javax.validation.constraints.Min; 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.validation.annotation.Validated; 10 | import org.springframework.web.bind.annotation.GetMapping; 11 | import org.springframework.web.bind.annotation.PathVariable; 12 | import org.springframework.web.bind.annotation.RequestMapping; 13 | import org.springframework.web.bind.annotation.RestController; 14 | import org.springframework.web.server.ResponseStatusException; 15 | 16 | import com.fasterxml.jackson.annotation.JsonView; 17 | import com.stacksimplify.restservices.entities.User; 18 | import com.stacksimplify.restservices.entities.Views; 19 | import com.stacksimplify.restservices.exceptions.UserNotFoundException; 20 | import com.stacksimplify.restservices.services.UserService; 21 | @RestController 22 | @Validated 23 | @RequestMapping(value = "/jsonview/users") 24 | public class UserJsonViewController { 25 | 26 | 27 | // Autowire the UserService 28 | @Autowired 29 | private UserService userService; 30 | 31 | // getUserById - External 32 | @JsonView(Views.External.class) 33 | @GetMapping("/external/{id}") 34 | public Optional getUserById(@PathVariable("id") @Min(1) Long id) { 35 | 36 | try { 37 | return userService.getUserById(id); 38 | } catch (UserNotFoundException ex) { 39 | throw new ResponseStatusException(HttpStatus.NOT_FOUND, ex.getMessage()); 40 | } 41 | 42 | } 43 | 44 | // getUserById - Internal 45 | @GetMapping("/internal/{id}") 46 | @JsonView(Views.Internal.class) 47 | public Optional getUserById2(@PathVariable("id") @Min(1) Long id) { 48 | 49 | try { 50 | return userService.getUserById(id); 51 | } catch (UserNotFoundException ex) { 52 | throw new ResponseStatusException(HttpStatus.NOT_FOUND, ex.getMessage()); 53 | } 54 | 55 | } 56 | 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/controllers/UserMapStructController.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.controllers; 2 | 3 | import java.util.List; 4 | import java.util.Optional; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.PathVariable; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | import com.stacksimplify.restservices.dtos.UserMsDto; 13 | import com.stacksimplify.restservices.entities.User; 14 | import com.stacksimplify.restservices.mappers.UserMapper; 15 | import com.stacksimplify.restservices.repositories.UserRepository; 16 | 17 | @RestController 18 | @RequestMapping("/mapstruct/users") 19 | public class UserMapStructController { 20 | 21 | @Autowired 22 | private UserRepository userRepository; 23 | 24 | @Autowired 25 | private UserMapper userMapper; 26 | 27 | @GetMapping 28 | public List getAllUserDtos() { 29 | return userMapper.usersToUserDtos(userRepository.findAll()); 30 | } 31 | 32 | @GetMapping("/{id}") 33 | public UserMsDto getUserById(@PathVariable Long id) { 34 | Optional userOptional = userRepository.findById(id); 35 | User user = userOptional.get(); 36 | return userMapper.userToUserMsDto(user); 37 | } 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/controllers/UserMappingJacksonController.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.controllers; 2 | 3 | import java.util.HashSet; 4 | import java.util.Optional; 5 | import java.util.Set; 6 | 7 | import javax.validation.constraints.Min; 8 | 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.http.HttpStatus; 11 | import org.springframework.http.converter.json.MappingJacksonValue; 12 | import org.springframework.validation.annotation.Validated; 13 | import org.springframework.web.bind.annotation.GetMapping; 14 | import org.springframework.web.bind.annotation.PathVariable; 15 | import org.springframework.web.bind.annotation.RequestMapping; 16 | import org.springframework.web.bind.annotation.RequestParam; 17 | import org.springframework.web.bind.annotation.RestController; 18 | import org.springframework.web.server.ResponseStatusException; 19 | 20 | import com.fasterxml.jackson.databind.ser.FilterProvider; 21 | import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; 22 | import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; 23 | import com.stacksimplify.restservices.entities.User; 24 | import com.stacksimplify.restservices.exceptions.UserNotFoundException; 25 | import com.stacksimplify.restservices.services.UserService; 26 | 27 | @RestController 28 | @RequestMapping(value = "/jacksonfilter/users") 29 | @Validated 30 | public class UserMappingJacksonController { 31 | 32 | // Autowire the UserService 33 | @Autowired 34 | private UserService userService; 35 | 36 | // getUserById - fields with hashset 37 | @GetMapping("/{id}") 38 | public MappingJacksonValue getUserById(@PathVariable("id") @Min(1) Long id) { 39 | 40 | try { 41 | 42 | Optional userOptional = userService.getUserById(id); 43 | User user = userOptional.get(); 44 | 45 | Set fields = new HashSet(); 46 | fields.add("userid"); 47 | fields.add("username"); 48 | fields.add("ssn"); 49 | fields.add("orders"); 50 | 51 | FilterProvider filterProvider = new SimpleFilterProvider().addFilter("userFilter", 52 | SimpleBeanPropertyFilter.filterOutAllExcept(fields)); 53 | MappingJacksonValue mapper = new MappingJacksonValue(user); 54 | 55 | mapper.setFilters(filterProvider); 56 | return mapper; 57 | 58 | } catch (UserNotFoundException ex) { 59 | throw new ResponseStatusException(HttpStatus.NOT_FOUND, ex.getMessage()); 60 | } 61 | 62 | } 63 | 64 | // getUserById - fields with @RequestParam 65 | @GetMapping("/params/{id}") 66 | public MappingJacksonValue getUserById2(@PathVariable("id") @Min(1) Long id, 67 | @RequestParam Set fields) { 68 | 69 | try { 70 | 71 | Optional userOptional = userService.getUserById(id); 72 | User user = userOptional.get(); 73 | 74 | FilterProvider filterProvider = new SimpleFilterProvider().addFilter("userFilter", 75 | SimpleBeanPropertyFilter.filterOutAllExcept(fields)); 76 | MappingJacksonValue mapper = new MappingJacksonValue(user); 77 | 78 | mapper.setFilters(filterProvider); 79 | return mapper; 80 | 81 | } catch (UserNotFoundException ex) { 82 | throw new ResponseStatusException(HttpStatus.NOT_FOUND, ex.getMessage()); 83 | } 84 | 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/controllers/UserMediaTypeVersioningController.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.controllers; 2 | 3 | import java.util.Optional; 4 | 5 | import javax.validation.constraints.Min; 6 | 7 | import org.modelmapper.ModelMapper; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.PathVariable; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | import com.stacksimplify.restservices.dtos.UserDtoV1; 15 | import com.stacksimplify.restservices.dtos.UserDtoV2; 16 | import com.stacksimplify.restservices.entities.User; 17 | import com.stacksimplify.restservices.exceptions.UserNotFoundException; 18 | import com.stacksimplify.restservices.services.UserService; 19 | 20 | @RestController 21 | @RequestMapping("/versioning/mediatype/users") 22 | public class UserMediaTypeVersioningController { 23 | 24 | @Autowired 25 | private UserService userService; 26 | 27 | @Autowired 28 | private ModelMapper modelMapper; 29 | 30 | // Media Type Versioning - V1 31 | @GetMapping(value = "/{id}", produces="application/vnd.stacksimplify.app-v1+json") 32 | public UserDtoV1 getUserById(@PathVariable("id") @Min(1) Long id) throws UserNotFoundException { 33 | 34 | Optional userOptional = userService.getUserById(id); 35 | 36 | if (!userOptional.isPresent()) { 37 | throw new UserNotFoundException("user not found"); 38 | } 39 | 40 | User user = userOptional.get(); 41 | 42 | UserDtoV1 userDtoV1 = modelMapper.map(user, UserDtoV1.class); 43 | return userDtoV1; 44 | 45 | } 46 | 47 | // Media Type Versioning - V2 48 | @GetMapping(value = "/{id}", produces="application/vnd.stacksimplify.app-v2+json") 49 | public UserDtoV2 getUserById2(@PathVariable("id") @Min(1) Long id) throws UserNotFoundException { 50 | 51 | Optional userOptional = userService.getUserById(id); 52 | 53 | if (!userOptional.isPresent()) { 54 | throw new UserNotFoundException("user not found"); 55 | } 56 | 57 | User user = userOptional.get(); 58 | 59 | UserDtoV2 userDtoV2 = modelMapper.map(user, UserDtoV2.class); 60 | return userDtoV2; 61 | 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/controllers/UserModelMapperController.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.controllers; 2 | 3 | import java.util.Optional; 4 | 5 | import javax.validation.constraints.Min; 6 | 7 | import org.modelmapper.ModelMapper; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.PathVariable; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | import com.stacksimplify.restservices.dtos.UserMmDto; 15 | import com.stacksimplify.restservices.entities.User; 16 | import com.stacksimplify.restservices.exceptions.UserNotFoundException; 17 | import com.stacksimplify.restservices.services.UserService; 18 | 19 | @RestController 20 | @RequestMapping("/modelmapper/users") 21 | public class UserModelMapperController { 22 | 23 | @Autowired 24 | private UserService userService; 25 | 26 | @Autowired 27 | private ModelMapper modelMapper; 28 | 29 | @GetMapping("/{id}") 30 | public UserMmDto getUserById(@PathVariable("id") @Min(1) Long id) throws UserNotFoundException { 31 | 32 | Optional userOptional = userService.getUserById(id); 33 | 34 | if(!userOptional.isPresent()) { 35 | throw new UserNotFoundException("user not found"); 36 | } 37 | 38 | User user = userOptional.get(); 39 | 40 | UserMmDto userMmDto = modelMapper.map(user, UserMmDto.class); 41 | return userMmDto; 42 | 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/controllers/UserRequestParameterVersioningController.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.controllers; 2 | 3 | import java.util.Optional; 4 | 5 | import javax.validation.constraints.Min; 6 | 7 | import org.modelmapper.ModelMapper; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.PathVariable; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | import com.stacksimplify.restservices.dtos.UserDtoV1; 15 | import com.stacksimplify.restservices.dtos.UserDtoV2; 16 | import com.stacksimplify.restservices.entities.User; 17 | import com.stacksimplify.restservices.exceptions.UserNotFoundException; 18 | import com.stacksimplify.restservices.services.UserService; 19 | 20 | @RestController 21 | @RequestMapping("/versioning/params/users") 22 | public class UserRequestParameterVersioningController { 23 | 24 | @Autowired 25 | private UserService userService; 26 | 27 | @Autowired 28 | private ModelMapper modelMapper; 29 | 30 | //Request Parameter based Versioning - V1 31 | @GetMapping(value = "/{id}", params = "version=1") 32 | public UserDtoV1 getUserById(@PathVariable("id") @Min(1) Long id) throws UserNotFoundException { 33 | 34 | Optional userOptional = userService.getUserById(id); 35 | 36 | if(!userOptional.isPresent()) { 37 | throw new UserNotFoundException("user not found"); 38 | } 39 | 40 | User user = userOptional.get(); 41 | 42 | UserDtoV1 userDtoV1 = modelMapper.map(user, UserDtoV1.class); 43 | return userDtoV1; 44 | 45 | } 46 | 47 | 48 | //Request Paramter based Versioning - V2 49 | @GetMapping(value = "/{id}", params = "version=2") 50 | public UserDtoV2 getUserById2(@PathVariable("id") @Min(1) Long id) throws UserNotFoundException { 51 | 52 | Optional userOptional = userService.getUserById(id); 53 | 54 | if(!userOptional.isPresent()) { 55 | throw new UserNotFoundException("user not found"); 56 | } 57 | 58 | User user = userOptional.get(); 59 | 60 | UserDtoV2 userDtoV2 = modelMapper.map(user, UserDtoV2.class); 61 | return userDtoV2; 62 | 63 | } 64 | 65 | 66 | 67 | 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/controllers/UserUriVersioningController.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.controllers; 2 | 3 | import java.util.Optional; 4 | 5 | import javax.validation.constraints.Min; 6 | 7 | import org.modelmapper.ModelMapper; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.PathVariable; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | import com.stacksimplify.restservices.dtos.UserDtoV1; 15 | import com.stacksimplify.restservices.dtos.UserDtoV2; 16 | import com.stacksimplify.restservices.entities.User; 17 | import com.stacksimplify.restservices.exceptions.UserNotFoundException; 18 | import com.stacksimplify.restservices.services.UserService; 19 | 20 | @RestController 21 | @RequestMapping("/versioning/uri/users") 22 | public class UserUriVersioningController { 23 | 24 | @Autowired 25 | private UserService userService; 26 | 27 | @Autowired 28 | private ModelMapper modelMapper; 29 | 30 | //URI based Versioning - V1 31 | @GetMapping({"/v1.0/{id}", "/v1.1/{id}" }) 32 | public UserDtoV1 getUserById(@PathVariable("id") @Min(1) Long id) throws UserNotFoundException { 33 | 34 | Optional userOptional = userService.getUserById(id); 35 | 36 | if(!userOptional.isPresent()) { 37 | throw new UserNotFoundException("user not found"); 38 | } 39 | 40 | User user = userOptional.get(); 41 | 42 | UserDtoV1 userDtoV1 = modelMapper.map(user, UserDtoV1.class); 43 | return userDtoV1; 44 | 45 | } 46 | 47 | 48 | //URI based Versioning - V2 49 | @GetMapping("/v2.0/{id}") 50 | public UserDtoV2 getUserById2(@PathVariable("id") @Min(1) Long id) throws UserNotFoundException { 51 | 52 | Optional userOptional = userService.getUserById(id); 53 | 54 | if(!userOptional.isPresent()) { 55 | throw new UserNotFoundException("user not found"); 56 | } 57 | 58 | User user = userOptional.get(); 59 | 60 | UserDtoV2 userDtoV2 = modelMapper.map(user, UserDtoV2.class); 61 | return userDtoV2; 62 | 63 | } 64 | 65 | 66 | 67 | 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/dtos/UserDtoV1.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.dtos; 2 | 3 | import java.util.List; 4 | 5 | import javax.persistence.Column; 6 | import javax.persistence.GeneratedValue; 7 | import javax.persistence.Id; 8 | import javax.persistence.OneToMany; 9 | import javax.validation.constraints.NotEmpty; 10 | import javax.validation.constraints.Size; 11 | 12 | import com.fasterxml.jackson.annotation.JsonView; 13 | import com.stacksimplify.restservices.entities.Order; 14 | import com.stacksimplify.restservices.entities.Views; 15 | 16 | public class UserDtoV1 { 17 | 18 | private Long userid; 19 | private String username; 20 | private String firstname; 21 | private String lastname; 22 | private String email; 23 | private String role; 24 | private String ssn; 25 | private List orders; 26 | 27 | 28 | 29 | 30 | public UserDtoV1() { 31 | 32 | } 33 | 34 | 35 | public UserDtoV1(Long userid, String username, String firstname, String lastname, String email, String role, 36 | String ssn, List orders) { 37 | super(); 38 | this.userid = userid; 39 | this.username = username; 40 | this.firstname = firstname; 41 | this.lastname = lastname; 42 | this.email = email; 43 | this.role = role; 44 | this.ssn = ssn; 45 | this.orders = orders; 46 | } 47 | 48 | 49 | public Long getUserid() { 50 | return userid; 51 | } 52 | public void setUserid(Long userid) { 53 | this.userid = userid; 54 | } 55 | public String getUsername() { 56 | return username; 57 | } 58 | public void setUsername(String username) { 59 | this.username = username; 60 | } 61 | public String getFirstname() { 62 | return firstname; 63 | } 64 | public void setFirstname(String firstname) { 65 | this.firstname = firstname; 66 | } 67 | public String getLastname() { 68 | return lastname; 69 | } 70 | public void setLastname(String lastname) { 71 | this.lastname = lastname; 72 | } 73 | public String getEmail() { 74 | return email; 75 | } 76 | public void setEmail(String email) { 77 | this.email = email; 78 | } 79 | public String getRole() { 80 | return role; 81 | } 82 | public void setRole(String role) { 83 | this.role = role; 84 | } 85 | public String getSsn() { 86 | return ssn; 87 | } 88 | public void setSsn(String ssn) { 89 | this.ssn = ssn; 90 | } 91 | public List getOrders() { 92 | return orders; 93 | } 94 | public void setOrders(List orders) { 95 | this.orders = orders; 96 | } 97 | 98 | 99 | 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/dtos/UserDtoV2.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.dtos; 2 | 3 | import java.util.List; 4 | 5 | import com.stacksimplify.restservices.entities.Order; 6 | 7 | public class UserDtoV2 { 8 | 9 | private Long userid; 10 | private String username; 11 | private String firstname; 12 | private String lastname; 13 | private String email; 14 | private String role; 15 | private String ssn; 16 | private List orders; 17 | private String address; 18 | 19 | public UserDtoV2() { 20 | 21 | } 22 | 23 | public UserDtoV2(Long userid, String username, String firstname, String lastname, String email, String role, 24 | String ssn, List orders, String address) { 25 | super(); 26 | this.userid = userid; 27 | this.username = username; 28 | this.firstname = firstname; 29 | this.lastname = lastname; 30 | this.email = email; 31 | this.role = role; 32 | this.ssn = ssn; 33 | this.orders = orders; 34 | this.address = address; 35 | } 36 | 37 | public Long getUserid() { 38 | return userid; 39 | } 40 | 41 | public void setUserid(Long userid) { 42 | this.userid = userid; 43 | } 44 | 45 | public String getUsername() { 46 | return username; 47 | } 48 | 49 | public void setUsername(String username) { 50 | this.username = username; 51 | } 52 | 53 | public String getFirstname() { 54 | return firstname; 55 | } 56 | 57 | public void setFirstname(String firstname) { 58 | this.firstname = firstname; 59 | } 60 | 61 | public String getLastname() { 62 | return lastname; 63 | } 64 | 65 | public void setLastname(String lastname) { 66 | this.lastname = lastname; 67 | } 68 | 69 | public String getEmail() { 70 | return email; 71 | } 72 | 73 | public void setEmail(String email) { 74 | this.email = email; 75 | } 76 | 77 | public String getRole() { 78 | return role; 79 | } 80 | 81 | public void setRole(String role) { 82 | this.role = role; 83 | } 84 | 85 | public String getSsn() { 86 | return ssn; 87 | } 88 | 89 | public void setSsn(String ssn) { 90 | this.ssn = ssn; 91 | } 92 | 93 | public List getOrders() { 94 | return orders; 95 | } 96 | 97 | public void setOrders(List orders) { 98 | this.orders = orders; 99 | } 100 | 101 | public String getAddress() { 102 | return address; 103 | } 104 | 105 | public void setAddress(String address) { 106 | this.address = address; 107 | } 108 | 109 | 110 | 111 | 112 | } 113 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/dtos/UserMmDto.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.dtos; 2 | 3 | import java.util.List; 4 | 5 | import com.stacksimplify.restservices.entities.Order; 6 | 7 | public class UserMmDto { 8 | 9 | private Long userid; 10 | private String username; 11 | private String firstname; 12 | private List orders; 13 | 14 | 15 | public Long getUserid() { 16 | return userid; 17 | } 18 | public void setUserid(Long userid) { 19 | this.userid = userid; 20 | } 21 | public String getUsername() { 22 | return username; 23 | } 24 | public void setUsername(String username) { 25 | this.username = username; 26 | } 27 | public String getFirstname() { 28 | return firstname; 29 | } 30 | public void setFirstname(String firstname) { 31 | this.firstname = firstname; 32 | } 33 | public List getOrders() { 34 | return orders; 35 | } 36 | public void setOrders(List orders) { 37 | this.orders = orders; 38 | } 39 | 40 | 41 | 42 | 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/dtos/UserMsDto.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.dtos; 2 | 3 | public class UserMsDto { 4 | 5 | private Long userid; 6 | private String username; 7 | private String emailaddress; 8 | private String rolename; 9 | 10 | 11 | 12 | 13 | public UserMsDto() { 14 | 15 | } 16 | 17 | 18 | public UserMsDto(Long userid, String username, String emailaddress, String rolename) { 19 | super(); 20 | this.userid = userid; 21 | this.username = username; 22 | this.emailaddress = emailaddress; 23 | this.rolename = rolename; 24 | } 25 | 26 | 27 | public Long getUserid() { 28 | return userid; 29 | } 30 | public void setUserid(Long userid) { 31 | this.userid = userid; 32 | } 33 | public String getUsername() { 34 | return username; 35 | } 36 | public void setUsername(String username) { 37 | this.username = username; 38 | } 39 | public String getEmailaddress() { 40 | return emailaddress; 41 | } 42 | public void setEmailaddress(String emailaddress) { 43 | this.emailaddress = emailaddress; 44 | } 45 | 46 | 47 | public String getRolename() { 48 | return rolename; 49 | } 50 | 51 | 52 | public void setRolename(String rolename) { 53 | this.rolename = rolename; 54 | } 55 | 56 | 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/entities/Order.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.entities; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.FetchType; 5 | import javax.persistence.GeneratedValue; 6 | import javax.persistence.Id; 7 | import javax.persistence.ManyToOne; 8 | import javax.persistence.Table; 9 | 10 | import org.springframework.hateoas.ResourceSupport; 11 | 12 | import com.fasterxml.jackson.annotation.JsonIgnore; 13 | import com.fasterxml.jackson.annotation.JsonView; 14 | 15 | @Entity 16 | @Table(name = "orders") 17 | public class Order extends ResourceSupport { 18 | 19 | @Id 20 | @GeneratedValue 21 | @JsonView(Views.Internal.class) 22 | private Long orderid; 23 | @JsonView(Views.Internal.class) 24 | private String orderdescription; 25 | 26 | @ManyToOne(fetch = FetchType.LAZY) 27 | @JsonIgnore 28 | private User user; 29 | 30 | public Order() { 31 | super(); 32 | // TODO Auto-generated constructor stub 33 | } 34 | 35 | public Long getOrderid() { 36 | return orderid; 37 | } 38 | 39 | public void setOrderid(Long orderid) { 40 | this.orderid = orderid; 41 | } 42 | 43 | public String getOrderdescription() { 44 | return orderdescription; 45 | } 46 | 47 | public void setOrderdescription(String orderdescription) { 48 | this.orderdescription = orderdescription; 49 | } 50 | 51 | public User getUser() { 52 | return user; 53 | } 54 | 55 | public void setUser(User user) { 56 | this.user = user; 57 | } 58 | 59 | 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/entities/User.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.entities; 2 | 3 | import java.util.List; 4 | 5 | import javax.persistence.Column; 6 | import javax.persistence.Entity; 7 | import javax.persistence.GeneratedValue; 8 | import javax.persistence.Id; 9 | import javax.persistence.OneToMany; 10 | import javax.persistence.Table; 11 | import javax.validation.constraints.NotEmpty; 12 | import javax.validation.constraints.Size; 13 | 14 | import org.springframework.hateoas.ResourceSupport; 15 | 16 | import com.fasterxml.jackson.annotation.JsonView; 17 | 18 | import io.swagger.annotations.ApiModel; 19 | import io.swagger.annotations.ApiModelProperty; 20 | 21 | //Entity 22 | // and 23 | @ApiModel(description = "This model is to create a user") 24 | @Entity 25 | @Table(name = "user") 26 | //@JsonIgnoreProperties({"firstname", "lastname"}) -- Static Filtering @JsonIgnore 27 | //@JsonFilter(value = "userFilter") -- Used for MappingJacksonValue filtering section 28 | public class User extends ResourceSupport { 29 | 30 | @ApiModelProperty(notes = " Auto generated unique id", required = true, position = 1) 31 | @Id 32 | @GeneratedValue 33 | @JsonView(Views.External.class) 34 | private Long userid; 35 | 36 | @ApiModelProperty(notes = "username should be in format flname", example = "kreddy", required = false, position = 2) 37 | @Size(min = 2, max = 50) 38 | @NotEmpty(message = "Username is Mandatory field. Please provide username") 39 | @Column(name = "USER_NAME", length = 50, nullable = false, unique = true) 40 | @JsonView(Views.External.class) 41 | private String username; 42 | 43 | @Size(min = 2, max = 50, message = "FirstName should have atleast 2 characters") 44 | @Column(name = "FIRST_NAME", length = 50, nullable = false) 45 | @JsonView(Views.External.class) 46 | private String firstname; 47 | 48 | @Column(name = "LAST_NAME", length = 50, nullable = false) 49 | @JsonView(Views.External.class) 50 | private String lastname; 51 | 52 | @Column(name = "EMAIL_ADDRESS", length = 50, nullable = false) 53 | @JsonView(Views.External.class) 54 | private String email; 55 | 56 | @Column(name = "ROLE", length = 50, nullable = false) 57 | @JsonView(Views.Internal.class) 58 | private String role; 59 | 60 | @Column(name = "SSN", length = 50, nullable = false, unique = true) 61 | //@JsonIgnore -- Static Filtering @JsonIgnore 62 | @JsonView(Views.Internal.class) 63 | private String ssn; 64 | 65 | @OneToMany(mappedBy = "user") 66 | @JsonView(Views.Internal.class) 67 | private List orders; 68 | 69 | @Column(name = "ADDRESS") 70 | private String address; 71 | 72 | // No Argument Constructor 73 | public User() { 74 | } 75 | 76 | // Fields Constructor 77 | public User(Long userid, 78 | @NotEmpty(message = "Username is Mandatory field. Please provide username") String username, 79 | @Size(min = 2, message = "FirstName should have atleast 2 characters") String firstname, String lastname, 80 | String email, String role, String ssn, List orders, String address) { 81 | super(); 82 | this.userid = userid; 83 | this.username = username; 84 | this.firstname = firstname; 85 | this.lastname = lastname; 86 | this.email = email; 87 | this.role = role; 88 | this.ssn = ssn; 89 | this.orders = orders; 90 | this.address = address; 91 | } 92 | 93 | 94 | // Getters and Setters 95 | 96 | public Long getUserid() { 97 | return userid; 98 | } 99 | 100 | 101 | 102 | public void setUserid(Long userid) { 103 | this.userid = userid; 104 | } 105 | 106 | public String getUsername() { 107 | return username; 108 | } 109 | 110 | public void setUsername(String username) { 111 | this.username = username; 112 | } 113 | 114 | public String getFirstname() { 115 | return firstname; 116 | } 117 | 118 | public void setFirstname(String firstname) { 119 | this.firstname = firstname; 120 | } 121 | 122 | public String getLastname() { 123 | return lastname; 124 | } 125 | 126 | public void setLastname(String lastname) { 127 | this.lastname = lastname; 128 | } 129 | 130 | public String getEmail() { 131 | return email; 132 | } 133 | 134 | public void setEmail(String email) { 135 | this.email = email; 136 | } 137 | 138 | public String getRole() { 139 | return role; 140 | } 141 | 142 | public void setRole(String role) { 143 | this.role = role; 144 | } 145 | 146 | public String getSsn() { 147 | return ssn; 148 | } 149 | 150 | public void setSsn(String ssn) { 151 | this.ssn = ssn; 152 | } 153 | 154 | public List getOrders() { 155 | return orders; 156 | } 157 | 158 | public void setOrders(List orders) { 159 | this.orders = orders; 160 | } 161 | 162 | 163 | 164 | 165 | 166 | public String getAddress() { 167 | return address; 168 | } 169 | 170 | public void setAddress(String address) { 171 | this.address = address; 172 | } 173 | 174 | // To String 175 | @Override 176 | public String toString() { 177 | return "User [userid=" + userid + ", username=" + username + ", firstname=" + firstname + ", lastname=" 178 | + lastname + ", email=" + email + ", role=" + role + ", ssn=" + ssn + ", orders=" + orders 179 | + ", address=" + address + "]"; 180 | } 181 | 182 | 183 | 184 | 185 | 186 | } 187 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/entities/Views.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.entities; 2 | 3 | public class Views { 4 | 5 | //external class 6 | public static class External { 7 | 8 | } 9 | 10 | 11 | 12 | //internal class 13 | public static class Internal extends External { 14 | 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/exceptions/CustomErrorDetails.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.exceptions; 2 | 3 | import java.util.Date; 4 | 5 | //Simple custom error details bean 6 | public class CustomErrorDetails { 7 | 8 | private Date timestamp; 9 | private String message; 10 | private String errordetails; 11 | 12 | //Fields Constructor 13 | public CustomErrorDetails(Date timestamp, String message, String errordetails) { 14 | super(); 15 | this.timestamp = timestamp; 16 | this.message = message; 17 | this.errordetails = errordetails; 18 | } 19 | 20 | //GETTERS 21 | public Date getTimestamp() { 22 | return timestamp; 23 | } 24 | public String getMessage() { 25 | return message; 26 | } 27 | public String getErrordetails() { 28 | return errordetails; 29 | } 30 | 31 | 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/exceptions/CustomGlobalExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.exceptions; 2 | 3 | import java.util.Date; 4 | 5 | import javax.validation.ConstraintViolationException; 6 | 7 | import org.springframework.http.HttpHeaders; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.http.ResponseEntity; 10 | import org.springframework.web.HttpRequestMethodNotSupportedException; 11 | import org.springframework.web.bind.MethodArgumentNotValidException; 12 | import org.springframework.web.bind.annotation.ControllerAdvice; 13 | import org.springframework.web.bind.annotation.ExceptionHandler; 14 | import org.springframework.web.context.request.WebRequest; 15 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; 16 | 17 | @ControllerAdvice 18 | public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler { 19 | 20 | // MethodArgumentNotValidException 21 | @Override 22 | protected ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex, 23 | HttpHeaders headers, HttpStatus status, WebRequest request) { 24 | 25 | CustomErrorDetails customErrorDetails = new CustomErrorDetails(new Date(), 26 | "From MethodArgumentNotValid Exception in GEH", ex.getMessage()); 27 | 28 | return new ResponseEntity<>(customErrorDetails, HttpStatus.BAD_REQUEST); 29 | } 30 | 31 | // HttpRequestMethodNotSupportedException 32 | @Override 33 | protected ResponseEntity handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex, 34 | HttpHeaders headers, HttpStatus status, WebRequest request) { 35 | 36 | CustomErrorDetails customErrorDetails = new CustomErrorDetails(new Date(), 37 | "From HttpRequestMethodNotSupportedException in GEH - Method Not allowed", ex.getMessage()); 38 | 39 | return new ResponseEntity<>(customErrorDetails, HttpStatus.METHOD_NOT_ALLOWED); 40 | 41 | } 42 | 43 | // UserNameNotFoundException 44 | @ExceptionHandler(UserNameNotFoundException.class) 45 | public final ResponseEntity handleUserNameNotFoundException(UserNameNotFoundException ex, 46 | WebRequest request) { 47 | CustomErrorDetails customErrorDetails = new CustomErrorDetails(new Date(), ex.getMessage(), 48 | request.getDescription(false)); 49 | 50 | return new ResponseEntity<>(customErrorDetails, HttpStatus.NOT_FOUND); 51 | 52 | } 53 | 54 | // ConstraintViolationException 55 | @ExceptionHandler(ConstraintViolationException.class) 56 | public final ResponseEntity handleConstraintViolationException(ConstraintViolationException ex, 57 | WebRequest request) { 58 | CustomErrorDetails customErrorDetails = new CustomErrorDetails(new Date(), ex.getMessage(), 59 | request.getDescription(false)); 60 | 61 | return new ResponseEntity<>(customErrorDetails, HttpStatus.BAD_REQUEST); 62 | 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/exceptions/GlobalRestControllerAdviceExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.exceptions; 2 | 3 | import java.util.Date; 4 | 5 | import org.springframework.http.HttpStatus; 6 | import org.springframework.web.bind.annotation.ExceptionHandler; 7 | import org.springframework.web.bind.annotation.ResponseStatus; 8 | import org.springframework.web.bind.annotation.RestControllerAdvice; 9 | 10 | //@RestControllerAdvice 11 | public class GlobalRestControllerAdviceExceptionHandler { 12 | 13 | @ExceptionHandler(UserNameNotFoundException.class) 14 | @ResponseStatus(HttpStatus.NOT_FOUND) 15 | public CustomErrorDetails usernameNotFound(UserNameNotFoundException ex) { 16 | 17 | return new CustomErrorDetails(new Date(), "From @RestControllerAdvice NOT FOUND", 18 | ex.getMessage()); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/exceptions/UserExistsException.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.exceptions; 2 | 3 | public class UserExistsException extends Exception { 4 | 5 | /** 6 | * 7 | */ 8 | private static final long serialVersionUID = 1904585489531578456L; 9 | 10 | public UserExistsException(String message) { 11 | super(message); 12 | // TODO Auto-generated constructor stub 13 | } 14 | 15 | 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/exceptions/UserNameNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.exceptions; 2 | 3 | public class UserNameNotFoundException extends Exception { 4 | 5 | /** 6 | * 7 | */ 8 | private static final long serialVersionUID = 1L; 9 | 10 | //Superclass Constructor 11 | public UserNameNotFoundException(String message) { 12 | super(message); 13 | // TODO Auto-generated constructor stub 14 | } 15 | 16 | 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/exceptions/UserNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.exceptions; 2 | 3 | public class UserNotFoundException extends Exception { 4 | 5 | 6 | private static final long serialVersionUID = 1L; 7 | 8 | public UserNotFoundException(String message) { 9 | super(message); 10 | } 11 | 12 | 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/mappers/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.mappers; 2 | 3 | import java.util.List; 4 | 5 | import org.mapstruct.Mapper; 6 | import org.mapstruct.Mapping; 7 | import org.mapstruct.Mappings; 8 | import org.mapstruct.factory.Mappers; 9 | 10 | import com.stacksimplify.restservices.dtos.UserMsDto; 11 | import com.stacksimplify.restservices.entities.User; 12 | 13 | @Mapper(componentModel = "Spring") 14 | public interface UserMapper { 15 | 16 | UserMapper INSTANCE = Mappers.getMapper(UserMapper.class); 17 | 18 | //User To UserMsDto 19 | @Mappings({ 20 | @Mapping(source= "email", target="emailaddress"), 21 | @Mapping(source = "role", target="rolename") 22 | }) 23 | UserMsDto userToUserMsDto(User user); 24 | 25 | //List to List 26 | List usersToUserDtos(List users); 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/repositories/OrderRepository.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.repositories; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | 6 | import com.stacksimplify.restservices.entities.Order; 7 | 8 | @Repository 9 | public interface OrderRepository extends JpaRepository{ 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/repositories/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.repositories; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | 6 | import com.stacksimplify.restservices.entities.User; 7 | 8 | //Repository 9 | @Repository 10 | public interface UserRepository extends JpaRepository{ 11 | 12 | User findByUsername(String username); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/stacksimplify/restservices/services/UserService.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices.services; 2 | 3 | import java.util.List; 4 | import java.util.Optional; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.stereotype.Service; 9 | import org.springframework.web.server.ResponseStatusException; 10 | 11 | import com.stacksimplify.restservices.entities.User; 12 | import com.stacksimplify.restservices.exceptions.UserExistsException; 13 | import com.stacksimplify.restservices.exceptions.UserNotFoundException; 14 | import com.stacksimplify.restservices.repositories.UserRepository; 15 | 16 | //Service 17 | @Service 18 | public class UserService { 19 | 20 | // Autowire the UserRepository 21 | @Autowired 22 | private UserRepository userRepository; 23 | 24 | // getAllUsers Method 25 | public List getAllUsers() { 26 | 27 | return userRepository.findAll(); 28 | 29 | } 30 | 31 | // CreateUser Method 32 | public User createUser(User user) throws UserExistsException{ 33 | //if user exist using username 34 | User existingUser = userRepository.findByUsername(user.getUsername()); 35 | 36 | //if not exists throw UserExistsException 37 | if(existingUser != null) { 38 | throw new UserExistsException("User already exists in repository"); 39 | } 40 | 41 | 42 | return userRepository.save(user); 43 | } 44 | 45 | // getUserById 46 | public Optional getUserById(Long id) throws UserNotFoundException { 47 | Optional user = userRepository.findById(id); 48 | 49 | if (!user.isPresent()) { 50 | throw new UserNotFoundException("User Not found in user Repository"); 51 | } 52 | 53 | return user; 54 | } 55 | 56 | // updateUserById 57 | public User updateUserById(Long id, User user) throws UserNotFoundException { 58 | Optional optionalUser = userRepository.findById(id); 59 | 60 | if (!optionalUser.isPresent()) { 61 | throw new UserNotFoundException("User Not found in user Repository, provide the correct user id"); 62 | } 63 | 64 | 65 | user.setUserid(id);; 66 | return userRepository.save(user); 67 | 68 | } 69 | 70 | // deleteUserById 71 | public void deleteUserById(Long id) { 72 | Optional optionalUser = userRepository.findById(id); 73 | if (!optionalUser.isPresent()) { 74 | throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"User Not found in user Repository, provide the correct user id"); 75 | } 76 | 77 | userRepository.deleteById(id); 78 | } 79 | 80 | // getUserByUsername 81 | 82 | public User getUserByUsername(String username) { 83 | return userRepository.findByUsername(username); 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.jpa.show-sql=true 2 | spring.h2.console.enabled=true 3 | server.error.include-stacktrace=never 4 | management.endpoints.web.exposure.include=* 5 | management.endpoint.health.show-details=always 6 | info.greet=Good Morning 7 | info.hello=Hello World 8 | #Point to Admin Server 9 | spring.boot.admin.client.url=http://localhost:9080 10 | #using the metadata 11 | spring.boot.admin.client.instance.metadata.tags.environment=dev 12 | #JMX Export Metrics 13 | management.metrics.export.jmx.enabled: true 14 | #AppOptics Token 15 | management.metrics.export.appoptics.api-token=1477e14d2e9b27904decc48e97c077665ca393844d03f3a0fea6b68f37e7a3d8 -------------------------------------------------------------------------------- /src/main/resources/data.sql: -------------------------------------------------------------------------------- 1 | insert into user values(101, 'New York','kreddy@stacksimplify.com', 'Kalyan', 'Reddy', 'admin', 'ssn101', 'kreddy'); 2 | insert into user values(102, 'New Jersey','gwiser@stacksimplify.com', 'Greg', 'Wiser', 'admin', 'ssn102', 'gwiser'); 3 | insert into user values(103, 'California', 'dmark@stacksimplify.com', 'David', 'Mark', 'admin', 'ssn103', 'dmark'); 4 | insert into orders values( 2001, 'order11', 101); 5 | insert into orders values( 2002, 'order12', 101); 6 | insert into orders values( 2003, 'order13', 101); 7 | insert into orders values( 2004, 'order21', 102); 8 | insert into orders values( 2005, 'order22', 102); 9 | insert into orders values( 2006, 'order31', 103); -------------------------------------------------------------------------------- /src/main/resources/messages.properties: -------------------------------------------------------------------------------- 1 | label.hello=Hello World -------------------------------------------------------------------------------- /src/main/resources/messages_fr.properties: -------------------------------------------------------------------------------- 1 | label.hello=Bonjour le monde -------------------------------------------------------------------------------- /src/test/java/com/stacksimplify/restservices/SpringbootBuildingblocksApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.stacksimplify.restservices; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class SpringbootBuildingblocksApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | --------------------------------------------------------------------------------