diff --git a/apigateway-service/pom.xml b/apigateway-service/pom.xml
index 4329204..ebc98ce 100644
--- a/apigateway-service/pom.xml
+++ b/apigateway-service/pom.xml
@@ -37,6 +37,15 @@
spring-boot-starter-test
test
+
+ io.jsonwebtoken
+ jjwt
+ 0.9.1
+
+
+ javax.xml.bind
+ jaxb-api
+
diff --git a/apigateway-service/src/main/java/com/example/apigatewayservice/filter/AuthorizationHeaderFilter.java b/apigateway-service/src/main/java/com/example/apigatewayservice/filter/AuthorizationHeaderFilter.java
new file mode 100644
index 0000000..43cace6
--- /dev/null
+++ b/apigateway-service/src/main/java/com/example/apigatewayservice/filter/AuthorizationHeaderFilter.java
@@ -0,0 +1,76 @@
+package com.example.apigatewayservice.filter;
+
+import io.jsonwebtoken.Jwts;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.cloud.gateway.filter.GatewayFilter;
+import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
+import org.springframework.core.env.Environment;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.server.reactive.ServerHttpRequest;
+import org.springframework.http.server.reactive.ServerHttpResponse;
+import org.springframework.stereotype.Component;
+import org.springframework.web.server.ServerWebExchange;
+import reactor.core.publisher.Mono;
+
+@Component
+@Slf4j
+public class AuthorizationHeaderFilter extends AbstractGatewayFilterFactory {
+ Environment env;
+
+ public AuthorizationHeaderFilter(Environment env) {
+ super(Config.class);
+ this.env = env;
+ }
+
+ public static class Config {
+
+ }
+
+ //login->token->user(with token)->header(includ token)
+ @Override
+ public GatewayFilter apply(Config config) {
+ return ((exchange, chain) -> {
+ ServerHttpRequest request = exchange.getRequest();
+
+ //토큰이 포함된 채로 왔는지
+ if (!request.getHeaders().containsKey(HttpHeaders.AUTHORIZATION)) {
+ return onError(exchange, "No authorization header", HttpStatus.UNAUTHORIZED);
+ }
+
+ String authrozationHeader = request.getHeaders().get(HttpHeaders.AUTHORIZATION).get(0);
+ String jwt = authrozationHeader.replace("Bearer", "");
+
+ if (!isJwtValid(jwt)) {
+ return onError(exchange, "Jwt token is not valid", HttpStatus.UNAUTHORIZED);
+ }
+ return chain.filter(exchange);
+ });
+ }
+
+ //Mono그냥 단위값. 이외 Flux(여러개의 값을 가질경우)라는 단위값이 있음. Spring WebFlux에서 추가된 방식
+ private Mono onError(ServerWebExchange exchange, String err, HttpStatus httpStatus) {
+ ServerHttpResponse response=exchange.getResponse();
+ response.setStatusCode(httpStatus);
+ log.error(err);
+ return response.setComplete();
+ }
+
+ private boolean isJwtValid(String jwt) {
+ boolean returnValue=true;
+ String subject=null;
+
+ try {
+ subject = Jwts.parser().setSigningKey(env.getProperty("token.secret"))
+ .parseClaimsJws(jwt).getBody()
+ .getSubject();
+ }catch (Exception e){
+ returnValue =false;
+ }
+
+ if(subject==null||subject.isEmpty()){
+ returnValue=false;
+ }
+ return returnValue;
+ }
+}
\ No newline at end of file
diff --git a/apigateway-service/src/main/resources/application.yml b/apigateway-service/src/main/resources/application.yml
index f46e74a..8801813 100644
--- a/apigateway-service/src/main/resources/application.yml
+++ b/apigateway-service/src/main/resources/application.yml
@@ -20,6 +20,44 @@ spring:
preLogger: true
postLogger: true
routes:
+# - id: user-service
+# uri: lb://USER-SERVICE
+# predicates:
+# - Path=/user-service/**
+ #이 아래부분 필터 넣은 거가 route 변경 한 부분임
+ - id: user-service
+ uri: lb://USER-SERVICE
+ predicates:
+ - Path=/user-service/login
+ - Method=POST
+ filters:
+ - RemoveRequestHeader=Cookie
+ - RewritePath=/user-service/(?.*), /$\{segment}
+ - id: user-service
+ uri: lb://USER-SERVICE
+ predicates:
+ - Path=/user-service/users
+ - Method=POST
+ filters:
+ - RemoveRequestHeader=Cookie
+ - RewritePath=/user-service/(?.*), /$\{segment}
+ - id: user-service
+ uri: lb://USER-SERVICE
+ predicates:
+ - Path=/user-service/**
+ - Method=GET
+ filters:
+ - RemoveRequestHeader=Cookie
+ - RewritePath=/user-service/(?.*), /$\{segment}
+ - AuthorizationHeaderFilter
+ - id: catalog-service
+ uri: lb://CATALOG-SERVICE
+ predicates:
+ - Path=/catalog-service/**
+ - id: order-service
+ uri: lb://ORDER-SERVICE
+ predicates:
+ - Path=/order-service/**
- id: first-service
uri: lb://MY-FIRST-SERVICE
predicates:
@@ -40,4 +78,6 @@ spring:
args:
baseMessage: Hi, there.
preLogger: true
- postLogger: true
\ No newline at end of file
+ postLogger: true
+token:
+ secret: user_token
\ No newline at end of file
diff --git a/catalog-service/.mvn/wrapper/maven-wrapper.jar b/catalog-service/.mvn/wrapper/maven-wrapper.jar
new file mode 100644
index 0000000..bf82ff0
Binary files /dev/null and b/catalog-service/.mvn/wrapper/maven-wrapper.jar differ
diff --git a/catalog-service/.mvn/wrapper/maven-wrapper.properties b/catalog-service/.mvn/wrapper/maven-wrapper.properties
new file mode 100644
index 0000000..ca5ab4b
--- /dev/null
+++ b/catalog-service/.mvn/wrapper/maven-wrapper.properties
@@ -0,0 +1,18 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.7/apache-maven-3.8.7-bin.zip
+wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar
diff --git a/catalog-service/mvnw b/catalog-service/mvnw
new file mode 100644
index 0000000..8a8fb22
--- /dev/null
+++ b/catalog-service/mvnw
@@ -0,0 +1,316 @@
+#!/bin/sh
+# ----------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+# ----------------------------------------------------------------------------
+
+# ----------------------------------------------------------------------------
+# Maven Start Up Batch script
+#
+# Required ENV vars:
+# ------------------
+# JAVA_HOME - location of a JDK home dir
+#
+# Optional ENV vars
+# -----------------
+# M2_HOME - location of maven2's installed home dir
+# MAVEN_OPTS - parameters passed to the Java VM when running Maven
+# e.g. to debug Maven itself, use
+# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
+# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
+# ----------------------------------------------------------------------------
+
+if [ -z "$MAVEN_SKIP_RC" ] ; then
+
+ if [ -f /usr/local/etc/mavenrc ] ; then
+ . /usr/local/etc/mavenrc
+ fi
+
+ if [ -f /etc/mavenrc ] ; then
+ . /etc/mavenrc
+ fi
+
+ if [ -f "$HOME/.mavenrc" ] ; then
+ . "$HOME/.mavenrc"
+ fi
+
+fi
+
+# OS specific support. $var _must_ be set to either true or false.
+cygwin=false;
+darwin=false;
+mingw=false
+case "`uname`" in
+ CYGWIN*) cygwin=true ;;
+ MINGW*) mingw=true;;
+ Darwin*) darwin=true
+ # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
+ # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
+ if [ -z "$JAVA_HOME" ]; then
+ if [ -x "/usr/libexec/java_home" ]; then
+ export JAVA_HOME="`/usr/libexec/java_home`"
+ else
+ export JAVA_HOME="/Library/Java/Home"
+ fi
+ fi
+ ;;
+esac
+
+if [ -z "$JAVA_HOME" ] ; then
+ if [ -r /etc/gentoo-release ] ; then
+ JAVA_HOME=`java-config --jre-home`
+ fi
+fi
+
+if [ -z "$M2_HOME" ] ; then
+ ## resolve links - $0 may be a link to maven's home
+ PRG="$0"
+
+ # need this for relative symlinks
+ while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG="`dirname "$PRG"`/$link"
+ fi
+ done
+
+ saveddir=`pwd`
+
+ M2_HOME=`dirname "$PRG"`/..
+
+ # make it fully qualified
+ M2_HOME=`cd "$M2_HOME" && pwd`
+
+ cd "$saveddir"
+ # echo Using m2 at $M2_HOME
+fi
+
+# For Cygwin, ensure paths are in UNIX format before anything is touched
+if $cygwin ; then
+ [ -n "$M2_HOME" ] &&
+ M2_HOME=`cygpath --unix "$M2_HOME"`
+ [ -n "$JAVA_HOME" ] &&
+ JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
+ [ -n "$CLASSPATH" ] &&
+ CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
+fi
+
+# For Mingw, ensure paths are in UNIX format before anything is touched
+if $mingw ; then
+ [ -n "$M2_HOME" ] &&
+ M2_HOME="`(cd "$M2_HOME"; pwd)`"
+ [ -n "$JAVA_HOME" ] &&
+ JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
+fi
+
+if [ -z "$JAVA_HOME" ]; then
+ javaExecutable="`which javac`"
+ if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
+ # readlink(1) is not available as standard on Solaris 10.
+ readLink=`which readlink`
+ if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
+ if $darwin ; then
+ javaHome="`dirname \"$javaExecutable\"`"
+ javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
+ else
+ javaExecutable="`readlink -f \"$javaExecutable\"`"
+ fi
+ javaHome="`dirname \"$javaExecutable\"`"
+ javaHome=`expr "$javaHome" : '\(.*\)/bin'`
+ JAVA_HOME="$javaHome"
+ export JAVA_HOME
+ fi
+ fi
+fi
+
+if [ -z "$JAVACMD" ] ; then
+ if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ else
+ JAVACMD="`\\unset -f command; \\command -v java`"
+ fi
+fi
+
+if [ ! -x "$JAVACMD" ] ; then
+ echo "Error: JAVA_HOME is not defined correctly." >&2
+ echo " We cannot execute $JAVACMD" >&2
+ exit 1
+fi
+
+if [ -z "$JAVA_HOME" ] ; then
+ echo "Warning: JAVA_HOME environment variable is not set."
+fi
+
+CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
+
+# traverses directory structure from process work directory to filesystem root
+# first directory with .mvn subdirectory is considered project base directory
+find_maven_basedir() {
+
+ if [ -z "$1" ]
+ then
+ echo "Path not specified to find_maven_basedir"
+ return 1
+ fi
+
+ basedir="$1"
+ wdir="$1"
+ while [ "$wdir" != '/' ] ; do
+ if [ -d "$wdir"/.mvn ] ; then
+ basedir=$wdir
+ break
+ fi
+ # workaround for JBEAP-8937 (on Solaris 10/Sparc)
+ if [ -d "${wdir}" ]; then
+ wdir=`cd "$wdir/.."; pwd`
+ fi
+ # end of workaround
+ done
+ echo "${basedir}"
+}
+
+# concatenates all lines of a file
+concat_lines() {
+ if [ -f "$1" ]; then
+ echo "$(tr -s '\n' ' ' < "$1")"
+ fi
+}
+
+BASE_DIR=`find_maven_basedir "$(pwd)"`
+if [ -z "$BASE_DIR" ]; then
+ exit 1;
+fi
+
+##########################################################################################
+# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
+# This allows using the maven wrapper in projects that prohibit checking in binary data.
+##########################################################################################
+if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Found .mvn/wrapper/maven-wrapper.jar"
+ fi
+else
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
+ fi
+ if [ -n "$MVNW_REPOURL" ]; then
+ jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
+ else
+ jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
+ fi
+ while IFS="=" read key value; do
+ case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
+ esac
+ done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Downloading from: $jarUrl"
+ fi
+ wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
+ if $cygwin; then
+ wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
+ fi
+
+ if command -v wget > /dev/null; then
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Found wget ... using wget"
+ fi
+ if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
+ wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
+ else
+ wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
+ fi
+ elif command -v curl > /dev/null; then
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Found curl ... using curl"
+ fi
+ if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
+ curl -o "$wrapperJarPath" "$jarUrl" -f
+ else
+ curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
+ fi
+
+ else
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Falling back to using Java to download"
+ fi
+ javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
+ # For Cygwin, switch paths to Windows format before running javac
+ if $cygwin; then
+ javaClass=`cygpath --path --windows "$javaClass"`
+ fi
+ if [ -e "$javaClass" ]; then
+ if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo " - Compiling MavenWrapperDownloader.java ..."
+ fi
+ # Compiling the Java class
+ ("$JAVA_HOME/bin/javac" "$javaClass")
+ fi
+ if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
+ # Running the downloader
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo " - Running MavenWrapperDownloader.java ..."
+ fi
+ ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
+ fi
+ fi
+ fi
+fi
+##########################################################################################
+# End of extension
+##########################################################################################
+
+export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
+if [ "$MVNW_VERBOSE" = true ]; then
+ echo $MAVEN_PROJECTBASEDIR
+fi
+MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin; then
+ [ -n "$M2_HOME" ] &&
+ M2_HOME=`cygpath --path --windows "$M2_HOME"`
+ [ -n "$JAVA_HOME" ] &&
+ JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
+ [ -n "$CLASSPATH" ] &&
+ CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
+ [ -n "$MAVEN_PROJECTBASEDIR" ] &&
+ MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
+fi
+
+# Provide a "standardized" way to retrieve the CLI args that will
+# work with both Windows and non-Windows executions.
+MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
+export MAVEN_CMD_LINE_ARGS
+
+WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
+
+exec "$JAVACMD" \
+ $MAVEN_OPTS \
+ $MAVEN_DEBUG_OPTS \
+ -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
+ "-Dmaven.home=${M2_HOME}" \
+ "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
+ ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
diff --git a/catalog-service/mvnw.cmd b/catalog-service/mvnw.cmd
new file mode 100644
index 0000000..1d8ab01
--- /dev/null
+++ b/catalog-service/mvnw.cmd
@@ -0,0 +1,188 @@
+@REM ----------------------------------------------------------------------------
+@REM Licensed to the Apache Software Foundation (ASF) under one
+@REM or more contributor license agreements. See the NOTICE file
+@REM distributed with this work for additional information
+@REM regarding copyright ownership. The ASF licenses this file
+@REM to you under the Apache License, Version 2.0 (the
+@REM "License"); you may not use this file except in compliance
+@REM with the License. You may obtain a copy of the License at
+@REM
+@REM https://www.apache.org/licenses/LICENSE-2.0
+@REM
+@REM Unless required by applicable law or agreed to in writing,
+@REM software distributed under the License is distributed on an
+@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+@REM KIND, either express or implied. See the License for the
+@REM specific language governing permissions and limitations
+@REM under the License.
+@REM ----------------------------------------------------------------------------
+
+@REM ----------------------------------------------------------------------------
+@REM Maven Start Up Batch script
+@REM
+@REM Required ENV vars:
+@REM JAVA_HOME - location of a JDK home dir
+@REM
+@REM Optional ENV vars
+@REM M2_HOME - location of maven2's installed home dir
+@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
+@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
+@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
+@REM e.g. to debug Maven itself, use
+@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
+@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
+@REM ----------------------------------------------------------------------------
+
+@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
+@echo off
+@REM set title of command window
+title %0
+@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
+@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
+
+@REM set %HOME% to equivalent of $HOME
+if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
+
+@REM Execute a user defined script before this one
+if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
+@REM check for pre script, once with legacy .bat ending and once with .cmd ending
+if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
+if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
+:skipRcPre
+
+@setlocal
+
+set ERROR_CODE=0
+
+@REM To isolate internal variables from possible post scripts, we use another setlocal
+@setlocal
+
+@REM ==== START VALIDATION ====
+if not "%JAVA_HOME%" == "" goto OkJHome
+
+echo.
+echo Error: JAVA_HOME not found in your environment. >&2
+echo Please set the JAVA_HOME variable in your environment to match the >&2
+echo location of your Java installation. >&2
+echo.
+goto error
+
+:OkJHome
+if exist "%JAVA_HOME%\bin\java.exe" goto init
+
+echo.
+echo Error: JAVA_HOME is set to an invalid directory. >&2
+echo JAVA_HOME = "%JAVA_HOME%" >&2
+echo Please set the JAVA_HOME variable in your environment to match the >&2
+echo location of your Java installation. >&2
+echo.
+goto error
+
+@REM ==== END VALIDATION ====
+
+:init
+
+@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
+@REM Fallback to current working directory if not found.
+
+set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
+IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
+
+set EXEC_DIR=%CD%
+set WDIR=%EXEC_DIR%
+:findBaseDir
+IF EXIST "%WDIR%"\.mvn goto baseDirFound
+cd ..
+IF "%WDIR%"=="%CD%" goto baseDirNotFound
+set WDIR=%CD%
+goto findBaseDir
+
+:baseDirFound
+set MAVEN_PROJECTBASEDIR=%WDIR%
+cd "%EXEC_DIR%"
+goto endDetectBaseDir
+
+:baseDirNotFound
+set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
+cd "%EXEC_DIR%"
+
+:endDetectBaseDir
+
+IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
+
+@setlocal EnableExtensions EnableDelayedExpansion
+for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
+@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
+
+:endReadAdditionalConfig
+
+SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
+set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
+set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
+
+set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
+
+FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
+ IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
+)
+
+@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
+@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
+if exist %WRAPPER_JAR% (
+ if "%MVNW_VERBOSE%" == "true" (
+ echo Found %WRAPPER_JAR%
+ )
+) else (
+ if not "%MVNW_REPOURL%" == "" (
+ SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
+ )
+ if "%MVNW_VERBOSE%" == "true" (
+ echo Couldn't find %WRAPPER_JAR%, downloading it ...
+ echo Downloading from: %DOWNLOAD_URL%
+ )
+
+ powershell -Command "&{"^
+ "$webclient = new-object System.Net.WebClient;"^
+ "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
+ "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
+ "}"^
+ "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
+ "}"
+ if "%MVNW_VERBOSE%" == "true" (
+ echo Finished downloading %WRAPPER_JAR%
+ )
+)
+@REM End of extension
+
+@REM Provide a "standardized" way to retrieve the CLI args that will
+@REM work with both Windows and non-Windows executions.
+set MAVEN_CMD_LINE_ARGS=%*
+
+%MAVEN_JAVA_EXE% ^
+ %JVM_CONFIG_MAVEN_PROPS% ^
+ %MAVEN_OPTS% ^
+ %MAVEN_DEBUG_OPTS% ^
+ -classpath %WRAPPER_JAR% ^
+ "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
+ %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
+if ERRORLEVEL 1 goto error
+goto end
+
+:error
+set ERROR_CODE=1
+
+:end
+@endlocal & set ERROR_CODE=%ERROR_CODE%
+
+if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
+@REM check for post script, once with legacy .bat ending and once with .cmd ending
+if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
+if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
+:skipRcPost
+
+@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
+if "%MAVEN_BATCH_PAUSE%"=="on" pause
+
+if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
+
+cmd /C exit /B %ERROR_CODE%
diff --git a/catalog-service/pom.xml b/catalog-service/pom.xml
new file mode 100644
index 0000000..d37f97b
--- /dev/null
+++ b/catalog-service/pom.xml
@@ -0,0 +1,90 @@
+
+
+ 4.0.0
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 2.7.12
+
+
+ com.example
+ catalog-service
+ 0.0.1-SNAPSHOT
+ catalog-service
+ catalog-service
+
+ 11
+ 2021.0.7
+
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ org.springframework.cloud
+ spring-cloud-starter-netflix-eureka-client
+
+
+
+ org.springframework.boot
+ spring-boot-devtools
+ runtime
+ true
+
+
+ com.h2database
+ h2
+ 1.3.176
+
+
+ org.projectlombok
+ lombok
+ true
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ org.modelmapper
+ modelmapper
+ 2.3.8
+
+
+
+
+
+ org.springframework.cloud
+ spring-cloud-dependencies
+ ${spring-cloud.version}
+ pom
+ import
+
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ org.projectlombok
+ lombok
+
+
+
+
+
+
+
+
diff --git a/catalog-service/src/main/java/com/example/catalogservice/CatalogServiceApplication.java b/catalog-service/src/main/java/com/example/catalogservice/CatalogServiceApplication.java
new file mode 100644
index 0000000..ab83a07
--- /dev/null
+++ b/catalog-service/src/main/java/com/example/catalogservice/CatalogServiceApplication.java
@@ -0,0 +1,13 @@
+package com.example.catalogservice;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class CatalogServiceApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(CatalogServiceApplication.class, args);
+ }
+
+}
diff --git a/catalog-service/src/main/java/com/example/catalogservice/controller/CatalogController.java b/catalog-service/src/main/java/com/example/catalogservice/controller/CatalogController.java
new file mode 100644
index 0000000..4ecfd8f
--- /dev/null
+++ b/catalog-service/src/main/java/com/example/catalogservice/controller/CatalogController.java
@@ -0,0 +1,45 @@
+package com.example.catalogservice.controller;
+
+import com.example.catalogservice.jpa.CatalogEntity;
+import com.example.catalogservice.service.CatalogService;
+import com.example.catalogservice.vo.ResponseCatalog;
+import org.modelmapper.ModelMapper;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.env.Environment;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RestController
+@RequestMapping("/catalog-service")
+public class CatalogController {
+ Environment env;//application.yml에서 필요한 환경변수 가져오려면 필요함!
+ CatalogService catalogService;
+ @Autowired
+ public CatalogController(Environment env, CatalogService catalogService) {
+ this.env = env;
+ this.catalogService = catalogService;
+ }
+
+ @GetMapping("/health_check")
+ public String status(){
+ return String.format("It's Working in Catalog Service on PORT %s", env.getProperty("local.server.port"));
+ }
+
+ @GetMapping("/catalogs")
+ public ResponseEntity> getCatalogs(){
+ Iterable userList = catalogService.getAllCatalogs();
+
+ List result= new ArrayList<>();
+ userList.forEach(v -> {
+ result.add((new ModelMapper().map(v,ResponseCatalog.class )));
+ });
+ return ResponseEntity.status(HttpStatus.OK).body(result);
+ }
+
+}
diff --git a/catalog-service/src/main/java/com/example/catalogservice/dto/CatalogDto.java b/catalog-service/src/main/java/com/example/catalogservice/dto/CatalogDto.java
new file mode 100644
index 0000000..eda8e74
--- /dev/null
+++ b/catalog-service/src/main/java/com/example/catalogservice/dto/CatalogDto.java
@@ -0,0 +1,16 @@
+package com.example.catalogservice.dto;
+
+import lombok.Data;
+
+import java.io.Serializable;
+
+@Data
+public class CatalogDto implements Serializable {
+ private String productId;
+ private Integer qty;
+ private Integer unitPrice;
+ private Integer totalPrice;
+
+ private String orderId;
+ private String userId;
+}
diff --git a/catalog-service/src/main/java/com/example/catalogservice/jpa/CatalogEntity.java b/catalog-service/src/main/java/com/example/catalogservice/jpa/CatalogEntity.java
new file mode 100644
index 0000000..ae06c0e
--- /dev/null
+++ b/catalog-service/src/main/java/com/example/catalogservice/jpa/CatalogEntity.java
@@ -0,0 +1,28 @@
+package com.example.catalogservice.jpa;
+
+import lombok.Data;
+import org.hibernate.annotations.ColumnDefault;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.util.Date;
+
+@Data
+@Entity
+@Table(name = "catalog")
+public class CatalogEntity implements Serializable {
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long id;
+ @Column(nullable = false, length = 120, unique = true)
+ private String productId;
+ @Column(nullable = false)
+ private String productName;
+ @Column(nullable = false)
+ private Integer stock;
+ @Column(nullable = false)
+ private Integer unitPrice;
+ @Column(nullable = false, updatable = false, insertable = false)
+ @ColumnDefault(value = "CURRENT_TIMESTAMP")
+ private Date createdAt;
+}
diff --git a/catalog-service/src/main/java/com/example/catalogservice/jpa/CatalogRepository.java b/catalog-service/src/main/java/com/example/catalogservice/jpa/CatalogRepository.java
new file mode 100644
index 0000000..9da8349
--- /dev/null
+++ b/catalog-service/src/main/java/com/example/catalogservice/jpa/CatalogRepository.java
@@ -0,0 +1,7 @@
+package com.example.catalogservice.jpa;
+
+import org.springframework.data.repository.CrudRepository;
+
+public interface CatalogRepository extends CrudRepository {
+ CatalogEntity findByProductId(String productId);
+}
diff --git a/catalog-service/src/main/java/com/example/catalogservice/service/CatalogService.java b/catalog-service/src/main/java/com/example/catalogservice/service/CatalogService.java
new file mode 100644
index 0000000..fd0a631
--- /dev/null
+++ b/catalog-service/src/main/java/com/example/catalogservice/service/CatalogService.java
@@ -0,0 +1,7 @@
+package com.example.catalogservice.service;
+
+import com.example.catalogservice.jpa.CatalogEntity;
+
+public interface CatalogService {
+ Iterable getAllCatalogs();
+}
diff --git a/catalog-service/src/main/java/com/example/catalogservice/service/CatalogServiceImpl.java b/catalog-service/src/main/java/com/example/catalogservice/service/CatalogServiceImpl.java
new file mode 100644
index 0000000..81b80c3
--- /dev/null
+++ b/catalog-service/src/main/java/com/example/catalogservice/service/CatalogServiceImpl.java
@@ -0,0 +1,25 @@
+package com.example.catalogservice.service;
+
+import com.example.catalogservice.jpa.CatalogEntity;
+import com.example.catalogservice.jpa.CatalogRepository;
+import lombok.Data;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+@Data
+@Slf4j
+@Service
+public class CatalogServiceImpl implements CatalogService{
+ CatalogRepository catalogRepository;
+ @Autowired
+ public CatalogServiceImpl(CatalogRepository catalogRepository) {
+ this.catalogRepository = catalogRepository;
+ }
+
+ @Override
+ public Iterable getAllCatalogs() {
+ return catalogRepository.findAll();
+ }
+
+}
diff --git a/catalog-service/src/main/java/com/example/catalogservice/vo/ResponseCatalog.java b/catalog-service/src/main/java/com/example/catalogservice/vo/ResponseCatalog.java
new file mode 100644
index 0000000..a98fe7d
--- /dev/null
+++ b/catalog-service/src/main/java/com/example/catalogservice/vo/ResponseCatalog.java
@@ -0,0 +1,16 @@
+package com.example.catalogservice.vo;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import lombok.Data;
+
+import java.util.Date;
+
+@Data
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class ResponseCatalog {
+ private String productId;
+ private String productName;
+ private Integer unitPrice;
+ private Integer stock;
+ private Date createdAt;
+}
diff --git a/catalog-service/src/main/resources/application.yml b/catalog-service/src/main/resources/application.yml
new file mode 100644
index 0000000..5eb18c5
--- /dev/null
+++ b/catalog-service/src/main/resources/application.yml
@@ -0,0 +1,38 @@
+server:
+ # ??? ??? ?????? ?
+ port: 0
+
+spring:
+ application:
+ name: catalog-service
+ h2:
+ console:
+ enabled: true
+ settings:
+ web-allow-others: true
+ path: /h2-console
+ jpa:
+ hibernate:
+ ddl-auto: create-drop
+ #????????? ???? sql??? ??? ??? spring ??? ? ?? ??? ??? ???? insert
+ show-sql: true
+ generate-ddl: true
+ database: h2
+ defer-datasource-initialization: true
+ datasource:
+ driver-class-name: org.h2.Driver
+ url: jdbc:h2:mem:testdb
+# username: sa
+
+eureka:
+ client:
+ register-with-eureka: true
+ fetch-registry: true
+ service-url:
+ defaultZone: http://127.0.0.1:8761/eureka
+ instance:
+ instance-id: ${spring.application.name}:${spring.application.instance_id:${random.value}}
+
+logging:
+ level:
+ com.example.catalogservice: DEBUG
\ No newline at end of file
diff --git a/catalog-service/src/main/resources/data.sql b/catalog-service/src/main/resources/data.sql
new file mode 100644
index 0000000..c6828b5
--- /dev/null
+++ b/catalog-service/src/main/resources/data.sql
@@ -0,0 +1,6 @@
+insert into catalog(product_id, product_name, stock, unit_price)
+ values ('CATALOG-001','Berlin', 100,1500);
+insert into catalog(product_id, product_name, stock, unit_price)
+ values ('CATALOG-002','Tokyo', 110,1000);
+insert into catalog(product_id, product_name, stock, unit_price)
+ values ('CATALOG-003','Stockholm', 120,2000);
\ No newline at end of file
diff --git a/catalog-service/src/test/java/com/example/catalogservice/CatalogServiceApplicationTests.java b/catalog-service/src/test/java/com/example/catalogservice/CatalogServiceApplicationTests.java
new file mode 100644
index 0000000..a5fb6d4
--- /dev/null
+++ b/catalog-service/src/test/java/com/example/catalogservice/CatalogServiceApplicationTests.java
@@ -0,0 +1,13 @@
+package com.example.catalogservice;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+
+@SpringBootTest
+class CatalogServiceApplicationTests {
+
+ @Test
+ void contextLoads() {
+ }
+
+}
diff --git a/order-service/.mvn/wrapper/maven-wrapper.jar b/order-service/.mvn/wrapper/maven-wrapper.jar
new file mode 100644
index 0000000..bf82ff0
Binary files /dev/null and b/order-service/.mvn/wrapper/maven-wrapper.jar differ
diff --git a/order-service/.mvn/wrapper/maven-wrapper.properties b/order-service/.mvn/wrapper/maven-wrapper.properties
new file mode 100644
index 0000000..ca5ab4b
--- /dev/null
+++ b/order-service/.mvn/wrapper/maven-wrapper.properties
@@ -0,0 +1,18 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.7/apache-maven-3.8.7-bin.zip
+wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar
diff --git a/order-service/mvnw b/order-service/mvnw
new file mode 100644
index 0000000..8a8fb22
--- /dev/null
+++ b/order-service/mvnw
@@ -0,0 +1,316 @@
+#!/bin/sh
+# ----------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+# ----------------------------------------------------------------------------
+
+# ----------------------------------------------------------------------------
+# Maven Start Up Batch script
+#
+# Required ENV vars:
+# ------------------
+# JAVA_HOME - location of a JDK home dir
+#
+# Optional ENV vars
+# -----------------
+# M2_HOME - location of maven2's installed home dir
+# MAVEN_OPTS - parameters passed to the Java VM when running Maven
+# e.g. to debug Maven itself, use
+# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
+# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
+# ----------------------------------------------------------------------------
+
+if [ -z "$MAVEN_SKIP_RC" ] ; then
+
+ if [ -f /usr/local/etc/mavenrc ] ; then
+ . /usr/local/etc/mavenrc
+ fi
+
+ if [ -f /etc/mavenrc ] ; then
+ . /etc/mavenrc
+ fi
+
+ if [ -f "$HOME/.mavenrc" ] ; then
+ . "$HOME/.mavenrc"
+ fi
+
+fi
+
+# OS specific support. $var _must_ be set to either true or false.
+cygwin=false;
+darwin=false;
+mingw=false
+case "`uname`" in
+ CYGWIN*) cygwin=true ;;
+ MINGW*) mingw=true;;
+ Darwin*) darwin=true
+ # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
+ # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
+ if [ -z "$JAVA_HOME" ]; then
+ if [ -x "/usr/libexec/java_home" ]; then
+ export JAVA_HOME="`/usr/libexec/java_home`"
+ else
+ export JAVA_HOME="/Library/Java/Home"
+ fi
+ fi
+ ;;
+esac
+
+if [ -z "$JAVA_HOME" ] ; then
+ if [ -r /etc/gentoo-release ] ; then
+ JAVA_HOME=`java-config --jre-home`
+ fi
+fi
+
+if [ -z "$M2_HOME" ] ; then
+ ## resolve links - $0 may be a link to maven's home
+ PRG="$0"
+
+ # need this for relative symlinks
+ while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG="`dirname "$PRG"`/$link"
+ fi
+ done
+
+ saveddir=`pwd`
+
+ M2_HOME=`dirname "$PRG"`/..
+
+ # make it fully qualified
+ M2_HOME=`cd "$M2_HOME" && pwd`
+
+ cd "$saveddir"
+ # echo Using m2 at $M2_HOME
+fi
+
+# For Cygwin, ensure paths are in UNIX format before anything is touched
+if $cygwin ; then
+ [ -n "$M2_HOME" ] &&
+ M2_HOME=`cygpath --unix "$M2_HOME"`
+ [ -n "$JAVA_HOME" ] &&
+ JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
+ [ -n "$CLASSPATH" ] &&
+ CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
+fi
+
+# For Mingw, ensure paths are in UNIX format before anything is touched
+if $mingw ; then
+ [ -n "$M2_HOME" ] &&
+ M2_HOME="`(cd "$M2_HOME"; pwd)`"
+ [ -n "$JAVA_HOME" ] &&
+ JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
+fi
+
+if [ -z "$JAVA_HOME" ]; then
+ javaExecutable="`which javac`"
+ if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
+ # readlink(1) is not available as standard on Solaris 10.
+ readLink=`which readlink`
+ if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
+ if $darwin ; then
+ javaHome="`dirname \"$javaExecutable\"`"
+ javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
+ else
+ javaExecutable="`readlink -f \"$javaExecutable\"`"
+ fi
+ javaHome="`dirname \"$javaExecutable\"`"
+ javaHome=`expr "$javaHome" : '\(.*\)/bin'`
+ JAVA_HOME="$javaHome"
+ export JAVA_HOME
+ fi
+ fi
+fi
+
+if [ -z "$JAVACMD" ] ; then
+ if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ else
+ JAVACMD="`\\unset -f command; \\command -v java`"
+ fi
+fi
+
+if [ ! -x "$JAVACMD" ] ; then
+ echo "Error: JAVA_HOME is not defined correctly." >&2
+ echo " We cannot execute $JAVACMD" >&2
+ exit 1
+fi
+
+if [ -z "$JAVA_HOME" ] ; then
+ echo "Warning: JAVA_HOME environment variable is not set."
+fi
+
+CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
+
+# traverses directory structure from process work directory to filesystem root
+# first directory with .mvn subdirectory is considered project base directory
+find_maven_basedir() {
+
+ if [ -z "$1" ]
+ then
+ echo "Path not specified to find_maven_basedir"
+ return 1
+ fi
+
+ basedir="$1"
+ wdir="$1"
+ while [ "$wdir" != '/' ] ; do
+ if [ -d "$wdir"/.mvn ] ; then
+ basedir=$wdir
+ break
+ fi
+ # workaround for JBEAP-8937 (on Solaris 10/Sparc)
+ if [ -d "${wdir}" ]; then
+ wdir=`cd "$wdir/.."; pwd`
+ fi
+ # end of workaround
+ done
+ echo "${basedir}"
+}
+
+# concatenates all lines of a file
+concat_lines() {
+ if [ -f "$1" ]; then
+ echo "$(tr -s '\n' ' ' < "$1")"
+ fi
+}
+
+BASE_DIR=`find_maven_basedir "$(pwd)"`
+if [ -z "$BASE_DIR" ]; then
+ exit 1;
+fi
+
+##########################################################################################
+# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
+# This allows using the maven wrapper in projects that prohibit checking in binary data.
+##########################################################################################
+if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Found .mvn/wrapper/maven-wrapper.jar"
+ fi
+else
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
+ fi
+ if [ -n "$MVNW_REPOURL" ]; then
+ jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
+ else
+ jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
+ fi
+ while IFS="=" read key value; do
+ case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
+ esac
+ done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Downloading from: $jarUrl"
+ fi
+ wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
+ if $cygwin; then
+ wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
+ fi
+
+ if command -v wget > /dev/null; then
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Found wget ... using wget"
+ fi
+ if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
+ wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
+ else
+ wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
+ fi
+ elif command -v curl > /dev/null; then
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Found curl ... using curl"
+ fi
+ if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
+ curl -o "$wrapperJarPath" "$jarUrl" -f
+ else
+ curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
+ fi
+
+ else
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo "Falling back to using Java to download"
+ fi
+ javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
+ # For Cygwin, switch paths to Windows format before running javac
+ if $cygwin; then
+ javaClass=`cygpath --path --windows "$javaClass"`
+ fi
+ if [ -e "$javaClass" ]; then
+ if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo " - Compiling MavenWrapperDownloader.java ..."
+ fi
+ # Compiling the Java class
+ ("$JAVA_HOME/bin/javac" "$javaClass")
+ fi
+ if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
+ # Running the downloader
+ if [ "$MVNW_VERBOSE" = true ]; then
+ echo " - Running MavenWrapperDownloader.java ..."
+ fi
+ ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
+ fi
+ fi
+ fi
+fi
+##########################################################################################
+# End of extension
+##########################################################################################
+
+export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
+if [ "$MVNW_VERBOSE" = true ]; then
+ echo $MAVEN_PROJECTBASEDIR
+fi
+MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin; then
+ [ -n "$M2_HOME" ] &&
+ M2_HOME=`cygpath --path --windows "$M2_HOME"`
+ [ -n "$JAVA_HOME" ] &&
+ JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
+ [ -n "$CLASSPATH" ] &&
+ CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
+ [ -n "$MAVEN_PROJECTBASEDIR" ] &&
+ MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
+fi
+
+# Provide a "standardized" way to retrieve the CLI args that will
+# work with both Windows and non-Windows executions.
+MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
+export MAVEN_CMD_LINE_ARGS
+
+WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
+
+exec "$JAVACMD" \
+ $MAVEN_OPTS \
+ $MAVEN_DEBUG_OPTS \
+ -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
+ "-Dmaven.home=${M2_HOME}" \
+ "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
+ ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
diff --git a/order-service/mvnw.cmd b/order-service/mvnw.cmd
new file mode 100644
index 0000000..1d8ab01
--- /dev/null
+++ b/order-service/mvnw.cmd
@@ -0,0 +1,188 @@
+@REM ----------------------------------------------------------------------------
+@REM Licensed to the Apache Software Foundation (ASF) under one
+@REM or more contributor license agreements. See the NOTICE file
+@REM distributed with this work for additional information
+@REM regarding copyright ownership. The ASF licenses this file
+@REM to you under the Apache License, Version 2.0 (the
+@REM "License"); you may not use this file except in compliance
+@REM with the License. You may obtain a copy of the License at
+@REM
+@REM https://www.apache.org/licenses/LICENSE-2.0
+@REM
+@REM Unless required by applicable law or agreed to in writing,
+@REM software distributed under the License is distributed on an
+@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+@REM KIND, either express or implied. See the License for the
+@REM specific language governing permissions and limitations
+@REM under the License.
+@REM ----------------------------------------------------------------------------
+
+@REM ----------------------------------------------------------------------------
+@REM Maven Start Up Batch script
+@REM
+@REM Required ENV vars:
+@REM JAVA_HOME - location of a JDK home dir
+@REM
+@REM Optional ENV vars
+@REM M2_HOME - location of maven2's installed home dir
+@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
+@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
+@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
+@REM e.g. to debug Maven itself, use
+@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
+@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
+@REM ----------------------------------------------------------------------------
+
+@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
+@echo off
+@REM set title of command window
+title %0
+@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
+@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
+
+@REM set %HOME% to equivalent of $HOME
+if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
+
+@REM Execute a user defined script before this one
+if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
+@REM check for pre script, once with legacy .bat ending and once with .cmd ending
+if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
+if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
+:skipRcPre
+
+@setlocal
+
+set ERROR_CODE=0
+
+@REM To isolate internal variables from possible post scripts, we use another setlocal
+@setlocal
+
+@REM ==== START VALIDATION ====
+if not "%JAVA_HOME%" == "" goto OkJHome
+
+echo.
+echo Error: JAVA_HOME not found in your environment. >&2
+echo Please set the JAVA_HOME variable in your environment to match the >&2
+echo location of your Java installation. >&2
+echo.
+goto error
+
+:OkJHome
+if exist "%JAVA_HOME%\bin\java.exe" goto init
+
+echo.
+echo Error: JAVA_HOME is set to an invalid directory. >&2
+echo JAVA_HOME = "%JAVA_HOME%" >&2
+echo Please set the JAVA_HOME variable in your environment to match the >&2
+echo location of your Java installation. >&2
+echo.
+goto error
+
+@REM ==== END VALIDATION ====
+
+:init
+
+@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
+@REM Fallback to current working directory if not found.
+
+set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
+IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
+
+set EXEC_DIR=%CD%
+set WDIR=%EXEC_DIR%
+:findBaseDir
+IF EXIST "%WDIR%"\.mvn goto baseDirFound
+cd ..
+IF "%WDIR%"=="%CD%" goto baseDirNotFound
+set WDIR=%CD%
+goto findBaseDir
+
+:baseDirFound
+set MAVEN_PROJECTBASEDIR=%WDIR%
+cd "%EXEC_DIR%"
+goto endDetectBaseDir
+
+:baseDirNotFound
+set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
+cd "%EXEC_DIR%"
+
+:endDetectBaseDir
+
+IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
+
+@setlocal EnableExtensions EnableDelayedExpansion
+for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
+@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
+
+:endReadAdditionalConfig
+
+SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
+set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
+set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
+
+set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
+
+FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
+ IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
+)
+
+@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
+@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
+if exist %WRAPPER_JAR% (
+ if "%MVNW_VERBOSE%" == "true" (
+ echo Found %WRAPPER_JAR%
+ )
+) else (
+ if not "%MVNW_REPOURL%" == "" (
+ SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
+ )
+ if "%MVNW_VERBOSE%" == "true" (
+ echo Couldn't find %WRAPPER_JAR%, downloading it ...
+ echo Downloading from: %DOWNLOAD_URL%
+ )
+
+ powershell -Command "&{"^
+ "$webclient = new-object System.Net.WebClient;"^
+ "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
+ "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
+ "}"^
+ "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
+ "}"
+ if "%MVNW_VERBOSE%" == "true" (
+ echo Finished downloading %WRAPPER_JAR%
+ )
+)
+@REM End of extension
+
+@REM Provide a "standardized" way to retrieve the CLI args that will
+@REM work with both Windows and non-Windows executions.
+set MAVEN_CMD_LINE_ARGS=%*
+
+%MAVEN_JAVA_EXE% ^
+ %JVM_CONFIG_MAVEN_PROPS% ^
+ %MAVEN_OPTS% ^
+ %MAVEN_DEBUG_OPTS% ^
+ -classpath %WRAPPER_JAR% ^
+ "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
+ %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
+if ERRORLEVEL 1 goto error
+goto end
+
+:error
+set ERROR_CODE=1
+
+:end
+@endlocal & set ERROR_CODE=%ERROR_CODE%
+
+if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
+@REM check for post script, once with legacy .bat ending and once with .cmd ending
+if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
+if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
+:skipRcPost
+
+@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
+if "%MAVEN_BATCH_PAUSE%"=="on" pause
+
+if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
+
+cmd /C exit /B %ERROR_CODE%
diff --git a/order-service/pom.xml b/order-service/pom.xml
new file mode 100644
index 0000000..e0f2d2d
--- /dev/null
+++ b/order-service/pom.xml
@@ -0,0 +1,91 @@
+
+
+ 4.0.0
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 2.7.12
+
+
+ com.example
+ order-service
+ 0.0.1-SNAPSHOT
+ order-service
+ order-service
+
+ 11
+ 2021.0.7
+
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ org.springframework.cloud
+ spring-cloud-starter-netflix-eureka-client
+
+
+
+ org.springframework.boot
+ spring-boot-devtools
+ runtime
+ true
+
+
+ com.h2database
+ h2
+ 1.3.176
+ runtime
+
+
+ org.modelmapper
+ modelmapper
+ 2.3.8
+
+
+ org.projectlombok
+ lombok
+ true
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+
+
+
+ org.springframework.cloud
+ spring-cloud-dependencies
+ ${spring-cloud.version}
+ pom
+ import
+
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ org.projectlombok
+ lombok
+
+
+
+
+
+
+
+
diff --git a/order-service/src/main/java/com/example/orderservice/OrderServiceApplication.java b/order-service/src/main/java/com/example/orderservice/OrderServiceApplication.java
new file mode 100644
index 0000000..860df88
--- /dev/null
+++ b/order-service/src/main/java/com/example/orderservice/OrderServiceApplication.java
@@ -0,0 +1,13 @@
+package com.example.orderservice;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class OrderServiceApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(OrderServiceApplication.class, args);
+ }
+
+}
diff --git a/order-service/src/main/java/com/example/orderservice/controller/OrderController.java b/order-service/src/main/java/com/example/orderservice/controller/OrderController.java
new file mode 100644
index 0000000..be14a96
--- /dev/null
+++ b/order-service/src/main/java/com/example/orderservice/controller/OrderController.java
@@ -0,0 +1,62 @@
+package com.example.orderservice.controller;
+
+import com.example.orderservice.dto.OrderDto;
+import com.example.orderservice.jpa.OrderEntity;
+import com.example.orderservice.service.OrderService;
+import com.example.orderservice.vo.ResponseOrder;
+import com.example.orderservice.vo.ResquestOrder;
+import org.hibernate.criterion.Order;
+import org.modelmapper.ModelMapper;
+import org.modelmapper.convention.MatchingStrategies;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.env.Environment;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RestController
+@RequestMapping("/order-service")
+public class OrderController {
+ Environment env;
+ OrderService orderService;
+ @Autowired
+ public OrderController(Environment env, OrderService orderService) {
+ this.env = env;
+ this.orderService = orderService;
+ }
+ @GetMapping("/health_check")
+ public String status(){
+ return String.format("It's Working in Order Service on PORT %s", env.getProperty("local.server.port"));
+ }
+ @PostMapping("/{userId}/orders")
+ public ResponseEntity> createOrder(@PathVariable("userId") String userId,
+ @RequestBody ResquestOrder orderDetails){
+ ModelMapper mapper= new ModelMapper();
+ mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
+
+ OrderDto orderDto= mapper.map(orderDetails, OrderDto.class);
+ orderDto.setUserId(userId);
+ OrderDto createOrder=orderService.createOrder(orderDto);
+
+ ResponseOrder responseOrder= mapper.map(orderDto,ResponseOrder.class);
+
+ return ResponseEntity.status(HttpStatus.CREATED).body(responseOrder);
+ }
+
+ @GetMapping("/{userId}/orders")
+ public ResponseEntity> getOrders(@PathVariable("userId") String userId,
+ @RequestBody ResquestOrder orderDetails){
+ Iterable orderList=orderService.getOrdersByUserId(userId);
+
+ List result = new ArrayList<>();
+ orderList.forEach(v->{
+ result.add(new ModelMapper().map(v,ResponseOrder.class));
+ });
+
+ return ResponseEntity.status(HttpStatus.OK).body(result);
+ }
+}
diff --git a/order-service/src/main/java/com/example/orderservice/dto/OrderDto.java b/order-service/src/main/java/com/example/orderservice/dto/OrderDto.java
new file mode 100644
index 0000000..b34a70e
--- /dev/null
+++ b/order-service/src/main/java/com/example/orderservice/dto/OrderDto.java
@@ -0,0 +1,16 @@
+package com.example.orderservice.dto;
+
+import lombok.Data;
+
+import java.io.Serializable;
+
+@Data
+public class OrderDto implements Serializable {
+ private String productId;
+ private Integer qty;
+ private Integer unitPrice;
+ private Integer totalPrice;
+
+ private String orderId;
+ private String userId;
+}
diff --git a/order-service/src/main/java/com/example/orderservice/jpa/OrderEntity.java b/order-service/src/main/java/com/example/orderservice/jpa/OrderEntity.java
new file mode 100644
index 0000000..6c8ece9
--- /dev/null
+++ b/order-service/src/main/java/com/example/orderservice/jpa/OrderEntity.java
@@ -0,0 +1,35 @@
+package com.example.orderservice.jpa;
+
+import lombok.Data;
+import org.hibernate.annotations.ColumnDefault;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.util.Date;
+
+@Data
+@Entity
+@Table(name = "orders")
+public class OrderEntity implements Serializable {
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long id;
+ @Column(nullable = false, length = 120, unique = true)
+ private String productId;
+ @Column(nullable = false)
+ private Integer qty;
+ @Column(nullable = false)
+ private Integer unitPrice;
+ @Column(nullable = false)
+ private Integer totalPrice;
+
+ @Column(nullable = false)
+ private String userId;
+ @Column(nullable = false, unique = true)
+ private String orderId;
+
+
+ @Column(nullable = false, updatable = false, insertable = false)
+ @ColumnDefault(value = "CURRENT_TIMESTAMP")
+ private Date createdAt;
+}
diff --git a/order-service/src/main/java/com/example/orderservice/jpa/OrderRepository.java b/order-service/src/main/java/com/example/orderservice/jpa/OrderRepository.java
new file mode 100644
index 0000000..57d485e
--- /dev/null
+++ b/order-service/src/main/java/com/example/orderservice/jpa/OrderRepository.java
@@ -0,0 +1,9 @@
+package com.example.orderservice.jpa;
+
+import org.aspectj.weaver.ast.Or;
+import org.springframework.data.repository.CrudRepository;
+
+public interface OrderRepository extends CrudRepository {
+ OrderEntity findByOrderId(String orderId);
+ Iterable findByUserId(String userId);
+}
diff --git a/order-service/src/main/java/com/example/orderservice/service/OrderService.java b/order-service/src/main/java/com/example/orderservice/service/OrderService.java
new file mode 100644
index 0000000..8d9e0cd
--- /dev/null
+++ b/order-service/src/main/java/com/example/orderservice/service/OrderService.java
@@ -0,0 +1,10 @@
+package com.example.orderservice.service;
+
+import com.example.orderservice.dto.OrderDto;
+import com.example.orderservice.jpa.OrderEntity;
+
+public interface OrderService {
+ OrderDto createOrder(OrderDto orderDetails);
+ OrderDto getOrderByOrderId(String orderId);
+ Iterable getOrdersByUserId(String userId);
+}
diff --git a/order-service/src/main/java/com/example/orderservice/service/OrderServiceImpl.java b/order-service/src/main/java/com/example/orderservice/service/OrderServiceImpl.java
new file mode 100644
index 0000000..d699e48
--- /dev/null
+++ b/order-service/src/main/java/com/example/orderservice/service/OrderServiceImpl.java
@@ -0,0 +1,51 @@
+package com.example.orderservice.service;
+
+import com.example.orderservice.dto.OrderDto;
+import com.example.orderservice.jpa.OrderEntity;
+import com.example.orderservice.jpa.OrderRepository;
+import lombok.extern.slf4j.Slf4j;
+import org.modelmapper.ModelMapper;
+import org.modelmapper.convention.MatchingStrategies;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.util.UUID;
+
+@Service
+@Slf4j
+public class OrderServiceImpl implements OrderService{
+ OrderRepository orderRepository;
+
+ @Autowired
+ public OrderServiceImpl(OrderRepository orderRepository) {
+ this.orderRepository = orderRepository;
+ }
+
+ @Override
+ public OrderDto createOrder(OrderDto orderDto) {
+ orderDto.setOrderId(UUID.randomUUID().toString());
+ orderDto.setTotalPrice(orderDto.getQty()* orderDto.getUnitPrice());
+
+ ModelMapper mapper= new ModelMapper();
+ mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
+ OrderEntity userEntity = mapper.map(orderDto, OrderEntity.class);
+
+ orderRepository.save(userEntity);
+
+ OrderDto returnUserDto=mapper.map(userEntity,OrderDto.class);
+
+ return returnUserDto;
+ }
+
+ @Override
+ public OrderDto getOrderByOrderId(String orderId) {
+ OrderEntity orderEntity= orderRepository.findByOrderId(orderId);
+ OrderDto orderDto= new ModelMapper().map(orderEntity,OrderDto.class);
+ return orderDto;
+ }
+
+ @Override
+ public Iterable getOrdersByUserId(String userId) {
+ return orderRepository.findByUserId(userId);
+ }
+}
diff --git a/order-service/src/main/java/com/example/orderservice/vo/ResponseOrder.java b/order-service/src/main/java/com/example/orderservice/vo/ResponseOrder.java
new file mode 100644
index 0000000..decc162
--- /dev/null
+++ b/order-service/src/main/java/com/example/orderservice/vo/ResponseOrder.java
@@ -0,0 +1,18 @@
+package com.example.orderservice.vo;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import lombok.Data;
+
+import java.util.Date;
+
+@Data
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class ResponseOrder {
+ private String productId;
+ private String qty;
+ private Integer unitPrice;
+ private Integer totalPrice;
+ private Date createdAt;
+
+ private String orderId;
+}
diff --git a/order-service/src/main/java/com/example/orderservice/vo/ResquestOrder.java b/order-service/src/main/java/com/example/orderservice/vo/ResquestOrder.java
new file mode 100644
index 0000000..2518f10
--- /dev/null
+++ b/order-service/src/main/java/com/example/orderservice/vo/ResquestOrder.java
@@ -0,0 +1,10 @@
+package com.example.orderservice.vo;
+
+import lombok.Data;
+
+@Data
+public class ResquestOrder {
+ private String productId;
+ private Integer qty;
+ private Integer unitPrice;
+}
diff --git a/order-service/src/main/resources/application.yml b/order-service/src/main/resources/application.yml
new file mode 100644
index 0000000..b68fc26
--- /dev/null
+++ b/order-service/src/main/resources/application.yml
@@ -0,0 +1,33 @@
+server:
+ # ??? ??? ?????? ?
+ port: 0
+
+spring:
+ application:
+ name: order-service
+ h2:
+ console:
+ enabled: true
+ settings:
+ web-allow-others: true
+ path: /h2-console
+ jpa:
+ hibernate:
+ ddl-auto: update
+ datasource:
+ driver-class-name: org.h2.Driver
+ url: jdbc:h2:mem:testdb
+# username: sa
+
+eureka:
+ client:
+ register-with-eureka: true
+ fetch-registry: true
+ service-url:
+ defaultZone: http://127.0.0.1:8761/eureka
+ instance:
+ instance-id: ${spring.application.name}:${spring.application.instance_id:${random.value}}
+
+logging:
+ level:
+ com.example.orderservice: DEBUG
\ No newline at end of file
diff --git a/order-service/src/test/java/com/example/orderservice/OrderServiceApplicationTests.java b/order-service/src/test/java/com/example/orderservice/OrderServiceApplicationTests.java
new file mode 100644
index 0000000..c706cba
--- /dev/null
+++ b/order-service/src/test/java/com/example/orderservice/OrderServiceApplicationTests.java
@@ -0,0 +1,13 @@
+package com.example.orderservice;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+
+@SpringBootTest
+class OrderServiceApplicationTests {
+
+ @Test
+ void contextLoads() {
+ }
+
+}
diff --git a/user-service/pom.xml b/user-service/pom.xml
index 8fbbf11..04840e0 100644
--- a/user-service/pom.xml
+++ b/user-service/pom.xml
@@ -67,6 +67,11 @@
org.springframework.boot
spring-boot-starter-security
+
+ io.jsonwebtoken
+ jjwt
+ 0.9.1
+
diff --git a/user-service/src/main/java/com/example/userservice/UserServiceApplication.java b/user-service/src/main/java/com/example/userservice/UserServiceApplication.java
index da4a6f9..8bb579c 100644
--- a/user-service/src/main/java/com/example/userservice/UserServiceApplication.java
+++ b/user-service/src/main/java/com/example/userservice/UserServiceApplication.java
@@ -9,7 +9,7 @@
@SpringBootApplication
@EnableDiscoveryClient
public class UserServiceApplication {
-
+//로그인시 가장 먼저 수행
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
diff --git a/user-service/src/main/java/com/example/userservice/controller/UserController.java b/user-service/src/main/java/com/example/userservice/controller/UserController.java
index 8a84eb7..bcb951e 100644
--- a/user-service/src/main/java/com/example/userservice/controller/UserController.java
+++ b/user-service/src/main/java/com/example/userservice/controller/UserController.java
@@ -1,6 +1,7 @@
package com.example.userservice.controller;
import com.example.userservice.dto.UserDto;
+import com.example.userservice.jpa.UserEntity;
import com.example.userservice.service.UserService;
import com.example.userservice.vo.Greeting;
import com.example.userservice.vo.RequestUser;
@@ -13,6 +14,12 @@
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
+import javax.ws.rs.Path;
+import javax.ws.rs.core.Response;
+import java.lang.reflect.Array;
+import java.util.ArrayList;
+import java.util.List;
+
@RestController
@RequestMapping("/")
public class UserController {
@@ -27,10 +34,10 @@ public UserController(Environment env,UserService userService) {
this.env = env;
this.userService=userService;
}
-
+//로그인일는 함수를 만들지 않았지만 스프링 시큐리티르 사요하면 기본적으로 로그인은 기본 제공이 됨.
@GetMapping("/health_check")
public String status(){
- return "It's Working in User Service";
+ return String.format("It's Working in User Service on PORT %s", env.getProperty("local.server.port"));
}
@GetMapping("/welcome")
@@ -51,4 +58,22 @@ public ResponseEntity> createUser(@RequestBody RequestUser user){
return ResponseEntity.status(HttpStatus.CREATED).body(responseUser);
}
+ @GetMapping("/users")
+ public ResponseEntity> getUSers(){
+ Iterable userList = userService.getUserByAll();
+
+ List result= new ArrayList<>();
+ userList.forEach(v -> {
+ result.add((new ModelMapper().map(v,ResponseUser.class )));
+ });
+ return ResponseEntity.status(HttpStatus.OK).body(result);
+ }
+
+ @GetMapping("/users/{userId}")
+ public ResponseEntity> getUSers(@PathVariable("userId") String userId){
+ UserDto userDto= userService.getUserByUserId(userId);
+
+ ResponseUser returnValue= new ModelMapper().map(userDto, ResponseUser.class);
+ return ResponseEntity.status(HttpStatus.OK).body(returnValue);
+ }
}
diff --git a/user-service/src/main/java/com/example/userservice/dto/UserDto.java b/user-service/src/main/java/com/example/userservice/dto/UserDto.java
index e64178d..6df3a13 100644
--- a/user-service/src/main/java/com/example/userservice/dto/UserDto.java
+++ b/user-service/src/main/java/com/example/userservice/dto/UserDto.java
@@ -1,8 +1,10 @@
package com.example.userservice.dto;
+import com.example.userservice.vo.ResponseOrder;
import lombok.Data;
import java.util.Date;
+import java.util.List;
@Data
public class UserDto {
@@ -13,4 +15,6 @@ public class UserDto {
private Date createdAt;
private String encryptedPwd;
+ private List orders;
+
}
diff --git a/user-service/src/main/java/com/example/userservice/jpa/UserRepository.java b/user-service/src/main/java/com/example/userservice/jpa/UserRepository.java
index 0041478..0e0ff74 100644
--- a/user-service/src/main/java/com/example/userservice/jpa/UserRepository.java
+++ b/user-service/src/main/java/com/example/userservice/jpa/UserRepository.java
@@ -3,4 +3,7 @@
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository {
+ UserEntity findByUserId(String userId);
+
+ UserEntity findByEmail(String username);
}
diff --git a/user-service/src/main/java/com/example/userservice/security/AuthenticationFilter.java b/user-service/src/main/java/com/example/userservice/security/AuthenticationFilter.java
new file mode 100644
index 0000000..6b7fe02
--- /dev/null
+++ b/user-service/src/main/java/com/example/userservice/security/AuthenticationFilter.java
@@ -0,0 +1,82 @@
+package com.example.userservice.security;
+
+import com.example.userservice.dto.UserDto;
+import com.example.userservice.service.UserService;
+import com.example.userservice.vo.RequestLogin;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.SignatureAlgorithm;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.core.env.Environment;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.userdetails.User;
+import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Date;
+
+@Slf4j
+public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {
+ private UserService userService;
+ private Environment env;
+
+
+ public AuthenticationFilter(AuthenticationManager authenticationManager,
+ UserService userService,
+ Environment env) {
+ super.setAuthenticationManager(authenticationManager);
+ this.userService = userService;
+ this.env = env;
+ }
+
+ @Override
+ public Authentication attemptAuthentication(HttpServletRequest request,
+ HttpServletResponse response) throws AuthenticationException {
+ //로그인시 세번째로 수행되는 과정으로 이 함수가 사용자가 로그인을 하게되면 제일 먼저 시도되는 함수
+ try {
+ RequestLogin creds = new ObjectMapper().readValue(request.getInputStream(), RequestLogin.class);
+ //inputstream으로 받은 이유는 전달 시켜주려고 하는 로그인의 값은 POST 형태인데 그럼 requestParameter을 받을 수 없기 때문에,
+ // inputStream으로 받으면 수작업으로 어떤 데이터가 들어와쓴ㄴ지를 처리할 수 있음.
+
+ return getAuthenticationManager().authenticate(
+ new UsernamePasswordAuthenticationToken(
+ creds.getEmail(),
+ creds.getPassword(),
+ new ArrayList<>()
+ )
+ );
+ // 사용자가 입려한 아이디와 메일 등 입력값을 spring security에서 사용하기 위한 형태로 바꿔주기 위해
+ // UsernamePasswordAuthenticationToken값으로 변화시켜붐
+ // 이걸 AuthenticationManager의 authenticate에 넘기면 아이디와 패스워드를 비교하는 인증처리를 해주겠다
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ protected void successfulAuthentication(HttpServletRequest request,
+ HttpServletResponse response, FilterChain chain,
+ Authentication authResult) throws IOException, ServletException {
+ //로그인시 다섯번째로 수행
+
+ String userName= ((User)authResult.getPrincipal()).getUsername();
+ UserDto userDetail=userService.getUserDetailsByEmail(userName);
+
+ String token=Jwts.builder()
+ .setSubject(userDetail.getUserId())
+ .setExpiration(new Date(System.currentTimeMillis()+Long.parseLong(env.getProperty("token.expiration_time"))))
+ .signWith(SignatureAlgorithm.HS512,env.getProperty("token.secret"))
+ .compact();
+
+ response.addHeader("token",token);;
+ response.addHeader("userId",userDetail.getUserId());
+ }
+}
diff --git a/user-service/src/main/java/com/example/userservice/security/WebSecurity.java b/user-service/src/main/java/com/example/userservice/security/WebSecurity.java
index 76c93fb..af695cd 100644
--- a/user-service/src/main/java/com/example/userservice/security/WebSecurity.java
+++ b/user-service/src/main/java/com/example/userservice/security/WebSecurity.java
@@ -1,17 +1,59 @@
package com.example.userservice.security;
+import com.example.userservice.UserServiceApplication;
+import com.example.userservice.service.UserService;
import org.springframework.context.annotation.Configuration;
+import org.springframework.core.env.Environment;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
+
+import javax.servlet.Filter;
+
@Configuration
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
+ //로그인시 두번째로 여기 관련딘 클래스들이 메모리에 올라감
+ private UserService userService;
+ private BCryptPasswordEncoder bCryptPasswordEncoder;
+ private Environment env;
+
+ public WebSecurity(Environment env,UserService userService, BCryptPasswordEncoder bCryptPasswordEncoder){
+ this.env=env;
+ this.userService=userService;
+ this.bCryptPasswordEncoder=bCryptPasswordEncoder;
+ }
+
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
//users로 들어오는 경로에 대해서는 인증작업 없이 사용 가능
- http.authorizeHttpRequests().antMatchers("/users/**").permitAll();
+ //http.authorizeHttpRequests().antMatchers("/users/**").permitAll();
+ http.authorizeRequests().antMatchers("/error/**").permitAll()
+ .antMatchers("/**")
+ .access("hasIpAddress(\"127.0.0.1\") or hasIpAddress(\"192.168.35.151\") " +
+ "or hasIpAddress(\"172.29.0.1\") or hasIpAddress(\"172.25.32.1\") ")
+ .and()
+ .addFilter(getAuthenticaionFilter());
+
http.headers().frameOptions().disable();
}
+
+ private AuthenticationFilter getAuthenticaionFilter() throws Exception {
+ AuthenticationFilter authenticationFilter = new AuthenticationFilter(authenticationManager(),userService,env);
+ //위에서 생성자를 통해 만들었으니까 아래 authenticationManager는 따로 호출할 필요 없어서 주석
+// authenticationFilter.setAuthenticationManager(authenticationManager());
+
+ return authenticationFilter;
+ }
+
+ //select pwd from users where emil=?
+ //db_pwd(encrypted)== input_pwd(encrypted)
+ @Override
+ public void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder);
+ }
}
diff --git a/user-service/src/main/java/com/example/userservice/service/UserService.java b/user-service/src/main/java/com/example/userservice/service/UserService.java
index fd25047..2a29cd4 100644
--- a/user-service/src/main/java/com/example/userservice/service/UserService.java
+++ b/user-service/src/main/java/com/example/userservice/service/UserService.java
@@ -1,7 +1,13 @@
package com.example.userservice.service;
import com.example.userservice.dto.UserDto;
+import com.example.userservice.jpa.UserEntity;
+import org.springframework.security.core.userdetails.UserDetailsService;
-public interface UserService {
+public interface UserService extends UserDetailsService {
UserDto createUser(UserDto userDto);
+ UserDto getUserByUserId(String userId);
+ Iterable getUserByAll();
+
+ UserDto getUserDetailsByEmail(String userName);
}
diff --git a/user-service/src/main/java/com/example/userservice/service/UserServiceImpl.java b/user-service/src/main/java/com/example/userservice/service/UserServiceImpl.java
index 0596af8..192021e 100644
--- a/user-service/src/main/java/com/example/userservice/service/UserServiceImpl.java
+++ b/user-service/src/main/java/com/example/userservice/service/UserServiceImpl.java
@@ -3,13 +3,19 @@
import com.example.userservice.dto.UserDto;
import com.example.userservice.jpa.UserEntity;
import com.example.userservice.jpa.UserRepository;
+import com.example.userservice.vo.ResponseOrder;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
+import org.springframework.security.core.userdetails.User;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
+import java.util.ArrayList;
+import java.util.List;
import java.util.UUID;
@Service
@@ -36,4 +42,46 @@ public UserDto createUser(UserDto userDto){
UserDto returnUserDto=mapper.map(userEntity,UserDto.class);
return returnUserDto;
}
+
+ @Override
+ public UserDto getUserByUserId(String userId) {
+ UserEntity userEntity=userRepository.findByUserId(userId);
+
+ if(userEntity ==null) throw new UsernameNotFoundException("User not found");
+
+ UserDto userDto = new ModelMapper().map(userEntity, UserDto.class);
+
+ List orders = new ArrayList<>();
+ userDto.setOrders(orders);
+
+ return userDto;
+ }
+
+ @Override
+ public Iterable getUserByAll() {
+ return userRepository.findAll();
+ }
+
+ @Override
+ public UserDto getUserDetailsByEmail(String email) {
+ UserEntity userEntity=userRepository.findByEmail(email);
+ if(userEntity==null)
+ throw new UsernameNotFoundException(email);
+
+ UserDto userDto=new ModelMapper().map(userEntity,UserDto.class);
+ return userDto;
+ }
+
+ @Override
+ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
+ //로그인시 네번째로 수행.
+ UserEntity userEntity=userRepository.findByEmail(username);
+ if(userEntity==null){
+ throw new UsernameNotFoundException(username);
+ }
+
+ return new User(userEntity.getEmail(), userEntity.getEncryptedPwd(),
+ true, true,true,true,
+ new ArrayList<>());
+ }
}
diff --git a/user-service/src/main/java/com/example/userservice/vo/RequestLogin.java b/user-service/src/main/java/com/example/userservice/vo/RequestLogin.java
new file mode 100644
index 0000000..50b82fd
--- /dev/null
+++ b/user-service/src/main/java/com/example/userservice/vo/RequestLogin.java
@@ -0,0 +1,18 @@
+package com.example.userservice.vo;
+
+import lombok.Data;
+
+import javax.validation.constraints.NotNull;
+import javax.validation.constraints.Size;
+
+@Data
+public class RequestLogin {
+ @NotNull(message = "Email cannot be null")
+ @Size(message = "Email not be less than two characters", min = 2)
+ private String email;
+
+ @NotNull(message = "Password cannot be null")
+ @Size(message = "Password must be equals or greater than 8 characters", min = 8)
+ private String password;
+
+}
diff --git a/user-service/src/main/java/com/example/userservice/vo/ResponseOrder.java b/user-service/src/main/java/com/example/userservice/vo/ResponseOrder.java
new file mode 100644
index 0000000..401534a
--- /dev/null
+++ b/user-service/src/main/java/com/example/userservice/vo/ResponseOrder.java
@@ -0,0 +1,17 @@
+package com.example.userservice.vo;
+
+import lombok.Data;
+
+import java.util.Date;
+
+@Data
+public class ResponseOrder {
+ private String productId;
+ private Integer qty;
+ private Integer unitPrice;
+ private Integer totalPrice;
+ private Date createdAt;
+
+ private String orderId;
+
+}
diff --git a/user-service/src/main/java/com/example/userservice/vo/ResponseUser.java b/user-service/src/main/java/com/example/userservice/vo/ResponseUser.java
index 57c8849..8ffdce3 100644
--- a/user-service/src/main/java/com/example/userservice/vo/ResponseUser.java
+++ b/user-service/src/main/java/com/example/userservice/vo/ResponseUser.java
@@ -1,10 +1,17 @@
package com.example.userservice.vo;
+import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
+import java.util.List;
+
@Data
+@JsonInclude(JsonInclude.Include.NON_NULL)
public class ResponseUser {
private String email;
private String name;
private String userId;
+
+ private List orders;
+
}
diff --git a/user-service/src/main/resources/application.yml b/user-service/src/main/resources/application.yml
index 264ce3e..a2b1663 100644
--- a/user-service/src/main/resources/application.yml
+++ b/user-service/src/main/resources/application.yml
@@ -26,4 +26,13 @@ eureka:
instance-id: ${spring.application.name}:${spring.application.instance_id:${random.value}}
greeting:
- message: Welcome to the Simple E-commerce.
\ No newline at end of file
+ message: Welcome to the Simple E-commerce.
+
+logging:
+ level:
+ com.example.userservice: DEBUG
+
+token:
+# 60*60*24*1000 = 하루짜리 토큰
+ expiration_time: 86400000
+ secret: user_token
\ No newline at end of file