diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9392259 --- /dev/null +++ b/.gitignore @@ -0,0 +1,49 @@ +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +/build/ diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..01e6799 Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..cd0d451 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip diff --git a/README.md b/README.md new file mode 100644 index 0000000..277041a --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# hexagonal-architecture-structure-example diff --git a/mvnw b/mvnw new file mode 100755 index 0000000..5551fde --- /dev/null +++ b/mvnw @@ -0,0 +1,286 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + wget "$jarUrl" -O "$wrapperJarPath" + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + curl -o "$wrapperJarPath" "$jarUrl" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..e5cfb0a --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,161 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" +FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + echo Found %WRAPPER_JAR% +) else ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" + echo Finished downloading %WRAPPER_JAR% +) +@REM End of extension + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..d9d7269 --- /dev/null +++ b/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.2.RELEASE + + + girgin.ramazan + hexagonal-architecture-structure-example + 0.0.1-SNAPSHOT + hexagonal-architecture-structure-example + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/HexagonalArchitectureStructureExampleApplication.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/HexagonalArchitectureStructureExampleApplication.java new file mode 100644 index 0000000..4a1861f --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/HexagonalArchitectureStructureExampleApplication.java @@ -0,0 +1,30 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample; + +import girgin.ramazan.hexagonalarchitecturestructureexample.infrastructure.interceptor.CorrelationIdInterceptor; +import girgin.ramazan.hexagonalarchitecturestructureexample.infrastructure.interceptor.LogExecutionInterceptor; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@SpringBootApplication +public class HexagonalArchitectureStructureExampleApplication { + + public static void main(String[] args) { + SpringApplication.run(HexagonalArchitectureStructureExampleApplication.class, args); + } + + @Bean + public WebMvcConfigurerAdapter adapter() { + return new WebMvcConfigurerAdapter() { + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(new CorrelationIdInterceptor()); + registry.addInterceptor(new LogExecutionInterceptor()); + } + }; + } + +} + diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/events/EventListener.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/events/EventListener.java new file mode 100644 index 0000000..a038fea --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/events/EventListener.java @@ -0,0 +1,4 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.application.events; + +public class EventListener { +} diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/controller/FooController.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/controller/FooController.java new file mode 100644 index 0000000..f374743 --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/controller/FooController.java @@ -0,0 +1,38 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.application.rest.controller; + +import girgin.ramazan.hexagonalarchitecturestructureexample.application.rest.converter.FooRequestToFooVoConverter; +import girgin.ramazan.hexagonalarchitecturestructureexample.application.rest.mapper.FooResponseMapper; +import girgin.ramazan.hexagonalarchitecturestructureexample.application.rest.model.dto.FooDto; +import girgin.ramazan.hexagonalarchitecturestructureexample.application.rest.model.request.FooRequest; +import girgin.ramazan.hexagonalarchitecturestructureexample.domain.service.FooService; +import girgin.ramazan.hexagonalarchitecturestructureexample.domain.service.vo.FooDetailsVo; +import girgin.ramazan.hexagonalarchitecturestructureexample.domain.service.vo.RetrieveFooVo; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class FooController { + + private final FooService fooService; + private final FooRequestToFooVoConverter fooRequestToFooVoConverter; + private final FooResponseMapper fooResponseMapper; + + public FooController(FooService fooService, + FooRequestToFooVoConverter fooRequestToFooVoConverter, + FooResponseMapper fooResponseMapper) { + this.fooService = fooService; + this.fooRequestToFooVoConverter = fooRequestToFooVoConverter; + this.fooResponseMapper = fooResponseMapper; + } + + + @PostMapping("/api/v1/foos") + @ResponseStatus(HttpStatus.OK) + public FooDto retrieve(FooRequest fooRequest) { + RetrieveFooVo retrieveFooVo = fooRequestToFooVoConverter.convert(fooRequest); + FooDetailsVo fooDetailsVo = fooService.retrieveFoo(retrieveFooVo); + return fooResponseMapper.map(fooDetailsVo); + } +} \ No newline at end of file diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/converter/FooRequestToFooVoConverter.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/converter/FooRequestToFooVoConverter.java new file mode 100644 index 0000000..51bb2b6 --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/converter/FooRequestToFooVoConverter.java @@ -0,0 +1,14 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.application.rest.converter; + +import girgin.ramazan.hexagonalarchitecturestructureexample.application.rest.model.request.FooRequest; +import girgin.ramazan.hexagonalarchitecturestructureexample.domain.service.vo.RetrieveFooVo; +import org.springframework.stereotype.Component; + +@Component +public class FooRequestToFooVoConverter { + public RetrieveFooVo convert(FooRequest fooRequest) { + return new RetrieveFooVo.Builder() + .propertyOne(fooRequest.getName()) + .build(); + } +} diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/exception/UnwantedCharacterInNameException.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/exception/UnwantedCharacterInNameException.java new file mode 100644 index 0000000..6acb057 --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/exception/UnwantedCharacterInNameException.java @@ -0,0 +1,9 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.application.rest.exception; + +import girgin.ramazan.hexagonalarchitecturestructureexample.domain.exception.BusinessException; + +public class UnwantedCharacterInNameException extends BusinessException { + public UnwantedCharacterInNameException() { + super("validation.error.unwanted.character.in.foo.request.name"); + } +} diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/mapper/FooResponseMapper.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/mapper/FooResponseMapper.java new file mode 100644 index 0000000..266a029 --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/mapper/FooResponseMapper.java @@ -0,0 +1,16 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.application.rest.mapper; + +import girgin.ramazan.hexagonalarchitecturestructureexample.application.rest.model.dto.FooDto; +import girgin.ramazan.hexagonalarchitecturestructureexample.domain.service.vo.FooDetailsVo; +import org.springframework.stereotype.Component; + +@Component +public class FooResponseMapper { + //could be implemented with mapstruct or converted to mapstruct + public FooDto map(FooDetailsVo fooDetailsVo) { + return new FooDto.Builder() + .id(fooDetailsVo.getId()) + .name(fooDetailsVo.getName()) + .build(); + } +} diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/model/dto/FooDto.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/model/dto/FooDto.java new file mode 100644 index 0000000..459105e --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/model/dto/FooDto.java @@ -0,0 +1,49 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.application.rest.model.dto; + +public class FooDto { + private Long id; + private String name; + + private FooDto(Builder builder) { + setId(builder.id); + setName(builder.name); + } + + public Long getId() { + return id; + } + + private void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + private void setName(String name) { + this.name = name; + } + + public static final class Builder { + private Long id; + private String name; + + public Builder() { + } + + public Builder id(Long val) { + id = val; + return this; + } + + public Builder name(String val) { + name = val; + return this; + } + + public FooDto build() { + return new FooDto(this); + } + } +} diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/model/request/FooRequest.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/model/request/FooRequest.java new file mode 100644 index 0000000..e210a1d --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/model/request/FooRequest.java @@ -0,0 +1,51 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.application.rest.model.request; + +public class FooRequest { + int id; + String name; + + public int getId() { + return id; + } + + private void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + private void setName(String name) { + this.name = name; + } + + public static final class FooRequestBuilder { + int id; + String name; + + private FooRequestBuilder() { + } + + public static FooRequestBuilder aFooRequest() { + return new FooRequestBuilder(); + } + + public FooRequestBuilder id(int id) { + this.id = id; + return this; + } + + public FooRequestBuilder name(String name) { + this.name = name; + return this; + } + + public FooRequest build() { + FooRequest fooRequest = new FooRequest(); + fooRequest.id = this.id; + fooRequest.name = this.name; + return fooRequest; + } + } +} diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/model/response/ErrorResponse.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/model/response/ErrorResponse.java new file mode 100644 index 0000000..7dcd120 --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/model/response/ErrorResponse.java @@ -0,0 +1,56 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.application.rest.model.response; + +public class ErrorResponse { + + private String code; + private String locale; + private String message; + + public String getCode() { + return code; + } + + public String getLocale() { + return locale; + } + + public String getMessage() { + return message; + } + + public static final class Builder { + private String code; + private String locale; + private String message; + + public Builder() { + } + + public static Builder anErrorResponse() { + return new Builder(); + } + + public Builder code(String code) { + this.code = code; + return this; + } + + public Builder locale(String locale) { + this.locale = locale; + return this; + } + + public Builder message(String message) { + this.message = message; + return this; + } + + public ErrorResponse build() { + ErrorResponse errorResponse = new ErrorResponse(); + errorResponse.message = this.message; + errorResponse.locale = this.locale; + errorResponse.code = this.code; + return errorResponse; + } + } +} \ No newline at end of file diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/validator/FooRequestValidator.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/validator/FooRequestValidator.java new file mode 100644 index 0000000..c59bedd --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/application/rest/validator/FooRequestValidator.java @@ -0,0 +1,12 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.application.rest.validator; + +import girgin.ramazan.hexagonalarchitecturestructureexample.application.rest.exception.UnwantedCharacterInNameException; +import girgin.ramazan.hexagonalarchitecturestructureexample.application.rest.model.request.FooRequest; + +public class FooRequestValidator { + public void validate(FooRequest fooRequest){ + if (fooRequest.getName().contains("UnwantedName")){ + throw new UnwantedCharacterInNameException(); + } + } +} diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/exception/BusinessException.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/exception/BusinessException.java new file mode 100644 index 0000000..dae558f --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/exception/BusinessException.java @@ -0,0 +1,23 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.domain.exception; + +public class BusinessException extends RuntimeException { + private String messageKey; + + public String getMessageKey() { + return messageKey; + } + + public void setMessageKey(String messageKey) { + this.messageKey = messageKey; + } + + public BusinessException(String messageKey) { + super(); + this.messageKey = messageKey; + } + + public BusinessException(String messageKey, Throwable cause) { + super(cause); + this.messageKey = messageKey; + } +} diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/exception/SomethingNotFoundException.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/exception/SomethingNotFoundException.java new file mode 100644 index 0000000..0e143d5 --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/exception/SomethingNotFoundException.java @@ -0,0 +1,8 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.domain.exception; + +public class SomethingNotFoundException extends BusinessException { + + public SomethingNotFoundException() { + super("error.while.doing.something"); + } +} diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/model/converter/StatusConverter.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/model/converter/StatusConverter.java new file mode 100644 index 0000000..f86c5d3 --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/model/converter/StatusConverter.java @@ -0,0 +1,25 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.domain.model.converter; + + +import girgin.ramazan.hexagonalarchitecturestructureexample.domain.model.enumtype.Status; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; +import java.util.stream.Stream; + +@Converter +public class StatusConverter implements AttributeConverter { + + @Override + public Integer convertToDatabaseColumn(Status status) { + return status.getValue(); + } + + @Override + public Status convertToEntityAttribute(Integer value) { + return Stream.of(Status.values()) + .filter(status -> status.getValue().equals(value)) + .findFirst() + .orElse(null); + } +} diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/model/entity/BaseEntity.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/model/entity/BaseEntity.java new file mode 100644 index 0000000..b4e0427 --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/model/entity/BaseEntity.java @@ -0,0 +1,63 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.domain.model.entity; + +import girgin.ramazan.hexagonalarchitecturestructureexample.domain.model.converter.StatusConverter; +import girgin.ramazan.hexagonalarchitecturestructureexample.domain.model.enumtype.Status; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; + +import javax.persistence.*; +import java.io.Serializable; +import java.time.LocalDateTime; + +@MappedSuperclass +public abstract class BaseEntity implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id", updatable = false, nullable = false) + private Long id; + + @CreatedDate + @Column(name = "created_at", nullable = false) + private LocalDateTime createdAt = LocalDateTime.now(); + + @LastModifiedDate + @Column(name = "updated_at") + private LocalDateTime updatedAt; + + @Convert(converter = StatusConverter.class) + @Column(name = "status", nullable = false) + private Status status = Status.ACTIVE; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public LocalDateTime getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(LocalDateTime createdAt) { + this.createdAt = createdAt; + } + + public LocalDateTime getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(LocalDateTime updatedAt) { + this.updatedAt = updatedAt; + } + + public Status getStatus() { + return status; + } + + public void setStatus(Status status) { + this.status = status; + } +} diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/model/entity/Foo.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/model/entity/Foo.java new file mode 100644 index 0000000..c955d24 --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/model/entity/Foo.java @@ -0,0 +1,22 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.domain.model.entity; + + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; + +@Entity +@Table(name = "foo") +public class Foo extends BaseEntity { + + @Column(name = "name", nullable = false, updatable = false) + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/model/enumtype/Status.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/model/enumtype/Status.java new file mode 100644 index 0000000..f5fd992 --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/model/enumtype/Status.java @@ -0,0 +1,20 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.domain.model.enumtype; + + +public enum Status { + + DELETED(-1), + PASSIVE(0), + ACTIVE(1); + + private final Integer value; + + Status(Integer value) { + this.value = value; + } + + public Integer getValue() { + return value; + } +} + diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/repository/FooRepository.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/repository/FooRepository.java new file mode 100644 index 0000000..beafb6e --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/repository/FooRepository.java @@ -0,0 +1,7 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.domain.repository; + +import girgin.ramazan.hexagonalarchitecturestructureexample.domain.model.entity.Foo; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface FooRepository extends JpaRepository { +} \ No newline at end of file diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/service/FooService.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/service/FooService.java new file mode 100644 index 0000000..b5bd8bb --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/service/FooService.java @@ -0,0 +1,26 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.domain.service; + +import girgin.ramazan.hexagonalarchitecturestructureexample.domain.exception.SomethingNotFoundException; +import girgin.ramazan.hexagonalarchitecturestructureexample.domain.service.external.servicea.ExternalServiceA; +import girgin.ramazan.hexagonalarchitecturestructureexample.domain.service.vo.FooDetailsVo; +import girgin.ramazan.hexagonalarchitecturestructureexample.domain.service.vo.RetrieveFooVo; +import org.springframework.stereotype.Service; + +@Service +public class FooService { + private final ExternalServiceA externalServiceA; + + public FooService(ExternalServiceA externalServiceA) { + this.externalServiceA = externalServiceA; + } + + public FooDetailsVo retrieveFoo(RetrieveFooVo retrieveFooVo) { + Long retrievedValueOrDetails = externalServiceA.retrieveValue(retrieveFooVo.getPropertyOne(), retrieveFooVo.getPropertyThree()); + if (retrievedValueOrDetails < 0) { //just for show how service - exception interacts + throw new SomethingNotFoundException(); + } + return new FooDetailsVo.Builder() + .id(retrievedValueOrDetails)//additional details could be added here + .build(); + } +} diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/service/external/servicea/ExternalServiceA.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/service/external/servicea/ExternalServiceA.java new file mode 100644 index 0000000..6e4f3d0 --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/service/external/servicea/ExternalServiceA.java @@ -0,0 +1,5 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.domain.service.external.servicea; + +public interface ExternalServiceA { + Long retrieveValue(String propertyOne, String propertyThree); +} diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/service/vo/FooDetailsVo.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/service/vo/FooDetailsVo.java new file mode 100644 index 0000000..dcec490 --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/service/vo/FooDetailsVo.java @@ -0,0 +1,63 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.domain.service.vo; + +public class FooDetailsVo { + private Long id; + private String name; + private String location; + + public Long getId() { + return id; + } + + private void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + private void setName(String name) { + this.name = name; + } + + public String getLocation() { + return location; + } + + private void setLocation(String location) { + this.location = location; + } + + public static final class Builder { + private Long id; + private String name; + private String location; + + public Builder() { + } + + public Builder id(Long id) { + this.id = id; + return this; + } + + public Builder name(String name) { + this.name = name; + return this; + } + + public Builder location(String location) { + this.location = location; + return this; + } + + public FooDetailsVo build() { + FooDetailsVo fooDetailsVo = new FooDetailsVo(); + fooDetailsVo.id = this.id; + fooDetailsVo.location = this.location; + fooDetailsVo.name = this.name; + return fooDetailsVo; + } + } +} diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/service/vo/RetrieveFooVo.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/service/vo/RetrieveFooVo.java new file mode 100644 index 0000000..f4822cf --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/domain/service/vo/RetrieveFooVo.java @@ -0,0 +1,67 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.domain.service.vo; + +public class RetrieveFooVo { + private String propertyOne; + private String propertyTwo; + private String propertyThree; + + public String getPropertyOne() { + return propertyOne; + } + + private void setPropertyOne(String propertyOne) { + this.propertyOne = propertyOne; + } + + public String getPropertyTwo() { + return propertyTwo; + } + + private void setPropertyTwo(String propertyTwo) { + this.propertyTwo = propertyTwo; + } + + public String getPropertyThree() { + return propertyThree; + } + + private void setPropertyThree(String propertyThree) { + this.propertyThree = propertyThree; + } + + public static final class Builder { + private String propertyOne; + private String propertyTwo; + private String propertyThree; + + public Builder() { + } + + public static Builder aRetrieveFooVo() { + return new Builder(); + } + + public Builder propertyOne(String propertyOne) { + this.propertyOne = propertyOne; + return this; + } + + public Builder propertyTwo(String propertyTwo) { + this.propertyTwo = propertyTwo; + return this; + } + + public Builder propertyThree(String propertyThree) { + this.propertyThree = propertyThree; + return this; + } + + public RetrieveFooVo build() { + RetrieveFooVo retrieveFooVo = new RetrieveFooVo(); + retrieveFooVo.propertyOne = this.propertyOne; + retrieveFooVo.propertyThree = this.propertyThree; + retrieveFooVo.propertyTwo = this.propertyTwo; + return retrieveFooVo; + } + } +} diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/adapter/external/ExternalServiceASoapAdapter.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/adapter/external/ExternalServiceASoapAdapter.java new file mode 100644 index 0000000..dcbe4f1 --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/adapter/external/ExternalServiceASoapAdapter.java @@ -0,0 +1,14 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.infrastructure.adapter.external; + +import girgin.ramazan.hexagonalarchitecturestructureexample.domain.service.external.servicea.ExternalServiceA; +import org.springframework.stereotype.Service; + +@Service +public class ExternalServiceASoapAdapter implements ExternalServiceA { + + @Override + public Long retrieveValue(String propertyOne, String propertyThree) { + //retrieve value from external service, with saop api. could be other adapter types + return 1L; + } +} diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/adapter/messaging/StringCloudStreamEventSender.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/adapter/messaging/StringCloudStreamEventSender.java new file mode 100644 index 0000000..437c82e --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/adapter/messaging/StringCloudStreamEventSender.java @@ -0,0 +1,4 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.infrastructure.adapter.messaging; + +public class StringCloudStreamEventSender { +} diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/configuration/DataSourceConfiguration.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/configuration/DataSourceConfiguration.java new file mode 100644 index 0000000..8a94e52 --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/configuration/DataSourceConfiguration.java @@ -0,0 +1,50 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.infrastructure.configuration; + +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import javax.sql.DataSource; +import java.util.concurrent.TimeUnit; + +@Configuration +public class DataSourceConfiguration { + + @Value("${spring.datasource.url}") + private String url; + + @Value("${spring.datasource.username}") + private String username; + + @Value("${spring.datasource.password}") + private String password; + + @Value("${spring.datasource.driver-class-name}") + private String driverClassName; + + @Value("${spring.datasource.poolName}") + private String poolName; + + @Bean + public DataSource dataSource() { + return new HikariDataSource(hikariConfig()); + } + + private HikariConfig hikariConfig() { + HikariConfig config = new HikariConfig(); + config.setDriverClassName(driverClassName); + config.setJdbcUrl(url); + config.setUsername(username); + config.setPassword(password); + config.setPoolName(poolName); + config.setMaximumPoolSize(20); + config.setMinimumIdle(2); + config.setIdleTimeout(TimeUnit.SECONDS.toMillis(30)); + config.addDataSourceProperty("cachePrepStmts", "true"); + config.addDataSourceProperty("prepStmtCacheSize", "250"); + config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); + return config; + } +} diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/configuration/WebMvcConfiguration.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/configuration/WebMvcConfiguration.java new file mode 100644 index 0000000..ed85d8e --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/configuration/WebMvcConfiguration.java @@ -0,0 +1,48 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.infrastructure.configuration; + +import girgin.ramazan.hexagonalarchitecturestructureexample.infrastructure.interceptor.CorrelationIdInterceptor; +import girgin.ramazan.hexagonalarchitecturestructureexample.infrastructure.interceptor.LogExecutionInterceptor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.ResourceBundleMessageSource; +import org.springframework.web.servlet.LocaleResolver; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.i18n.CookieLocaleResolver; +import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; + +import java.util.Locale; + +@Configuration +public class WebMvcConfiguration implements WebMvcConfigurer { + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(new CorrelationIdInterceptor()); + registry.addInterceptor(new LogExecutionInterceptor()); + registry.addInterceptor(localeChangeInterceptor()); + } + + @Bean + public LocaleResolver localeResolver() { + CookieLocaleResolver slr = new CookieLocaleResolver(); + slr.setDefaultLocale(Locale.ENGLISH); + return slr; + } + + @Bean + public ResourceBundleMessageSource messageSource() { + ResourceBundleMessageSource source = new ResourceBundleMessageSource(); + source.setBasenames("i18n/messages"); + source.setUseCodeAsDefaultMessage(true); + source.setDefaultEncoding("UTF-8"); + return source; + } + + @Bean + public LocaleChangeInterceptor localeChangeInterceptor() { + LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); + localeChangeInterceptor.setParamName("lang"); + return localeChangeInterceptor; + } +} diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/configuration/properties/FooProperties.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/configuration/properties/FooProperties.java new file mode 100644 index 0000000..2a5134b --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/configuration/properties/FooProperties.java @@ -0,0 +1,28 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.infrastructure.configuration.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties(prefix = "foo") +public class FooProperties { + + private String firstValue; + private String secondValue; + + public String getFirstValue() { + return firstValue; + } + + public void setFirstValue(String firstValue) { + this.firstValue = firstValue; + } + + public String getSecondValue() { + return secondValue; + } + + public void setSecondValue(String secondValue) { + this.secondValue = secondValue; + } +} diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/interceptor/CorrelationIdInterceptor.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/interceptor/CorrelationIdInterceptor.java new file mode 100644 index 0000000..cf0569a --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/interceptor/CorrelationIdInterceptor.java @@ -0,0 +1,31 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.infrastructure.interceptor; + +import org.slf4j.MDC; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.Optional; +import java.util.UUID; + +public class CorrelationIdInterceptor extends HandlerInterceptorAdapter { + + private static final String CORRELATION_ID_HEADER_NAME = "x-correlation-id"; + private static final String CORRELATION_ID_LOG_VAR_NAME = "correlationId"; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + MDC.put(CORRELATION_ID_LOG_VAR_NAME, getCorrelationId(request)); + return true; + } + + private String getCorrelationId(HttpServletRequest request) { + return Optional.ofNullable(request.getHeader(CORRELATION_ID_HEADER_NAME)) + .orElseGet(() -> UUID.randomUUID().toString()); + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { + MDC.remove(CORRELATION_ID_LOG_VAR_NAME); + } +} \ No newline at end of file diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/interceptor/LogExecutionInterceptor.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/interceptor/LogExecutionInterceptor.java new file mode 100644 index 0000000..71cb9fb --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/interceptor/LogExecutionInterceptor.java @@ -0,0 +1,44 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.infrastructure.interceptor; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class LogExecutionInterceptor extends HandlerInterceptorAdapter { + + private static final Logger logger = LoggerFactory.getLogger(LogExecutionInterceptor.class); + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + try { + if (handler instanceof HandlerMethod) { + HandlerMethod handlerMethod = (HandlerMethod) handler; + request.setAttribute("requestStartTime", System.currentTimeMillis()); + logger.info("Starting rest method for {}", + handlerMethod.getBean().getClass().getName()); + } + } catch (Exception e) { + logger.error("Caught an exception while executing handler method", e); + } + return true; + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { + try { + if (handler instanceof HandlerMethod) { + HandlerMethod handlerMethod = (HandlerMethod) handler; + logger.info("Completed rest method for {} takes {} ms", + handlerMethod.getBean().getClass().getName(), + (System.currentTimeMillis() - (Long) request.getAttribute("requestStartTime"))); + } + } catch (Exception e) { + logger.error("Caught an exception while executing handler method", e); + } + } +} + diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/interceptor/exception/RestControllerExceptionHandler.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/interceptor/exception/RestControllerExceptionHandler.java new file mode 100644 index 0000000..49a898e --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/interceptor/exception/RestControllerExceptionHandler.java @@ -0,0 +1,61 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.infrastructure.interceptor.exception; + +import girgin.ramazan.hexagonalarchitecturestructureexample.application.rest.exception.UnwantedCharacterInNameException; +import girgin.ramazan.hexagonalarchitecturestructureexample.application.rest.model.response.ErrorResponse; +import girgin.ramazan.hexagonalarchitecturestructureexample.domain.exception.BusinessException; +import girgin.ramazan.hexagonalarchitecturestructureexample.domain.exception.SomethingNotFoundException; +import girgin.ramazan.hexagonalarchitecturestructureexample.infrastructure.interceptor.exception.locale.MessageSourceLocalizer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.util.Pair; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.util.Locale; + +@RestControllerAdvice +public class RestControllerExceptionHandler { + + private static final Logger logger = LoggerFactory.getLogger(RestControllerExceptionHandler.class); + + private final MessageSourceLocalizer messageSourceLocalizer; + + public RestControllerExceptionHandler(MessageSourceLocalizer messageSourceLocalizer) { + this.messageSourceLocalizer = messageSourceLocalizer; + } + + @ExceptionHandler(SomethingNotFoundException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public ErrorResponse handleProductNotFoundException(Locale locale, SomethingNotFoundException ex) { + logger.error(ex.getMessageKey(), ex); + return convertExceptionToResponse(locale, ex); + } + + @ExceptionHandler(UnwantedCharacterInNameException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public ErrorResponse handleUnwantedCharacterInNameException(Locale locale, UnwantedCharacterInNameException ex) { + logger.error(ex.getMessageKey(), ex); + return convertExceptionToResponse(locale, ex); + } + + private ErrorResponse convertExceptionToResponse(Locale locale, BusinessException ex) { + String localizedMessage = messageSourceLocalizer.getLocaleMessage(ex.getLocalizedMessage()); + Pair codeAndMessage = parseMessage(localizedMessage); + return new ErrorResponse.Builder() + .code(codeAndMessage.getFirst()) + .message(codeAndMessage.getSecond()) + .locale(locale.getDisplayName()) + .build(); + } + + private Pair parseMessage(String message) { + String[] codeAndMessage = message.split(";"); + if (codeAndMessage.length != 2) { + logger.error("Format error in locatization for message: " + message); + return Pair.of("", message); + } + return Pair.of(codeAndMessage[0], codeAndMessage[1]); + } +} \ No newline at end of file diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/interceptor/exception/locale/LocaleService.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/interceptor/exception/locale/LocaleService.java new file mode 100644 index 0000000..a7087d6 --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/interceptor/exception/locale/LocaleService.java @@ -0,0 +1,31 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.infrastructure.interceptor.exception.locale; + +import org.springframework.context.i18n.LocaleContext; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.stereotype.Component; + +import java.util.Locale; +import java.util.Optional; + +@Component +public class LocaleService { + + private Optional getLocale() { + LocaleContext localeContext = LocaleContextHolder.getLocaleContext(); + return Optional.ofNullable(localeContext) + .map(localeContext1 -> localeContext1.getLocale()); + } + + public Optional getLocaleLanguage() { + Optional locale = getLocale(); + return locale.isPresent() ? Optional.of(((Locale) locale.get()).getLanguage()) : Optional.empty(); + } + + private Locale getLocaleOrDefault() { + return getLocale().orElse(new Locale("TR")); + } + + public String getLocaleLanguageOrDefault() { + return getLocaleOrDefault().getLanguage(); + } +} \ No newline at end of file diff --git a/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/interceptor/exception/locale/MessageSourceLocalizer.java b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/interceptor/exception/locale/MessageSourceLocalizer.java new file mode 100644 index 0000000..084ee30 --- /dev/null +++ b/src/main/java/girgin/ramazan/hexagonalarchitecturestructureexample/infrastructure/interceptor/exception/locale/MessageSourceLocalizer.java @@ -0,0 +1,36 @@ +package girgin.ramazan.hexagonalarchitecturestructureexample.infrastructure.interceptor.exception.locale; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.MessageSource; +import org.springframework.context.NoSuchMessageException; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.stereotype.Component; + +import java.util.Locale; + +@Component +public class MessageSourceLocalizer { + + private static final Logger logger = LoggerFactory.getLogger(MessageSourceLocalizer.class); + + private final MessageSource messageSource; + + public MessageSourceLocalizer(MessageSource messageSource) { + this.messageSource = messageSource; + } + + public String getLocaleMessage(String key) { + return getLocaleMessage(key, new Object[0]); + } + + public String getLocaleMessage(String key, Object... args) { + try { + Locale locale = LocaleContextHolder.getLocale(); + return messageSource.getMessage(key, args, locale); + } catch (NoSuchMessageException e) { + logger.error(key + " not found in messages file", e); + return String.format("???%s???", key); + } + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..e69de29 diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..daa9a5e --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,17 @@ +spring: + application.name: hexagonal-architecture-example + datasource: + driver-class-name: com.mysql.jdbc.Driver + poolName: hexagonal-architecture-example-dbconnectionpool + jpa: + database: MYSQL + show-sql: false + hibernate: + dialect: org.hibernate.dialect.MySQL5InnoDBDialect + naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy + ddl-auto: validate +queue: + activemq: + brokerUrl: vm://localhost?broker.persistent=false&broker.useJmx=true&broker.useShutdownHook=false&jms.redeliveryPolicy.maximumRedeliveries=3&jms.redeliveryPolicy.redeliveryDelay=2000 + inMemory: true + pooled: true \ No newline at end of file diff --git a/src/main/resources/i18n/messages_en.properties b/src/main/resources/i18n/messages_en.properties new file mode 100644 index 0000000..fb3d1e1 --- /dev/null +++ b/src/main/resources/i18n/messages_en.properties @@ -0,0 +1,3 @@ +error.system.occurred=1000;System error +validation.error.unwanted.character.in.foo.request.name=2000;Unwanted character in foo request name field +error.while.doing.something=3000;Error while doing something \ No newline at end of file