├── AccountMicroservice ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── quicktutorials │ │ │ └── learnmicroservices │ │ │ └── AccountMicroservice │ │ │ ├── AccountMicroserviceApplication.java │ │ │ ├── controllers │ │ │ └── RestController.java │ │ │ ├── daos │ │ │ ├── AccountDao.java │ │ │ ├── OperationDao.java │ │ │ └── UserDao.java │ │ │ ├── entities │ │ │ ├── Account.java │ │ │ ├── Operation.java │ │ │ └── User.java │ │ │ ├── services │ │ │ ├── LoginService.java │ │ │ ├── LoginServiceImpl.java │ │ │ ├── OperationService.java │ │ │ └── OperationServiceImpl.java │ │ │ └── utils │ │ │ ├── EncryptionUtils.java │ │ │ ├── JwtUtils.java │ │ │ └── UserNotLoggedException.java │ └── resources │ │ ├── application.properties │ │ └── static │ │ ├── js │ │ └── actions.js │ │ └── signin.html │ └── test │ └── java │ └── com │ └── quicktutorials │ └── learnmicroservices │ └── AccountMicroservice │ └── AccountMicroserviceApplicationTests.java ├── CouponMicroservice ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── quicktutorialz │ │ │ └── learnmicroservices │ │ │ └── CouponMicroservice │ │ │ ├── CouponMicroserviceApplication.java │ │ │ ├── controllers │ │ │ └── RestController.java │ │ │ ├── daos │ │ │ └── CouponDao.java │ │ │ ├── entities │ │ │ ├── Coupon.java │ │ │ └── JsonResponseBody.java │ │ │ └── services │ │ │ ├── CouponService.java │ │ │ └── CouponServiceImpl.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── quicktutorialz │ └── learnmicroservices │ └── CouponMicroservice │ └── CouponMicroserviceApplicationTests.java ├── README - Database MySQL ├── README.md └── coupondb.sql /AccountMicroservice/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /AccountMicroservice/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alessandroargentieri/Sviluppo-web-a-microservizi-REST-con-Java-Spring-boot-e-AJAX/478893c571d150ab9e8b68310d66e84673f3f6f0/AccountMicroservice/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /AccountMicroservice/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip 2 | -------------------------------------------------------------------------------- /AccountMicroservice/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 | # http://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 Migwn, 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 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /AccountMicroservice/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 http://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 enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /AccountMicroservice/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.quicktutorials.learnmicroservices 7 | AccountMicroservice 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | AccountMicroservice 12 | First Microservice in SpringBoot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.7.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-data-jpa 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-web 35 | 36 | 37 | 38 | com.h2database 39 | h2 40 | runtime 41 | 42 | 43 | org.projectlombok 44 | lombok 45 | true 46 | 1.16.10 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-starter-test 51 | test 52 | 53 | 54 | org.jasypt 55 | jasypt 56 | 1.9.2 57 | 58 | 59 | io.jsonwebtoken 60 | jjwt 61 | 0.7.0 62 | 63 | 64 | 65 | 66 | 67 | 68 | org.springframework.boot 69 | spring-boot-maven-plugin 70 | 71 | 72 | 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /AccountMicroservice/src/main/java/com/quicktutorials/learnmicroservices/AccountMicroservice/AccountMicroserviceApplication.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorials.learnmicroservices.AccountMicroservice; 2 | 3 | import com.quicktutorials.learnmicroservices.AccountMicroservice.daos.AccountDao; 4 | import com.quicktutorials.learnmicroservices.AccountMicroservice.daos.OperationDao; 5 | import com.quicktutorials.learnmicroservices.AccountMicroservice.daos.UserDao; 6 | import com.quicktutorials.learnmicroservices.AccountMicroservice.entities.Account; 7 | import com.quicktutorials.learnmicroservices.AccountMicroservice.entities.Operation; 8 | import com.quicktutorials.learnmicroservices.AccountMicroservice.entities.User; 9 | import com.quicktutorials.learnmicroservices.AccountMicroservice.utils.EncryptionUtils; 10 | import org.jasypt.util.text.BasicTextEncryptor; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.boot.CommandLineRunner; 15 | import org.springframework.boot.SpringApplication; 16 | import org.springframework.boot.autoconfigure.SpringBootApplication; 17 | import org.springframework.context.annotation.Bean; 18 | 19 | import java.util.Date; 20 | 21 | @SpringBootApplication 22 | public class AccountMicroserviceApplication implements CommandLineRunner{ 23 | 24 | @Autowired 25 | UserDao userDao; 26 | 27 | @Autowired 28 | AccountDao accountDao; 29 | 30 | @Autowired 31 | OperationDao operationDao; 32 | 33 | @Autowired 34 | EncryptionUtils encryptionUtils; 35 | 36 | 37 | 38 | 39 | private static final Logger log = LoggerFactory.getLogger(AccountMicroserviceApplication.class); 40 | 41 | 42 | public static void main(String[] args){ 43 | SpringApplication.run(AccountMicroserviceApplication.class, args); 44 | } 45 | 46 | @Override 47 | public void run(String... strings) throws Exception { 48 | //... 49 | log.info("Hello 1"); 50 | 51 | String encryptedPwd = encryptionUtils.encrypt("Abba"); 52 | System.out.println("Ecripted pwd into DB: " + encryptedPwd); 53 | log.info("Ecripted pwd into DB: " + encryptedPwd); 54 | userDao.save(new User("RGNLSN87H13D761R", "Alessandro Argentieri", encryptedPwd, "user")); 55 | 56 | encryptedPwd = encryptionUtils.encrypt("WeLoveTokyo"); 57 | userDao.save(new User("FRNFBA85M08D761M", "Fabio Fiorenza", encryptedPwd, "user")); 58 | 59 | encryptedPwd = encryptionUtils.encrypt("Melograno"); 60 | userDao.save(new User("DSTLCU89R52D761R", "Lucia Distante", encryptedPwd, "user")); 61 | 62 | accountDao.save(new Account("cn4563df3", "RGNLSN87H13D761R", 3000.00)); 63 | accountDao.save(new Account("cn7256su9", "RGNLSN87H13D761R", 4000.00)); 64 | accountDao.save(new Account("cn6396dr7", "FRNFBA85M08D761M", 7000.00)); 65 | accountDao.save(new Account("cn2759ds4", "DSTLCU89R52D761R", 2000.00)); 66 | accountDao.save(new Account("cn2874da2", "DSTLCU89R52D761R", 8000.00)); 67 | 68 | operationDao.save(new Operation("3452",new Date(),"Bonifico bancario", 100.00, "cn4563df3","cn4563df3")); 69 | operationDao.save(new Operation("3453",new Date(),"Pagamento tasse", -100.00, "cn4563df3","cn4563df3")); 70 | operationDao.save(new Operation("3454",new Date(),"Postagiro", 230.00, "cn4563df3","cn2759ds4")); 71 | operationDao.save(new Operation("3455",new Date(),"Vaglia postale", 172.00, "cn4563df3","cn4563df3")); 72 | operationDao.save(new Operation("3456",new Date(),"Acquisto azioni", -3400.00, "cn2759ds4","")); 73 | operationDao.save(new Operation("3457",new Date(),"Vendita azione", 100.00, "cn4563df3","")); 74 | operationDao.save(new Operation("3458",new Date(),"Prelevamento", -100.00, "cn4563df3","")); 75 | operationDao.save(new Operation("3459",new Date(),"Deposito", 1100.00, "cn4563df3","")); 76 | operationDao.save(new Operation("3460",new Date(),"Bonifico bancario", 100.00, "cn2874da2","cn4563df3")); 77 | operationDao.save(new Operation("3461",new Date(),"Bonifico bancario", 100.00, "cn4563df3","cn2874da2")); 78 | operationDao.save(new Operation("3462",new Date(),"Bonifico bancario", 100.00, "cn4563df3","cn4563df3")); 79 | operationDao.save(new Operation("3463",new Date(),"Postagiro", 230.00, "cn7256su9","cn2759ds4")); 80 | operationDao.save(new Operation("3464",new Date(),"Vaglia postale", 172.00, "cn4563df3","cn7256su9")); 81 | operationDao.save(new Operation("3465",new Date(),"Acquisto azioni", -3400.00, "cn7256su9","")); 82 | 83 | } 84 | 85 | @Bean 86 | public BasicTextEncryptor textEncryptor(){ 87 | BasicTextEncryptor textEncryptor = new BasicTextEncryptor(); 88 | textEncryptor.setPassword("mySecretEncriptionKeyBlaBla1234"); 89 | return textEncryptor; 90 | } 91 | 92 | 93 | 94 | } 95 | -------------------------------------------------------------------------------- /AccountMicroservice/src/main/java/com/quicktutorials/learnmicroservices/AccountMicroservice/controllers/RestController.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorials.learnmicroservices.AccountMicroservice.controllers; 2 | 3 | 4 | import com.quicktutorials.learnmicroservices.AccountMicroservice.entities.Operation; 5 | import com.quicktutorials.learnmicroservices.AccountMicroservice.entities.User; 6 | import com.quicktutorials.learnmicroservices.AccountMicroservice.services.LoginService; 7 | import com.quicktutorials.learnmicroservices.AccountMicroservice.services.LoginServiceImpl; 8 | import com.quicktutorials.learnmicroservices.AccountMicroservice.services.OperationService; 9 | import com.quicktutorials.learnmicroservices.AccountMicroservice.utils.UserNotLoggedException; 10 | import io.jsonwebtoken.ExpiredJwtException; 11 | import lombok.AllArgsConstructor; 12 | import lombok.Getter; 13 | import lombok.Setter; 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | import org.springframework.beans.factory.annotation.Autowired; 17 | import org.springframework.http.HttpStatus; 18 | import org.springframework.http.ResponseEntity; 19 | import org.springframework.validation.BindingResult; 20 | import org.springframework.validation.Errors; 21 | import org.springframework.validation.Validator; 22 | import org.springframework.web.bind.annotation.CrossOrigin; 23 | import org.springframework.web.bind.annotation.PathVariable; 24 | import org.springframework.web.bind.annotation.RequestMapping; 25 | import org.springframework.web.bind.annotation.RequestParam; 26 | 27 | 28 | import javax.servlet.http.HttpServletRequest; 29 | import javax.validation.Valid; 30 | 31 | import java.io.UnsupportedEncodingException; 32 | import java.util.Date; 33 | import java.util.Map; 34 | import java.util.Optional; 35 | 36 | import static org.springframework.web.bind.annotation.RequestMethod.POST; 37 | 38 | @org.springframework.web.bind.annotation.RestController 39 | public class RestController { 40 | 41 | 42 | private static final Logger log = LoggerFactory.getLogger(RestController.class); 43 | 44 | @Autowired 45 | LoginService loginService; 46 | 47 | @Autowired 48 | OperationService operationService; 49 | 50 | 51 | 52 | @RequestMapping("/hello") 53 | public String sayHello(){ 54 | return "Hello everyone!"; 55 | } 56 | 57 | /* testare con PostMan con modalità x-www-form-urlencoded */ 58 | 59 | //if pwd is null it will still return a user 60 | @RequestMapping("/newuser1") 61 | public String addUser(User user){ 62 | return "User added correctly:" + user.getId() + ", "+ user.getUsername(); 63 | } 64 | 65 | //if pwd is null it will return a JAVA JSR-303 error message thanks to @Valid 66 | @RequestMapping("/newuser2") 67 | public String addUserValid(@Valid User user){ 68 | return "User added correctly:" + user.getId() + ", "+ user.getUsername(); 69 | } 70 | 71 | //if pwd is null it will return a JAVA JSR-303 error message thanks to Spring object BindingResult 72 | @RequestMapping("/newuser3") 73 | public String addUserValidPlusBinding(@Valid User user, BindingResult result){ 74 | if(result.hasErrors()){ 75 | return result.toString(); 76 | } 77 | return "User added correctly:" + user.getId() + ", "+ user.getUsername(); 78 | } 79 | 80 | //if pwd is null it will return a SPRING VALIDATOR error message thanks to Spring object BindingResult 81 | @RequestMapping("/newuser4") 82 | public String addUserValidPlusBinding2(User user, BindingResult result){ 83 | /* Spring validation */ 84 | UserValidator userValidator = new UserValidator(); 85 | userValidator.validate(user, result); 86 | 87 | if(result.hasErrors()){ 88 | return result.toString(); 89 | } 90 | return "User added correctly:" + user.getId() + ", "+ user.getUsername(); 91 | } 92 | 93 | 94 | 95 | /*---------------------------INNER CLASS------------------------*/ 96 | //Spring Validator Example 97 | private class UserValidator implements Validator { 98 | 99 | @Override 100 | public boolean supports(Class clazz) { 101 | return User.class.equals(clazz); 102 | } 103 | 104 | @Override 105 | public void validate(Object obj, Errors errors) { 106 | User user = (User) obj; 107 | if (user.getPassword().length() < 8) { 108 | errors.rejectValue("password", "the password must be at least 8 chars long!"); 109 | } 110 | } 111 | } 112 | /*---------------------------------------------------------*/ 113 | 114 | /** 115 | * inner class used as the Object tied into the Body of the ResponseEntity. 116 | * It's important to have this Object because it is composed of server response code and response object. 117 | * Then, JACKSON LIBRARY automatically convert this JsonResponseBody Object into a JSON response. 118 | */ 119 | @AllArgsConstructor 120 | public class JsonResponseBody{ 121 | @Getter @Setter 122 | private int server; 123 | @Getter @Setter 124 | private Object response; 125 | } 126 | 127 | /*---------------------------------------------------------*/ 128 | 129 | 130 | @CrossOrigin 131 | @RequestMapping(value = "/login", method = POST) 132 | public ResponseEntity loginUser(@RequestParam(value ="id") String id, @RequestParam(value="password") String pwd){ 133 | //check if user exists in DB -> if exists generate JWT and send back to client 134 | try { 135 | Optional userr = loginService.getUserFromDbAndVerifyPassword(id, pwd); 136 | if(userr.isPresent()){ 137 | User user = userr.get(); 138 | String jwt = loginService.createJwt(user.getId(), user.getUsername(), user.getPermission(), new Date()); 139 | return ResponseEntity.status(HttpStatus.OK).header("jwt", jwt).body(new JsonResponseBody(HttpStatus.OK.value(), "Success! User logged in!")); 140 | } 141 | }catch (UserNotLoggedException e1){ 142 | return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new JsonResponseBody(HttpStatus.FORBIDDEN.value(), "Login failed! Wrong credentials" + e1.toString())); 143 | }catch (UnsupportedEncodingException e2){ 144 | return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new JsonResponseBody(HttpStatus.FORBIDDEN.value(), "Token Error" + e2.toString())); 145 | } 146 | return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new JsonResponseBody(HttpStatus.FORBIDDEN.value(), "No corrispondence in the database of users")); 147 | } 148 | 149 | 150 | @RequestMapping("/operations/account/{account}") 151 | public ResponseEntity fetchAllOperationsPerAccount(HttpServletRequest request, @PathVariable(name = "account") String account){ 152 | //request -> fetch JWT -> check validity -> Get operations from the user account 153 | try { 154 | loginService.verifyJwtAndGetData(request); 155 | //user verified 156 | return ResponseEntity.status(HttpStatus.OK).body(new JsonResponseBody(HttpStatus.OK.value(), operationService.getAllOperationPerAccount(account))); 157 | }catch(UnsupportedEncodingException e1){ 158 | return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new JsonResponseBody(HttpStatus.FORBIDDEN.value(), "Unsupported Encoding: " + e1.toString())); 159 | }catch (UserNotLoggedException e2) { 160 | return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new JsonResponseBody(HttpStatus.FORBIDDEN.value(), "User not correctly logged: " + e2.toString())); 161 | }catch(ExpiredJwtException e3){ 162 | return ResponseEntity.status(HttpStatus.GATEWAY_TIMEOUT).body(new JsonResponseBody(HttpStatus.GATEWAY_TIMEOUT.value(), "Session Expired!: " + e3.toString())); 163 | } 164 | } 165 | 166 | @RequestMapping(value = "/accounts/user", method = POST) 167 | public ResponseEntity fetchAllAccountsPerUser(HttpServletRequest request){ 168 | //request -> fetch JWT -> recover User Data -> Get user accounts from DB 169 | try { 170 | Map userData = loginService.verifyJwtAndGetData(request); 171 | return ResponseEntity.status(HttpStatus.OK).body(new JsonResponseBody(HttpStatus.OK.value(), operationService.getAllAccountsPerUser((String) userData.get("subject")))); 172 | }catch(UnsupportedEncodingException e1){ 173 | return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new JsonResponseBody(HttpStatus.BAD_REQUEST.value(), "Bad Request: " + e1.toString())); 174 | }catch(UserNotLoggedException e2){ 175 | return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new JsonResponseBody(HttpStatus.FORBIDDEN.value(), "User not logged! Login first : " + e2.toString())); 176 | }catch(ExpiredJwtException e3){ 177 | return ResponseEntity.status(HttpStatus.GATEWAY_TIMEOUT).body(new JsonResponseBody(HttpStatus.GATEWAY_TIMEOUT.value(), "Session Expired!: " + e3.toString())); 178 | } 179 | } 180 | 181 | 182 | 183 | @RequestMapping(value = "/operations/add", method=POST) 184 | public ResponseEntity addOperation(HttpServletRequest request, @Valid Operation operation, BindingResult bindingResult){ 185 | //request -> fetch JWT -> recover User Data -> Save valid operation in DB 186 | if(bindingResult.hasErrors()){ 187 | return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new JsonResponseBody(HttpStatus.FORBIDDEN.value(), "Error! Invalid format of data.")); 188 | } 189 | try { 190 | loginService.verifyJwtAndGetData(request); 191 | return ResponseEntity.status(HttpStatus.OK).body(new JsonResponseBody(HttpStatus.OK.value(), operationService.saveOperation(operation))); 192 | }catch(UserNotLoggedException e1){ 193 | return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new JsonResponseBody(HttpStatus.FORBIDDEN.value(), "User not logged! Login first : " + e1.toString())); 194 | }catch(UnsupportedEncodingException e2){ 195 | return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new JsonResponseBody(HttpStatus.BAD_REQUEST.value(), "Bad Request: " + e2.toString())); 196 | }catch(ExpiredJwtException e3){ 197 | return ResponseEntity.status(HttpStatus.GATEWAY_TIMEOUT).body(new JsonResponseBody(HttpStatus.GATEWAY_TIMEOUT.value(), "Session Expired!: " + e3.toString())); 198 | } 199 | } 200 | 201 | 202 | 203 | 204 | } -------------------------------------------------------------------------------- /AccountMicroservice/src/main/java/com/quicktutorials/learnmicroservices/AccountMicroservice/daos/AccountDao.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorials.learnmicroservices.AccountMicroservice.daos; 2 | 3 | import com.quicktutorials.learnmicroservices.AccountMicroservice.entities.Account; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.Query; 6 | import org.springframework.data.repository.query.Param; 7 | 8 | import java.util.List; 9 | 10 | public interface AccountDao extends JpaRepository{ 11 | 12 | @Query(value = "SELECT * FROM accounts WHERE FK_USER=:user", nativeQuery = true) 13 | List getAllAccountsPerUser(@Param("user") String user); 14 | 15 | List findByFkUser(String fkUser); 16 | } 17 | -------------------------------------------------------------------------------- /AccountMicroservice/src/main/java/com/quicktutorials/learnmicroservices/AccountMicroservice/daos/OperationDao.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorials.learnmicroservices.AccountMicroservice.daos; 2 | 3 | import com.quicktutorials.learnmicroservices.AccountMicroservice.entities.Operation; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.Query; 6 | import org.springframework.data.repository.query.Param; 7 | 8 | import java.util.List; 9 | 10 | public interface OperationDao extends JpaRepository{ 11 | 12 | @Query(value = "SELECT * FROM operations WHERE FK_ACCOUNT1=:account OR FK_ACCOUNT2=:account", nativeQuery = true) 13 | List findAllOperationsByAccount(@Param("account")String account); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /AccountMicroservice/src/main/java/com/quicktutorials/learnmicroservices/AccountMicroservice/daos/UserDao.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorials.learnmicroservices.AccountMicroservice.daos; 2 | 3 | import com.quicktutorials.learnmicroservices.AccountMicroservice.entities.User; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | import java.util.Optional; 7 | 8 | public interface UserDao extends JpaRepository{ 9 | //custom 10 | Optional findById(String id); 11 | } 12 | -------------------------------------------------------------------------------- /AccountMicroservice/src/main/java/com/quicktutorials/learnmicroservices/AccountMicroservice/entities/Account.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorials.learnmicroservices.AccountMicroservice.entities; 2 | 3 | 4 | import lombok.AllArgsConstructor; 5 | import lombok.Getter; 6 | import lombok.NoArgsConstructor; 7 | import lombok.Setter; 8 | import org.hibernate.validator.constraints.NotBlank; 9 | import org.hibernate.validator.constraints.NotEmpty; 10 | 11 | import javax.persistence.Column; 12 | import javax.persistence.Entity; 13 | import javax.persistence.Id; 14 | import javax.persistence.Table; 15 | import javax.validation.constraints.NotNull; 16 | 17 | @Entity 18 | @Table(name="accounts") 19 | @AllArgsConstructor @NoArgsConstructor 20 | public class Account { 21 | 22 | //String ID, String FK_USER, Double TOTAL 23 | @Id 24 | @Column(name="ID") 25 | @NotNull @NotBlank @NotEmpty 26 | @Getter @Setter 27 | private String id; 28 | 29 | @Column(name="FK_USER") 30 | @Getter @Setter 31 | @NotEmpty @NotBlank @NotNull 32 | private String fkUser; 33 | 34 | @Column(name="TOTAL") 35 | @Getter @Setter 36 | private Double total; 37 | } 38 | -------------------------------------------------------------------------------- /AccountMicroservice/src/main/java/com/quicktutorials/learnmicroservices/AccountMicroservice/entities/Operation.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorials.learnmicroservices.AccountMicroservice.entities; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | import lombok.NoArgsConstructor; 6 | import lombok.Setter; 7 | import org.hibernate.validator.constraints.NotBlank; 8 | import org.hibernate.validator.constraints.NotEmpty; 9 | 10 | import javax.persistence.*; 11 | import javax.validation.constraints.NotNull; 12 | import java.util.Date; 13 | 14 | @Entity 15 | @Table(name="operations") 16 | @AllArgsConstructor @NoArgsConstructor 17 | public class Operation { 18 | 19 | //String ID, Date DATE, Double VALUE, String DESCRIPTION, String FK_ACCOUNT1, String FK_ACCOUNT2 20 | 21 | @Id 22 | @Column(name="ID") 23 | @Getter @Setter 24 | @NotBlank @NotNull @NotEmpty 25 | private String id; 26 | 27 | @Column(name="DATE") 28 | @Getter @Setter 29 | private Date date; 30 | 31 | @Column(name="DESCRIPTION") 32 | @Getter @Setter 33 | private String description; 34 | 35 | @Column(name="VALUE") 36 | @Getter @Setter 37 | @NotNull 38 | private Double value; 39 | 40 | @Column(name="FK_ACCOUNT1") 41 | @Getter @Setter 42 | @NotNull @NotBlank @NotEmpty 43 | private String fkAccount1; 44 | 45 | @Column(name="FK_ACCOUNT2") 46 | @Getter @Setter 47 | private String fkAccount2; 48 | 49 | @PrePersist 50 | void getTimeOperation() { 51 | this.date = new Date(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /AccountMicroservice/src/main/java/com/quicktutorials/learnmicroservices/AccountMicroservice/entities/User.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorials.learnmicroservices.AccountMicroservice.entities; 2 | 3 | 4 | //1) JPA 5 | //2) JSR-303 6 | //3) LOMBOK 7 | 8 | 9 | 10 | import lombok.AllArgsConstructor; 11 | import lombok.Getter; 12 | import lombok.NoArgsConstructor; 13 | import lombok.Setter; 14 | import org.hibernate.validator.constraints.NotBlank; 15 | import org.hibernate.validator.constraints.NotEmpty; 16 | 17 | import javax.persistence.Column; 18 | import javax.persistence.Entity; 19 | import javax.persistence.Id; 20 | import javax.persistence.Table; 21 | import javax.validation.constraints.NotNull; 22 | 23 | @AllArgsConstructor @NoArgsConstructor //Lombok annotations 24 | @Entity //JPA defines an Entity 25 | @Table(name = "users") //JPA (if table name in the DB differs from Class Name) 26 | public class User { 27 | 28 | 29 | //String ID, String USERNAME, String PASSWORD, String PERMISSION 30 | 31 | @Id //JPA id of the table 32 | @Column(name="ID") //JPA (if column name is different from variable name) 33 | @NotEmpty @NotBlank @NotNull //JSR-303 Validation 34 | @Getter @Setter //Lombok annotations 35 | private String id; 36 | 37 | @Column(name="USERNAME") //JPA (if column name is different from variable name) 38 | @NotEmpty @NotBlank @NotNull //JSR-303 Validation 39 | @Getter @Setter //Lombok annotations 40 | private String username; 41 | 42 | @Column(name="PASSWORD") //JPA (if column name is different from variable name) 43 | @NotEmpty @NotBlank @NotNull //JSR-303 Validation 44 | @Getter @Setter //Lombok annotations 45 | private String password; 46 | 47 | @Column(name="PERMISSION") //JPA (if column name is different from variable name) 48 | @NotEmpty @NotBlank @NotNull //JSR-303 Validation 49 | @Getter @Setter //Lombok annotations 50 | private String permission; 51 | 52 | 53 | 54 | } 55 | -------------------------------------------------------------------------------- /AccountMicroservice/src/main/java/com/quicktutorials/learnmicroservices/AccountMicroservice/services/LoginService.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorials.learnmicroservices.AccountMicroservice.services; 2 | 3 | import com.quicktutorials.learnmicroservices.AccountMicroservice.entities.User; 4 | import com.quicktutorials.learnmicroservices.AccountMicroservice.utils.UserNotLoggedException; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | import java.io.UnsupportedEncodingException; 8 | import java.util.Date; 9 | import java.util.Map; 10 | import java.util.Optional; 11 | 12 | public interface LoginService { 13 | 14 | Optional getUserFromDbAndVerifyPassword(String id, String password)throws UserNotLoggedException; 15 | //-> userDao.findById(id), encryptionUtils.decrypt(pwd) -> UserNotLoggedException 16 | 17 | String createJwt(String subject, String name, String permission, Date date) throws UnsupportedEncodingException; 18 | //-> JwtUtils.generateJwt(...) -> UnsupportedEncodingException 19 | 20 | 21 | Map verifyJwtAndGetData(HttpServletRequest request) throws UserNotLoggedException, UnsupportedEncodingException; 22 | //-> JwtUtils.getJwtFromHttpRequest(request) -> UserNotLoggedException 23 | // -> JwtUtils.jwt2Map(jwt) -> UnsupportedEncodingException 24 | // -> ExpiredJwtException 25 | 26 | 27 | } 28 | -------------------------------------------------------------------------------- /AccountMicroservice/src/main/java/com/quicktutorials/learnmicroservices/AccountMicroservice/services/LoginServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorials.learnmicroservices.AccountMicroservice.services; 2 | 3 | import com.quicktutorials.learnmicroservices.AccountMicroservice.daos.UserDao; 4 | import com.quicktutorials.learnmicroservices.AccountMicroservice.entities.User; 5 | import com.quicktutorials.learnmicroservices.AccountMicroservice.utils.EncryptionUtils; 6 | import com.quicktutorials.learnmicroservices.AccountMicroservice.utils.JwtUtils; 7 | import com.quicktutorials.learnmicroservices.AccountMicroservice.utils.UserNotLoggedException; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.stereotype.Service; 12 | 13 | import javax.servlet.http.HttpServletRequest; 14 | import java.io.UnsupportedEncodingException; 15 | import java.util.Date; 16 | import java.util.Map; 17 | import java.util.Optional; 18 | 19 | @Service 20 | public class LoginServiceImpl implements LoginService{ 21 | 22 | private static final Logger log = LoggerFactory.getLogger(LoginServiceImpl.class); 23 | 24 | @Autowired 25 | UserDao userDao; 26 | 27 | @Autowired 28 | EncryptionUtils encryptionUtils; 29 | 30 | 31 | 32 | @Override 33 | public Optional getUserFromDbAndVerifyPassword(String id, String password) throws UserNotLoggedException{ 34 | 35 | Optional userr = userDao.findById(id); 36 | if(userr.isPresent()){ 37 | User user = userr.get(); 38 | if(encryptionUtils.decrypt(user.getPassword()).equals(password)){ 39 | log.info("Username and Password verified"); 40 | }else{ 41 | log.info("Username verified. Password not"); 42 | throw new UserNotLoggedException("User not correctly logged in"); 43 | } 44 | } 45 | return userr; 46 | } 47 | 48 | 49 | @Override 50 | public String createJwt(String subject, String name, String permission, Date datenow) throws UnsupportedEncodingException{ 51 | Date expDate = datenow; 52 | expDate.setTime(datenow.getTime() + (300*1000)); 53 | log.info("JWT Creation. Expiration time: " + expDate.getTime()); 54 | String token = JwtUtils.generateJwt(subject, expDate, name, permission); 55 | return token; 56 | } 57 | 58 | 59 | @Override 60 | public Map verifyJwtAndGetData(HttpServletRequest request) throws UserNotLoggedException, UnsupportedEncodingException{ 61 | String jwt = JwtUtils.getJwtFromHttpRequest(request); 62 | if(jwt == null){ 63 | throw new UserNotLoggedException("Authentication token not found in the request"); 64 | } 65 | Map userData = JwtUtils.jwt2Map(jwt); 66 | return userData; 67 | } 68 | 69 | 70 | } 71 | -------------------------------------------------------------------------------- /AccountMicroservice/src/main/java/com/quicktutorials/learnmicroservices/AccountMicroservice/services/OperationService.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorials.learnmicroservices.AccountMicroservice.services; 2 | 3 | import com.quicktutorials.learnmicroservices.AccountMicroservice.entities.Account; 4 | import com.quicktutorials.learnmicroservices.AccountMicroservice.entities.Operation; 5 | 6 | import java.util.List; 7 | 8 | public interface OperationService { 9 | 10 | List getAllOperationPerAccount(String accountId); 11 | List getAllAccountsPerUser(String userId); 12 | Operation saveOperation(Operation operation); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /AccountMicroservice/src/main/java/com/quicktutorials/learnmicroservices/AccountMicroservice/services/OperationServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorials.learnmicroservices.AccountMicroservice.services; 2 | 3 | 4 | import com.quicktutorials.learnmicroservices.AccountMicroservice.daos.AccountDao; 5 | import com.quicktutorials.learnmicroservices.AccountMicroservice.daos.OperationDao; 6 | import com.quicktutorials.learnmicroservices.AccountMicroservice.entities.Account; 7 | import com.quicktutorials.learnmicroservices.AccountMicroservice.entities.Operation; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.stereotype.Service; 10 | 11 | 12 | import javax.transaction.Transactional; 13 | import java.util.Date; 14 | import java.util.List; 15 | 16 | @Service @Transactional 17 | public class OperationServiceImpl implements OperationService { 18 | 19 | @Autowired 20 | AccountDao accountDao; 21 | 22 | @Autowired 23 | OperationDao operationDao; 24 | 25 | 26 | @Override 27 | public List getAllOperationPerAccount(String accountId){ 28 | return operationDao.findAllOperationsByAccount(accountId); 29 | } 30 | 31 | @Override 32 | public List getAllAccountsPerUser(String userId){ 33 | return accountDao.getAllAccountsPerUser(userId); 34 | } 35 | 36 | @Override 37 | public Operation saveOperation(Operation operation){ 38 | 39 | if(operation.getDate() == null){ 40 | operation.setDate(new Date()); 41 | } 42 | 43 | return operationDao.save(operation); 44 | } 45 | 46 | 47 | 48 | } 49 | -------------------------------------------------------------------------------- /AccountMicroservice/src/main/java/com/quicktutorials/learnmicroservices/AccountMicroservice/utils/EncryptionUtils.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorials.learnmicroservices.AccountMicroservice.utils; 2 | 3 | 4 | import org.jasypt.util.text.BasicTextEncryptor; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Component; 7 | 8 | /** 9 | * This class provides a series of method in order to encrypt and decript user passwords. it uses jasypt library 10 | */ 11 | @Component //Spring will automatically instatiate and inject this component as a normal @Bean defined into a @Configuration file 12 | public class EncryptionUtils { 13 | 14 | @Autowired //@Bean declared in @SpringBootApplication file and injected here by Spring 15 | BasicTextEncryptor textEncryptor; 16 | 17 | /* 18 | this method provides an encryption of the String passed in input 19 | */ 20 | public String encrypt(String data){ 21 | return textEncryptor.encrypt(data); 22 | } 23 | 24 | /* 25 | this method provides a decryption of the String passed in input 26 | */ 27 | public String decrypt(String encriptedData){ 28 | return textEncryptor.decrypt(encriptedData); 29 | } 30 | 31 | } -------------------------------------------------------------------------------- /AccountMicroservice/src/main/java/com/quicktutorials/learnmicroservices/AccountMicroservice/utils/JwtUtils.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorials.learnmicroservices.AccountMicroservice.utils; 2 | 3 | import io.jsonwebtoken.*; 4 | import org.springframework.stereotype.Component; 5 | 6 | import javax.servlet.http.Cookie; 7 | import javax.servlet.http.HttpServletRequest; 8 | import java.util.Date; 9 | import java.util.HashMap; 10 | import java.util.Map; 11 | 12 | /** 13 | * This class provides method in order to generate and validate JSON Web Tokens 14 | */ 15 | //it will be automatically instantiated and injected by Spring 16 | public class JwtUtils { 17 | 18 | //https://stormpath.com/blog/jwt-java-create-verify 19 | //https://stormpath.com/blog/beginners-guide-jwts-in-java 20 | //https://github.com/jwtk/jjwt 21 | 22 | /** 23 | * this method generate the Jwt token to be sent to the client 24 | * @param subject "RGNLSN87H13D761R" 25 | * @param date new Date(1300819380) 26 | * @param name "Alessandro Argentieri" 27 | * @param scope "user" 28 | * @return String jwt 29 | * @throws java.io.UnsupportedEncodingException 30 | */ 31 | public static String generateJwt(String subject, Date date, String name, String scope) throws java.io.UnsupportedEncodingException{ 32 | 33 | String jwt = Jwts.builder() 34 | .setSubject(subject) 35 | .setExpiration(date) 36 | .claim("name", name) 37 | .claim("scope", scope) 38 | .signWith( 39 | SignatureAlgorithm.HS256, 40 | "myPersonalSecretKey12345".getBytes("UTF-8") 41 | ) 42 | .compact(); 43 | 44 | return jwt; 45 | } 46 | 47 | /** 48 | * this method converts the token into a map of Userdata checking it's validity 49 | * @param jwt 50 | * @return HashMap of user data 51 | * @throws java.io.UnsupportedEncodingException 52 | */ 53 | public static Map jwt2Map(String jwt) throws java.io.UnsupportedEncodingException, ExpiredJwtException{ 54 | 55 | Jws claim = Jwts.parser() 56 | .setSigningKey("myPersonalSecretKey12345".getBytes("UTF-8")) 57 | .parseClaimsJws(jwt); 58 | 59 | String name = claim.getBody().get("name", String.class); 60 | String scope = (String) claim.getBody().get("scope"); 61 | 62 | Date expDate = claim.getBody().getExpiration(); 63 | String subj = claim.getBody().getSubject(); 64 | 65 | Map userData = new HashMap<>(); 66 | userData.put("name", name); 67 | userData.put("scope", scope); 68 | userData.put("exp_date", expDate); 69 | userData.put("subject", subj); 70 | 71 | Date now = new Date(); 72 | if(now.after(expDate)){ 73 | throw new ExpiredJwtException(null, null, "Session expired!"); 74 | } 75 | 76 | return userData; 77 | } 78 | 79 | 80 | /** 81 | * this method extracts the jwt from the header or the cookie in the Http request 82 | * @param request 83 | * @return jwt 84 | */ 85 | public static String getJwtFromHttpRequest(HttpServletRequest request){ 86 | String jwt = null; 87 | if(request.getHeader("jwt") != null){ 88 | jwt = request.getHeader("jwt"); //token present in header 89 | }else if(request.getCookies() != null){ 90 | Cookie[] cookies = request.getCookies(); //token present in cookie 91 | for (Cookie cookie : cookies) { 92 | if (cookie.getName().equals("jwt")) { 93 | jwt = cookie.getValue(); 94 | } 95 | } 96 | } 97 | return jwt; 98 | } 99 | 100 | 101 | 102 | 103 | 104 | } 105 | -------------------------------------------------------------------------------- /AccountMicroservice/src/main/java/com/quicktutorials/learnmicroservices/AccountMicroservice/utils/UserNotLoggedException.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorials.learnmicroservices.AccountMicroservice.utils; 2 | 3 | public class UserNotLoggedException extends Exception { 4 | 5 | public UserNotLoggedException(String errorMessage){ 6 | super(errorMessage); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /AccountMicroservice/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port = 8094 -------------------------------------------------------------------------------- /AccountMicroservice/src/main/resources/static/js/actions.js: -------------------------------------------------------------------------------- 1 | 2 | $(document).ready(function(){ 3 | $("#signin_section").show(); /* it shows the sign in and hide the operation sections */ 4 | $("#operation_section").hide(); 5 | ChangeUrl("Signin","/signin.html"); /* it sets the new url when the page is loaded */ 6 | }); 7 | 8 | /* -------- functions --------- */ 9 | 10 | 11 | /* function used to get the jwt from cookies after having saved it, for later async ajax calls to microservices */ 12 | function getCookie(name) { 13 | var value = "; " + document.cookie; 14 | var parts = value.split("; " + name + "="); 15 | if (parts.length == 2) 16 | return parts.pop().split(";").shift(); 17 | } 18 | 19 | /* function used to change the text of the url giving the impression we're changing page */ 20 | function ChangeUrl(title, url) { 21 | if (typeof (history.pushState) != "undefined") { 22 | var obj = { Title: title, Url: url }; 23 | history.pushState(obj, obj.Title, obj.Url); 24 | } else { 25 | alert("Browser does not support HTML5."); 26 | } 27 | } 28 | 29 | 30 | /* -------- on click events -------- */ 31 | 32 | /* sign in submit function */ 33 | $("#submit").click(function(e) { 34 | e.preventDefault(); 35 | $.ajax({ /* Ajax call to AccountMicroservice for login */ 36 | url: 'http://localhost:8094/login', 37 | type: "POST", 38 | data: { 39 | id: $("#id").val(), 40 | password: $("#password").val() 41 | }, 42 | success: function (data, status, xhr) { 43 | $("#signin_section").hide(); /* it hides sign in section and shows operation section */ 44 | $("#operation_section").show(); 45 | $("#showCoupon").hide(); 46 | $("#operations").hide(); 47 | console.log(data); 48 | ChangeUrl("Operations","/operations.html"); /* it changes url after sign in */ 49 | 50 | document.cookie = "jwt=" + xhr.getResponseHeader("jwt"); /* it saves in cookies the received token */ 51 | }, 52 | error: function(result) { 53 | alert("Sign in failed!"); 54 | console.log(result); 55 | } 56 | }); 57 | }); 58 | 59 | 60 | 61 | /* sign out submit function */ 62 | $("#signout").click(function(e) { 63 | e.preventDefault(); 64 | document.cookie = "jwt=;expires=Thu, 01 Jan 1970 00:00:01 GMT;"; /* it cancels jwt from cookies */ 65 | $("#accountsList").empty(); 66 | $("#operationsTitle").empty(); /* it empties all lists and info */ 67 | $("#operationsList").empty(); 68 | $("#operations").hide(); 69 | $("#signin_section").show(); /* it hides operations and shows sign in section */ 70 | $("#operation_section").hide(); 71 | alert("You're logged out!"); 72 | ChangeUrl("Signin","/signin.html"); /* it changes url again to signin.html */ 73 | }); 74 | 75 | 76 | /* on click of #getAllAccounts button */ 77 | $("#getAccounts").click(function(e) { 78 | e.preventDefault(); 79 | 80 | /* first Ajax call */ 81 | $.ajax({ /* Ajax call to AccountMicroservice for accouns */ 82 | url: 'http://localhost:8094/accounts/user', 83 | type: "POST", 84 | success: function (data, status, xhr) { 85 | console.log(data); 86 | $("#accountsList").empty(); /* Reset info */ 87 | $("#operationsTitle").empty(); 88 | $("#operationsList").empty(); 89 | $("#showCoupon").show(); 90 | $("#operations").hide(); 91 | jQuery.each(data.response, function(i, val) { 92 | /* with the response it fills #accountList */ 93 | $("#accountsList").append("
  • Account " + val.id+ "

  • "); 94 | }); 95 | }, 96 | error: function(result) { 97 | alert("Error accessing accounts!"); 98 | console.log(result); 99 | } 100 | }); 101 | 102 | /* second Ajax call */ 103 | $.ajax({ /* Ajax call to CouponMicroservice for coupons */ 104 | url: 'http://localhost:8095/findCoupon', 105 | type: "POST", 106 | data: { 107 | jwt: getCookie("jwt") /* it gets jwt from cookies and send as body POST */ 108 | }, 109 | success: function (data, status, xhr) { 110 | console.log(data); 111 | $("#coupons").empty(); 112 | $("#coupons").append(data.response); /* it resets and fills #coupons section with result */ 113 | console.log("Data.response: " + data.response); 114 | }, 115 | error: function(result) { 116 | alert("Error accessing CouponMicroservice!"); 117 | console.log(result); 118 | } 119 | }); 120 | 121 | }); 122 | 123 | 124 | /* onclick on the choosen Account */ 125 | //get operation for one account 126 | $(document).on('click', '.accountButton', function (e) { 127 | e.preventDefault(); 128 | $("#operationsTitle").text("Operations for account number " + e.target.id); /* it sets the title of the section */ 129 | $.ajax({ /* Ajax call to AccountMicroservice */ 130 | url: 'http://localhost:8094/operations/account/' + e.target.id, 131 | type: "GET", 132 | success: function (data, status, xhr) { 133 | console.log(data); 134 | $("#operationsList").empty(); 135 | jQuery.each(data.response, function(i, val) { 136 | /* with the response it fills #operationsList */ 137 | $("#operationsList").append("
  • COD: " + val.id + ", DESCR: " + val.description + ", VALUE: " + val.value + "

  • "); 138 | }); 139 | }, 140 | error: function(result) { 141 | alert("Error!"); 142 | console.log(result); 143 | } 144 | }); 145 | $("#operations").show(); /* it shows the sub section of the operations */ 146 | $("#codeInput").val(""); /* it empties the form to save a new operation */ 147 | $("#descrInput").val(""); 148 | $("#valueInput").val(""); 149 | $("#fkAccount1Input").val(e.target.id); 150 | $("#fkAccount2Input").val(""); 151 | }); 152 | 153 | /* onclick to save a new operation in database */ 154 | $("#submitNewOperation").click(function(e) { 155 | e.preventDefault(); 156 | if($("#codeInput").val() != "" && $("#valueInput").val() != ""){ /* having a valid value to submit */ 157 | $.ajax({ 158 | url: 'http://localhost:8094/operations/add', /* Ajax call to AccountMicroservice to save operation */ 159 | type: "POST", 160 | data: { 161 | id: $("#codeInput").val(), /* it gets the values from the HTML5 form to send in req. */ 162 | value: $("#valueInput").val(), 163 | description: $("#descrInput").val(), 164 | fkAccount1: $("#fkAccount1Input").val(), 165 | fkAccount2: $("#fkAccount2Input").val() 166 | }, 167 | success: function (data, status, xhr) { 168 | alert("Success!"); 169 | $("#codeInput").val(""); /* it empties the form to save a new operation */ 170 | $("#descrInput").val(""); 171 | $("#valueInput").val(""); 172 | $("#fkAccount1Input").val(e.target.id); 173 | $("#fkAccount2Input").val(""); 174 | $("#operations").hide(); 175 | }, 176 | error: function(result) { 177 | alert("Error!"); 178 | console.log(result); 179 | } 180 | }); 181 | }else{ 182 | alert("Insert a valid operation!"); 183 | } 184 | }); 185 | 186 | -------------------------------------------------------------------------------- /AccountMicroservice/src/main/resources/static/signin.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Single Page App 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
    16 |

    Sign in

    17 |
    18 |
    19 | USER ID CODE:
    20 |
    21 | PASSWORD:
    22 |
    23 |
    24 | 25 |
    26 | 27 | 28 | 29 |
    30 | 31 | Sign out 32 | 33 |

    You're logged in!

    34 |
    35 | 36 |

    37 |
    38 | 39 |
    40 |

    Coupons

    41 |

    42 |
    43 |
    44 | 45 |
      46 | 47 | 48 |
      49 |
      50 | 51 |

      52 |
        53 | 54 |
        55 | 56 | 57 |

        New Operation

        58 |
        59 | 60 | 61 | 62 | 63 | 64 | 65 |
        66 | 67 | 68 |
        69 | 70 |
        71 | 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /AccountMicroservice/src/test/java/com/quicktutorials/learnmicroservices/AccountMicroservice/AccountMicroserviceApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorials.learnmicroservices.AccountMicroservice; 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 AccountMicroserviceApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /CouponMicroservice/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /CouponMicroservice/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alessandroargentieri/Sviluppo-web-a-microservizi-REST-con-Java-Spring-boot-e-AJAX/478893c571d150ab9e8b68310d66e84673f3f6f0/CouponMicroservice/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /CouponMicroservice/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip 2 | -------------------------------------------------------------------------------- /CouponMicroservice/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 | # http://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 Migwn, 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 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /CouponMicroservice/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 http://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 enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /CouponMicroservice/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.quicktutorialz.learnmicroservices 7 | CouponMicroservice 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | CouponMicroservice 12 | It consumes the rest message of account microservice 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.7.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-data-jpa 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-web 35 | 36 | 37 | 38 | mysql 39 | mysql-connector-java 40 | runtime 41 | 5.1.39 42 | 43 | 44 | org.projectlombok 45 | lombok 46 | true 47 | 1.16.10 48 | 49 | 50 | org.springframework.boot 51 | spring-boot-starter-test 52 | test 53 | 54 | 55 | 56 | 57 | 58 | 59 | org.springframework.boot 60 | spring-boot-maven-plugin 61 | 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /CouponMicroservice/src/main/java/com/quicktutorialz/learnmicroservices/CouponMicroservice/CouponMicroserviceApplication.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorialz.learnmicroservices.CouponMicroservice; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class CouponMicroserviceApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(CouponMicroserviceApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /CouponMicroservice/src/main/java/com/quicktutorialz/learnmicroservices/CouponMicroservice/controllers/RestController.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorialz.learnmicroservices.CouponMicroservice.controllers; 2 | 3 | import com.quicktutorialz.learnmicroservices.CouponMicroservice.entities.JsonResponseBody; 4 | import com.quicktutorialz.learnmicroservices.CouponMicroservice.services.CouponService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.http.HttpStatus; 7 | import org.springframework.http.ResponseEntity; 8 | import org.springframework.web.bind.annotation.CrossOrigin; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.RequestParam; 11 | 12 | 13 | @org.springframework.web.bind.annotation.RestController 14 | public class RestController { 15 | 16 | @Autowired 17 | CouponService couponService; 18 | 19 | @CrossOrigin 20 | @RequestMapping("/findCoupon") 21 | public ResponseEntity findCoupons(@RequestParam (value = "jwt") String jwt){ 22 | try { 23 | String coupons = couponService.getAvailableCoupons(jwt); 24 | return ResponseEntity.status(HttpStatus.OK).body(new JsonResponseBody(HttpStatus.OK.value(), coupons)); 25 | }catch(Exception e) { 26 | return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new JsonResponseBody(HttpStatus.BAD_REQUEST.value(), "Error: " + e.toString())); 27 | } 28 | } 29 | 30 | @RequestMapping("/test") 31 | public String test(){ 32 | return "CouponService works correctly"; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /CouponMicroservice/src/main/java/com/quicktutorialz/learnmicroservices/CouponMicroservice/daos/CouponDao.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorialz.learnmicroservices.CouponMicroservice.daos; 2 | 3 | import com.quicktutorialz.learnmicroservices.CouponMicroservice.entities.Coupon; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | import java.util.Optional; 7 | 8 | public interface CouponDao extends JpaRepository { 9 | 10 | Optional findByAccount(String account); 11 | } 12 | -------------------------------------------------------------------------------- /CouponMicroservice/src/main/java/com/quicktutorialz/learnmicroservices/CouponMicroservice/entities/Coupon.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorialz.learnmicroservices.CouponMicroservice.entities; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | import lombok.NoArgsConstructor; 6 | import lombok.Setter; 7 | 8 | import javax.persistence.*; 9 | 10 | @Table (name="coupon") 11 | @Entity 12 | @AllArgsConstructor @NoArgsConstructor 13 | public class Coupon { 14 | 15 | @Id 16 | @Column(name="couponid") 17 | @Getter @Setter 18 | @GeneratedValue(strategy = GenerationType.AUTO) 19 | private int id; 20 | 21 | @Column(name="couponcode") 22 | @Getter @Setter 23 | private String code; 24 | 25 | @Column(name="account") 26 | @Getter @Setter 27 | private String account; 28 | 29 | 30 | } 31 | -------------------------------------------------------------------------------- /CouponMicroservice/src/main/java/com/quicktutorialz/learnmicroservices/CouponMicroservice/entities/JsonResponseBody.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorialz.learnmicroservices.CouponMicroservice.entities; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | 7 | @AllArgsConstructor 8 | public class JsonResponseBody{ 9 | @Getter 10 | @Setter 11 | private int server; 12 | @Getter @Setter 13 | private Object response; 14 | } -------------------------------------------------------------------------------- /CouponMicroservice/src/main/java/com/quicktutorialz/learnmicroservices/CouponMicroservice/services/CouponService.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorialz.learnmicroservices.CouponMicroservice.services; 2 | 3 | 4 | 5 | public interface CouponService { 6 | 7 | String getAvailableCoupons(String jwt); 8 | 9 | } 10 | -------------------------------------------------------------------------------- /CouponMicroservice/src/main/java/com/quicktutorialz/learnmicroservices/CouponMicroservice/services/CouponServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorialz.learnmicroservices.CouponMicroservice.services; 2 | 3 | 4 | import com.quicktutorialz.learnmicroservices.CouponMicroservice.daos.CouponDao; 5 | import com.quicktutorialz.learnmicroservices.CouponMicroservice.entities.Coupon; 6 | import com.quicktutorialz.learnmicroservices.CouponMicroservice.entities.JsonResponseBody; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.http.HttpEntity; 9 | import org.springframework.http.HttpMethod; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.stereotype.Service; 12 | import org.springframework.util.LinkedMultiValueMap; 13 | import org.springframework.util.MultiValueMap; 14 | import org.springframework.web.client.RestTemplate; 15 | 16 | import java.util.LinkedHashMap; 17 | import java.util.List; 18 | import java.util.Optional; 19 | 20 | 21 | @Service 22 | public class CouponServiceImpl implements CouponService{ 23 | 24 | @Autowired 25 | CouponDao couponDao; 26 | 27 | @Override 28 | public String getAvailableCoupons(String jwt){ 29 | 30 | List accounts = getAccountsGivenJwt(jwt); 31 | 32 | if(accounts !=null && accounts.size() > 0){ 33 | String availableCoupons = ""; 34 | for(int i=0; i couponn = couponDao.findByAccount(idAccount); 38 | if(couponn.isPresent()){ 39 | availableCoupons = availableCoupons + "CouponCode: " + couponn.get().getCode() + " (for Account: " + idAccount + ") "; 40 | } 41 | } 42 | 43 | return "Available coupons: " + availableCoupons; 44 | } 45 | 46 | return "No coupon available for the user"; 47 | } 48 | 49 | 50 | 51 | //makes the call to the AccountMicroservice 52 | private List getAccountsGivenJwt(String jwt){ 53 | 54 | //preparing the header for the request (adding the jwt) 55 | MultiValueMap headers = new LinkedMultiValueMap(); 56 | headers.add("jwt", jwt); 57 | HttpEntity request = new HttpEntity(String.class, headers); 58 | 59 | RestTemplate restTemplate = new RestTemplate(); 60 | ResponseEntity responseEntity = restTemplate.exchange("http://localhost:8094/accounts/user", HttpMethod.POST, request, JsonResponseBody.class); 61 | 62 | List accounts = (List) responseEntity.getBody().getResponse(); 63 | return accounts; 64 | 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /CouponMicroservice/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8095 2 | spring.jpa.hibernate.ddl-auto=none 3 | spring.datasource.url=jdbc:mysql://localhost:3306/coupondb 4 | spring.datasource.username=springuser 5 | spring.datasource.password=ThePassword -------------------------------------------------------------------------------- /CouponMicroservice/src/test/java/com/quicktutorialz/learnmicroservices/CouponMicroservice/CouponMicroserviceApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.quicktutorialz.learnmicroservices.CouponMicroservice; 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 CouponMicroserviceApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /README - Database MySQL: -------------------------------------------------------------------------------- 1 | 2 | 1. Scaricare XAMPP 3 | 2. Aprire il Control Panel 4 | 3. Avviare i server MySQL e Apache dal control Panel 5 | 4. Aprire il browser 6 | 5. Scrivere localhost/phpmyadmin nella barra degli indirizzi 7 | 6. Andare nella sezione "Databases" 8 | 7. Andare nella sezione "Import" 9 | 8. Importare il file "coupondb.sql" 10 | 9. Cliccare su "Go" 11 | 10. Il database è correttamente importato -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Sviluppo-web-a-microservizi-REST-con-Java-Spring-boot-e-AJAX 2 | Materiale del corso UDEMY : Sviluppo web a microservizi REST con Java Spring boot e AJAX 3 | 4 | https://www.udemy.com/draft/1346864/?couponCode=LEARNMICROSERVICES75 5 | 6 | Snippet e risorse per il corso 7 | 8 | ----------------------------------------- 9 | 10 | ## Documentazioni e tutorial ## 11 | 12 | Istruzioni installazione JRE 1.8 13 | https://www.java.com/it/download/help/download_options.xml 14 | 15 | Istruzioni installazione Maven 16 | https://maven.apache.org/install.html 17 | 18 | Istruzioni installazione Git 19 | https://git-scm.com/book/it/v1/Per-Iniziare-Installare-Git 20 | 21 | Istruzioni installazione IntelliJIDEA Community Edition 22 | https://www.jetbrains.com/idea/documentation/ 23 | 24 | Link di istallazione di XAMPP: 25 | https://www.apachefriends.org/download.html 26 | 27 | Documentazione Spring Framework 28 | https://docs.spring.io/spring/docs/current/spring-framework-reference/pdf/spring-framework-reference.pdf 29 | 30 | Documentazione Spring Boot 31 | https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/ 32 | 33 | Documentazione JPA 34 | https://docs.spring.io/spring-data/jpa/docs/current/reference/pdf/spring-data-jpa-reference.pdf 35 | 36 | Ottimo tutorial JPA 37 | https://www.petrikainulainen.net/spring-data-jpa-tutorial/ 38 | 39 | Strategie per definire i metodi-query 40 | https://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-creating-database-queries-from-method-names/ 41 | https://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-introduction-to-query-methods/ 42 | 43 | Documentazione JWT 44 | https://stormpath.com/blog/jwt-java-create-verify 45 | https://stormpath.com/blog/beginners-guide-jwts-in-java 46 | https://github.com/jwtk/jjwt 47 | 48 | Documentazione JSR-303 49 | http://beanvalidation.org/1.0/spec/ 50 | 51 | Project Lombok 52 | https://projectlombok.org/ 53 | 54 | Libreria criptaggio password 55 | http://www.jasypt.org/ 56 | 57 | Istruzioni installazione PostMan 58 | https://www.angeloparziale.it/blog/2017/06/22/postman/ 59 | 60 | Documentazione AJAX: 61 | https://www.w3schools.com/xml/ajax_intro.asp 62 | 63 | ------------------------------------------ 64 | 65 | # Snippets o link utili: # 66 | 67 | ## Spring Initializer ## 68 | 69 | 70 | ## Struttura del DB ## 71 | 72 | ### nome DB: accountdb (H2 - in Memory DB) il nome non è importante ### 73 | 74 | TABLE users (String ID, String USERNAME, String PASSWORD, String PERMISSION) 75 | 76 | TABLE accounts (String ID, String FK_USER, Double TOTAL) 77 | 78 | TABLE operations (String ID, Date DATE, Double VALUE, String DESCRIPTION, String FK_ACCOUNT1, String FK_ACCOUNT2) 79 | 80 | ### nome DB: coupondb (in MySQL) ### 81 | 82 | TABLE coupon ( (autogenerated int) couponid, String couponcode, String account) 83 | 84 | 85 | ------------------------------------------ 86 | 87 | ## pom.xml di AccountMicroservice ## 88 | 89 | 90 | 92 | 4.0.0 93 | 94 | com.quicktutorials.learnmicroservices 95 | AccountMicroservice 96 | 0.0.1-SNAPSHOT 97 | jar 98 | 99 | AccountMicroservice 100 | First Microservice in SpringBoot 101 | 102 | 103 | org.springframework.boot 104 | spring-boot-starter-parent 105 | 1.5.7.RELEASE 106 | 107 | 108 | 109 | 110 | UTF-8 111 | UTF-8 112 | 1.8 113 | 114 | 115 | 116 | 117 | org.springframework.boot 118 | spring-boot-starter-data-jpa 119 | 120 | 121 | org.springframework.boot 122 | spring-boot-starter-web 123 | 124 | 125 | 126 | com.h2database 127 | h2 128 | runtime 129 | 130 | 131 | org.projectlombok 132 | lombok 133 | true 134 | 1.16.10 135 | 136 | 137 | org.springframework.boot 138 | spring-boot-starter-test 139 | test 140 | 141 | 142 | org.jasypt 143 | jasypt 144 | 1.9.2 145 | 146 | 147 | io.jsonwebtoken 148 | jjwt 149 | 0.7.0 150 | 151 | 152 | 153 | 154 | 155 | 156 | org.springframework.boot 157 | spring-boot-maven-plugin 158 | 159 | 160 | 161 | 162 | 163 | ------------------------------------------ 164 | 165 | ## pom.xml di CouponMicroservice ## 166 | 167 | 168 | 170 | 4.0.0 171 | 172 | com.quicktutorialz.learnmicroservices 173 | CouponMicroservice 174 | 0.0.1-SNAPSHOT 175 | jar 176 | 177 | CouponMicroservice 178 | It consumes the rest message of account microservice 179 | 180 | 181 | org.springframework.boot 182 | spring-boot-starter-parent 183 | 1.5.7.RELEASE 184 | 185 | 186 | 187 | 188 | UTF-8 189 | UTF-8 190 | 1.8 191 | 192 | 193 | 194 | 195 | org.springframework.boot 196 | spring-boot-starter-data-jpa 197 | 198 | 199 | org.springframework.boot 200 | spring-boot-starter-web 201 | 202 | 203 | 204 | mysql 205 | mysql-connector-java 206 | runtime 207 | 5.1.39 208 | 209 | 210 | org.projectlombok 211 | lombok 212 | true 213 | 1.16.10 214 | 215 | 216 | org.springframework.boot 217 | spring-boot-starter-test 218 | test 219 | 220 | 221 | 222 | 223 | 224 | 225 | org.springframework.boot 226 | spring-boot-maven-plugin 227 | 228 | 229 | 230 | 231 | 232 | ------------------------------------------ 233 | 234 | ## Metodi dei due Service di AccountMicroservice: ## 235 | 236 | ### LoginService: ### 237 | 238 | ```Optional(User) getUserFromDbAndVerifyPassword(String id, String password)``` 239 | #### Richiama al suo interno: #### 240 | * userDao.findById(id), encryptionUtils.decrypt(pwd) 241 | #### che possono entrambe lanciare: #### 242 | * UserNotLoggedException 243 | 244 | ```String createJwt(String subject, String name, String permission, Date date) ``` 245 | #### Richiama al suo interno: #### 246 | * JwtUtils.generateJwt(...) 247 | #### che può lanciare: #### 248 | * UnsupportedEncodingException 249 | 250 | ```Map verifyJwtAndGetData(HttpServletRequest request)``` 251 | #### Richiama al suo interno: #### 252 | * JwtUtils.getJwtFromHttpRequest(request) 253 | #### che può lanciare: #### 254 | * UserNotLoggedException 255 | #### Richiama anche:#### 256 | * JwtUtils.jwt2Map(jwt) 257 | #### che può lanciare: #### 258 | * UnsupportedEncodingException 259 | * ExpiredJwtException 260 | 261 | ### OperationService: ### 262 | 263 | ```List getAllOperationPerAccount(String accountId)``` 264 | ```List getAllAccountsPerUser(String userId)``` 265 | ```Operation saveOperation(Operation operation)``` 266 | 267 | 268 | 269 | ------------------------------------------ 270 | # Interfaccia FRONT-END # 271 | 272 | ``` 273 | 274 | 275 | 276 | 277 | Single Page App 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 |
        288 |

        Sign in

        289 |
        290 |
        291 | USER ID CODE:
        292 |
        293 | PASSWORD:
        294 |
        295 |
        296 | 297 |
        298 | 299 | 300 | 301 |
        302 | 303 | Sign out 304 | 305 |

        You're logged in!

        306 |
        307 | 308 |

        309 |
        310 | 311 |
        312 |

        Coupons

        313 |

        314 |
        315 |
        316 | 317 |
          318 | 319 | 320 |
          321 |
          322 | 323 |

          324 |
            325 | 326 |
            327 | 328 | 329 |

            New Operation

            330 |
            331 | 332 | 333 | 334 | 335 | 336 | 337 |
            338 | 339 | 340 |
            341 | 342 |
            343 | 344 | 510 | 511 | 512 | 513 | 514 | 515 | ``` 516 | 517 | 518 | 519 | -------------------------------------------------------------------------------- /coupondb.sql: -------------------------------------------------------------------------------- 1 | -- phpMyAdmin SQL Dump 2 | -- version 4.7.0 3 | -- https://www.phpmyadmin.net/ 4 | -- 5 | -- Host: localhost 6 | -- Generation Time: Nov 08, 2017 at 11:42 AM 7 | -- Server version: 10.1.25-MariaDB 8 | -- PHP Version: 5.6.31 9 | 10 | SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 11 | SET AUTOCOMMIT = 0; 12 | START TRANSACTION; 13 | SET time_zone = "+00:00"; 14 | 15 | 16 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; 17 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; 18 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; 19 | /*!40101 SET NAMES utf8mb4 */; 20 | 21 | -- 22 | -- Database: `coupondb` 23 | -- 24 | CREATE DATABASE `coupondb`; 25 | -- -------------------------------------------------------- 26 | 27 | -- 28 | -- Table structure for table `coupon` 29 | -- 30 | 31 | CREATE TABLE `coupon` ( 32 | `couponid` int(11) NOT NULL, 33 | `couponcode` varchar(10) NOT NULL, 34 | `account` varchar(9) NOT NULL 35 | ) ENGINE=InnoDB DEFAULT CHARSET=latin1; 36 | 37 | -- 38 | -- Dumping data for table `coupon` 39 | -- 40 | 41 | INSERT INTO `coupon` (`couponid`, `couponcode`, `account`) VALUES 42 | (1, 'abcdefghi0', 'cn4563df3'), 43 | (2, 'abcdefghi1', 'cn7256su9'); 44 | 45 | -- 46 | -- Indexes for dumped tables 47 | -- 48 | 49 | -- 50 | -- Indexes for table `coupon` 51 | -- 52 | ALTER TABLE `coupon` 53 | ADD PRIMARY KEY (`couponid`); 54 | 55 | -- 56 | -- AUTO_INCREMENT for dumped tables 57 | -- 58 | 59 | -- 60 | -- AUTO_INCREMENT for table `coupon` 61 | -- 62 | ALTER TABLE `coupon` 63 | MODIFY `couponid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;COMMIT; 64 | 65 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; 66 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; 67 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; 68 | --------------------------------------------------------------------------------