Initial commit

This commit is contained in:
Reinhard Prechtl 2017-06-09 12:20:53 +02:00
commit 7073606393
35 changed files with 1367 additions and 0 deletions

25
.gitignore vendored Normal file
View file

@ -0,0 +1,25 @@
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/
logs/

BIN
.mvn/wrapper/maven-wrapper.jar vendored Normal file

Binary file not shown.

1
.mvn/wrapper/maven-wrapper.properties vendored Normal file
View file

@ -0,0 +1 @@
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip

36
domain/pom.xml Normal file
View file

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>domain</artifactId>
<parent>
<groupId>de.rpr.mycity</groupId>
<artifactId>spring-kotlin-jpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-java8</artifactId>
</dependency>
</dependencies>
</project>

View file

@ -0,0 +1,19 @@
package de.rpr.mycity.domain
import java.math.BigDecimal
import javax.persistence.AttributeConverter
class DoubleAttributeConverter : AttributeConverter<Double, BigDecimal?> {
override fun convertToDatabaseColumn(attribute: Double?): BigDecimal? {
return if (attribute != null) {
BigDecimal(attribute)
} else {
null
}
}
override fun convertToEntityAttribute(dbData: BigDecimal?): Double? {
return dbData?.toDouble()
}
}

View file

@ -0,0 +1,42 @@
package de.rpr.mycity.domain.city
import de.rpr.mycity.domain.city.api.CityService
import de.rpr.mycity.domain.city.api.dto.CityDto
import de.rpr.mycity.domain.city.api.dto.CreateCityDto
import de.rpr.mycity.domain.city.api.dto.UpdateCityDto
import de.rpr.mycity.domain.city.entity.CityEntity
import de.rpr.mycity.domain.city.repository.CityRepository
import org.slf4j.Logger
import org.springframework.stereotype.Service
import javax.transaction.Transactional
@Service
@Transactional
internal class DefaultCityService(val cityRepo: CityRepository, val log: Logger) : CityService {
override fun retrieveCity(cityId: String): CityDto? {
log.debug("Retrieving city: {}", cityId)
return cityRepo.findOne(cityId)?.toDto()
}
override fun retrieveCities(): List<CityDto> {
log.debug("Retrieving cities")
return cityRepo.findAll().map { it.toDto() }
}
override fun updateCity(id: String, city: UpdateCityDto): CityDto? {
log.debug("Updating city: {} with data: {}", id, city)
val currentCity = cityRepo.findOne(id)
return if (currentCity != null) cityRepo.save(CityEntity.fromDto(city, currentCity)).toDto()
else null
}
override fun addCity(city: CreateCityDto): CityDto {
log.debug("Adding City: {}", city)
return cityRepo.save(CityEntity.fromDto(city)).toDto()
}
}

View file

@ -0,0 +1,14 @@
package de.rpr.mycity.domain.city
import de.rpr.mycity.domain.city.entity.CityEntity
import de.rpr.mycity.domain.city.repository.CityRepository
import org.springframework.boot.autoconfigure.domain.EntityScan
import org.springframework.context.annotation.Configuration
import org.springframework.data.jpa.repository.config.EnableJpaRepositories
import org.springframework.transaction.annotation.EnableTransactionManagement
@Configuration
@EnableJpaRepositories(basePackageClasses = arrayOf(CityRepository::class))
@EntityScan(basePackageClasses = arrayOf(CityEntity::class))
@EnableTransactionManagement
internal class InternalCityConfig

View file

@ -0,0 +1,9 @@
package de.rpr.mycity.domain.city.api
import de.rpr.mycity.domain.city.InternalCityConfig
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration
@Configuration
@ComponentScan(basePackageClasses = arrayOf(InternalCityConfig::class))
class CityConfig

View file

@ -0,0 +1,16 @@
package de.rpr.mycity.domain.city.api
import de.rpr.mycity.domain.city.api.dto.CityDto
import de.rpr.mycity.domain.city.api.dto.CreateCityDto
import de.rpr.mycity.domain.city.api.dto.UpdateCityDto
interface CityService {
fun retrieveCity(cityId: String): CityDto?
fun retrieveCities(): List<CityDto>
fun addCity(city: CreateCityDto): CityDto
fun updateCity(id: String, city: UpdateCityDto): CityDto?
}

View file

@ -0,0 +1,12 @@
package de.rpr.mycity.domain.city.api.dto
import de.rpr.mycity.domain.location.api.CoordinateDto
import java.time.LocalDateTime
data class CityDto(
var id: String,
var name: String,
var description: String? = null,
var location: CoordinateDto,
var updatedAt: LocalDateTime,
var createdAt: LocalDateTime)

View file

@ -0,0 +1,11 @@
package de.rpr.mycity.domain.city.api.dto
import de.rpr.mycity.domain.location.api.CoordinateDto
import org.hibernate.validator.constraints.NotEmpty
import javax.validation.Valid
data class CreateCityDto(
@NotEmpty var id: String,
@NotEmpty var name: String,
var description: String? = null,
@Valid var location: CoordinateDto)

View file

@ -0,0 +1,8 @@
package de.rpr.mycity.domain.city.api.dto
import de.rpr.mycity.domain.location.api.CoordinateDto
data class UpdateCityDto(
val name: String?,
val description: String?,
val location: CoordinateDto?)

View file

@ -0,0 +1,66 @@
package de.rpr.mycity.domain.city.entity
import de.rpr.mycity.domain.city.api.dto.CityDto
import de.rpr.mycity.domain.city.api.dto.CreateCityDto
import de.rpr.mycity.domain.city.api.dto.UpdateCityDto
import de.rpr.mycity.domain.location.jpa.Coordinate
import java.time.LocalDateTime
import javax.persistence.Embedded
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.Table
@Entity
@Table(name = "city")
internal data class CityEntity(
@Id val id: String? = null,
val name: String,
val description: String? = null,
@Embedded val location: Coordinate,
val updatedAt: LocalDateTime = LocalDateTime.now(),
val createdAt: LocalDateTime = LocalDateTime.now()) {
// Default constructor for JPA
@Suppress("unused")
private constructor() : this(
name = "",
location = Coordinate.origin(),
updatedAt = LocalDateTime.MIN)
fun toDto(): CityDto = CityDto(
id = this.id!!,
name = this.name,
description = this.description,
location = this.location.toDto(),
updatedAt = this.updatedAt,
createdAt = this.createdAt
)
companion object {
fun fromDto(dto: CityDto) = CityEntity(
id = dto.id,
name = dto.name,
description = dto.description,
location = Coordinate.fromDto(dto.location),
updatedAt = dto.updatedAt,
createdAt = dto.createdAt)
fun fromDto(dto: CreateCityDto) = CityEntity(
id = dto.id,
name = dto.name,
description = dto.description,
location = Coordinate(dto.location.longitude, dto.location.latitude))
fun fromDto(dto: UpdateCityDto, defaultCity: CityEntity) = CityEntity(
id = defaultCity.id!!,
name = dto.name ?: defaultCity.name,
description = dto.description ?: defaultCity.description,
location = if (dto.location != null) Coordinate(dto.location.longitude, dto.location.latitude) else defaultCity.location,
updatedAt = LocalDateTime.now(),
createdAt = defaultCity.createdAt)
}
}

View file

@ -0,0 +1,10 @@
package de.rpr.mycity.domain.city.repository
import de.rpr.mycity.domain.city.entity.CityEntity
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
import javax.transaction.Transactional
@Repository
@Transactional(Transactional.TxType.MANDATORY)
internal interface CityRepository : JpaRepository<CityEntity, String>

View file

@ -0,0 +1,10 @@
package de.rpr.mycity.domain.location.api
data class CoordinateDto(
val longitude: Double,
val latitude: Double) {
companion object {
fun origin() = CoordinateDto(0.0, 0.0)
}
}

View file

@ -0,0 +1,23 @@
package de.rpr.mycity.domain.location.jpa
import de.rpr.mycity.domain.DoubleAttributeConverter
import de.rpr.mycity.domain.location.api.CoordinateDto
import javax.persistence.Convert
import javax.persistence.Embeddable
@Embeddable
internal data class Coordinate(
@Convert(converter = DoubleAttributeConverter::class) val longitude: Double,
@Convert(converter = DoubleAttributeConverter::class) val latitude: Double) {
private constructor() : this(0.0, 0.0)
fun toDto(): CoordinateDto = CoordinateDto(this.longitude, this.latitude)
companion object {
fun origin() = Coordinate()
fun fromDto(dto: CoordinateDto): Coordinate = Coordinate(dto.longitude, dto.latitude)
}
}

View file

@ -0,0 +1,12 @@
CREATE SEQUENCE hibernate_sequence;
CREATE TABLE city (
id VARCHAR(15) PRIMARY KEY,
name VARCHAR(128) NOT NULL,
description VARCHAR(1024) NULL,
latitude NUMERIC NOT NULL,
longitude NUMERIC NOT NULL,
updated_at TIMESTAMP NOT NULL,
created_at TIMESTAMP NOT NULL
);

View file

@ -0,0 +1,115 @@
package de.rpr.mycity.domain.city
import de.rpr.mycity.domain.city.api.CityConfig
import de.rpr.mycity.domain.city.api.CityService
import de.rpr.mycity.domain.city.api.dto.CreateCityDto
import de.rpr.mycity.domain.city.api.dto.UpdateCityDto
import de.rpr.mycity.domain.city.entity.CityEntity
import de.rpr.mycity.domain.city.repository.CityRepository
import de.rpr.mycity.domain.location.api.CoordinateDto
import de.rpr.mycity.domain.location.jpa.Coordinate
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.JUnitSoftAssertions
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.mock
import org.slf4j.Logger
import org.springframework.beans.factory.InjectionPoint
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Scope
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit4.SpringRunner
import javax.transaction.Transactional
@RunWith(SpringRunner::class)
@ContextConfiguration(classes = arrayOf(
DefaultCityServiceTest.Config::class,
CityConfig::class))
@Transactional
@DataJpaTest
internal class DefaultCityServiceTest {
class Config {
@Bean
@Scope("prototype")
fun logger(injectionPoint: InjectionPoint): Logger = mock(Logger::class.java)
}
@Autowired
lateinit var service: CityService
@Autowired
lateinit var repository: CityRepository
@get:Rule
var softly = JUnitSoftAssertions()
@Test
fun `'retrieveCities' should retrieve empty list if repository doesn't contain entities`() {
assertThat(service.retrieveCities()).isEmpty()
}
@Test
fun `'retrieveCity' should return null if city for cityId doesnt exist`() {
assertThat(service.retrieveCity("invalid")).isNull()
}
@Test
fun `'retrieveCity' should map existing entity from repository`() {
repository.save(CityEntity("city", "cityname", "description", Coordinate(1.0, -1.0)))
val result = service.retrieveCity("city")
softly.assertThat(result?.id).isNotNull
softly.assertThat(result?.name).isEqualTo("cityname")
softly.assertThat(result?.description).isEqualTo("description")
softly.assertThat(result?.location).isEqualTo(CoordinateDto(1.0, -1.0))
}
@Test
fun `'retrieveCities' should map entity from repository`() {
repository.save(CityEntity("city", "cityname", "description", Coordinate(1.0, -1.0)))
val result = service.retrieveCities()
softly.assertThat(result).hasSize(1)
result.forEach {
softly.assertThat(it.id).isNotNull
softly.assertThat(it.name).isEqualTo("cityname")
softly.assertThat(it.description).isEqualTo("description")
softly.assertThat(it.location).isEqualTo(CoordinateDto(1.0, -1.0))
}
}
@Test
fun `'addCity' should return created entity`() {
val (id, name, description, location) = service.addCity(CreateCityDto("id", "name", "description", CoordinateDto(1.0, 1.0)))
softly.assertThat(id).isEqualTo("id")
softly.assertThat(name).isEqualTo("name")
softly.assertThat(description).isEqualTo("description")
softly.assertThat(location).isEqualTo(CoordinateDto(1.0, 1.0))
}
@Test
fun `'updateCity' should update existing values`() {
val existingCity = repository.save(CityEntity("city", "cityname", "description", Coordinate(1.0, -1.0)))
val result = service.updateCity(existingCity.id!!, UpdateCityDto("new name", "new description", CoordinateDto(-1.0, -1.0)))
softly.assertThat(result).isNotNull
softly.assertThat(result?.id).isEqualTo(existingCity.id)
softly.assertThat(result?.name).isEqualTo("new name")
softly.assertThat(result?.description).isEqualTo("new description")
softly.assertThat(result?.location).isEqualTo(CoordinateDto(-1.0, -1.0))
}
@Test
fun `'updateCity' shouldn't update null values`() {
val existingCity = repository.save(CityEntity("city", "cityname", "description", Coordinate(1.0, -1.0)))
val result = service.updateCity(existingCity.id!!, UpdateCityDto(null, null, null))
softly.assertThat(result).isNotNull
softly.assertThat(result?.id).isEqualTo(existingCity.id)
softly.assertThat(result?.name).isEqualTo("cityname")
softly.assertThat(result?.description).isEqualTo("description")
softly.assertThat(result?.location).isEqualTo(CoordinateDto(1.0, -1.0))
}
}

225
mvnw vendored Executable file
View file

@ -0,0 +1,225 @@
#!/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 Migwn, 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
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
echo $MAVEN_PROJECTBASEDIR
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 "$@"

143
mvnw.cmd vendored Normal file
View file

@ -0,0 +1,143 @@
@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 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
%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%

138
pom.xml Normal file
View file

@ -0,0 +1,138 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>de.rpr.mycity</groupId>
<artifactId>spring-kotlin-jpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name></name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<kotlin.compiler.incremental>true</kotlin.compiler.incremental>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<kotlin.version>1.1.2-2</kotlin.version>
<kotlin-test.version>1.1.2-4</kotlin-test.version>
<mockito.version>2.8.9</mockito.version>
</properties>
<modules>
<module>web</module>
<module>domain</module>
</modules>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jre8</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>4.2.0</version>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.nhaarman</groupId>
<artifactId>mockito-kotlin</artifactId>
<version>1.4.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
<plugins>
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
<configuration>
<compilerPlugins>
<plugin>spring</plugin>
</compilerPlugins>
<jvmTarget>1.8</jvmTarget>
</configuration>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>

58
web/pom.xml Normal file
View file

@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>de.rpr.mycity</groupId>
<artifactId>spring-kotlin-jpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>web</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>de.rpr.mycity</groupId>
<artifactId>domain</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View file

@ -0,0 +1,33 @@
package de.rpr.mycity
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.InjectionPoint
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Scope
@SpringBootApplication
class Application {
@Bean
@Scope("prototype")
fun logger(injectionPoint: InjectionPoint): Logger = LoggerFactory.getLogger(injectionPoint.methodParameter.containingClass)
@Bean
fun objectMapper(): ObjectMapper {
val mapper = ObjectMapper().registerModule(KotlinModule())
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
return mapper
}
}
fun main(args: Array<String>) {
SpringApplication.run(Application::class.java, *args)
}

View file

@ -0,0 +1,80 @@
package de.rpr.mycity.web
import de.rpr.mycity.domain.city.api.CityService
import de.rpr.mycity.domain.city.api.dto.CreateCityDto
import de.rpr.mycity.domain.city.api.dto.UpdateCityDto
import de.rpr.mycity.web.CITIES_PATH
import de.rpr.mycity.web.resource.CityResource
import org.slf4j.Logger
import org.springframework.hateoas.Resources
import org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo
import org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn
import org.springframework.http.HttpEntity
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.util.UriComponentsBuilder
@RestController
@RequestMapping(
value = CITIES_PATH,
produces = arrayOf(
MediaType.APPLICATION_JSON_VALUE,
MediaType.TEXT_XML_VALUE,
MediaType.APPLICATION_XML_VALUE))
class CityController(val cityService: CityService, val log: Logger) {
@GetMapping
fun retrieveCities(): HttpEntity<Resources<CityResource>> {
log.debug("Retrieving cities")
val result = cityService.retrieveCities()
return ResponseEntity.ok(Resources(result.map { CityResource.fromDto(it) }))
}
@GetMapping("{id}")
fun retrieveCity(@PathVariable("id") cityId: String): HttpEntity<CityResource> {
log.debug("Retrieving city: {}", cityId)
val result = cityService.retrieveCity(cityId)
if (result != null) {
val resource = CityResource.fromDto(result)
resource.add(linkTo(methodOn(this::class.java).retrieveCity(result.id)).withSelfRel())
return ResponseEntity.ok(resource)
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build()
}
}
@PostMapping(consumes = arrayOf(
MediaType.APPLICATION_JSON_VALUE,
MediaType.TEXT_XML_VALUE,
MediaType.APPLICATION_XML_VALUE))
fun addCity(@RequestBody city: CreateCityDto, uriBuilder: UriComponentsBuilder): HttpEntity<CityResource> {
log.debug("Request to add a city")
val result = cityService.addCity(city)
val resource = CityResource.fromDto(result)
resource.add(linkTo(methodOn(this::class.java).retrieveCity(result.id)).withSelfRel())
return ResponseEntity
.created(uriBuilder.path("$CITIES_PATH/{id}").buildAndExpand(result.id).toUri())
.body(resource)
}
@PutMapping("{id}")
fun updateCity(@PathVariable("id") cityId: String, @RequestBody city: UpdateCityDto): HttpEntity<CityResource> {
log.debug("Request to update city: {}", cityId)
val result = cityService.updateCity(cityId, city)
if (result != null) {
val resource = CityResource.fromDto(result)
resource.add(linkTo(methodOn(this::class.java).retrieveCity(result.id)).withSelfRel())
return ResponseEntity.ok(resource)
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build()
}
}
}

View file

@ -0,0 +1,11 @@
package de.rpr.mycity.web
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
@Controller
class IndexController {
@GetMapping
fun index() = "index"
}

View file

@ -0,0 +1,8 @@
package de.rpr.mycity.web
/*
This file contains path constants for the controllers
*/
internal const val CITIES_PATH = "cities"
internal const val VENUES_PATH = "venues"

View file

@ -0,0 +1,56 @@
package de.rpr.mycity.web.conversion
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.*
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import de.rpr.mycity.domain.location.api.CoordinateDto
@JsonSerialize(using = CoordinateSerializer::class)
@JsonDeserialize(using = CoordinateDeserializer::class)
data class CoordinateType(
val longitude: Double,
val latitude: Double) {
companion object {
fun fromDto(dto: CoordinateDto): CoordinateType = CoordinateType(
longitude = dto.longitude,
latitude = dto.latitude
)
}
}
class CoordinateSerializer : JsonSerializer<CoordinateType>() {
override fun serialize(
value: CoordinateType?,
gen: JsonGenerator?,
serializers: SerializerProvider?) {
if (gen != null && value != null) {
gen.writeStartObject()
gen.writeNumberField("lat", value.latitude)
gen.writeNumberField("long", value.longitude)
gen.writeEndObject()
}
}
}
class CoordinateDeserializer : JsonDeserializer<CoordinateType?>() {
override fun deserialize(
p: JsonParser?,
ctxt: DeserializationContext?): CoordinateType? {
if (p != null && ctxt != null) {
val node: JsonNode = p.codec.readTree(p)
return CoordinateType(
longitude = node.get("long").doubleValue(),
latitude = node.get("lat").doubleValue())
} else {
return null
}
}
}

View file

@ -0,0 +1,27 @@
package de.rpr.mycity.web.resource
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonProperty
import de.rpr.mycity.domain.city.api.dto.CityDto
import de.rpr.mycity.web.conversion.CoordinateType
import org.springframework.hateoas.ResourceSupport
data class CityResource
@JsonCreator
constructor(
@JsonProperty("id") val _id: String,
@JsonProperty("name") val name: String,
@JsonProperty("desc") val description: String?,
@JsonProperty("loc") val location: CoordinateType) : ResourceSupport() {
companion object {
fun fromDto(dto: CityDto): CityResource =
CityResource(
_id = dto.id,
name = dto.name,
description = dto.description,
location = CoordinateType.fromDto(dto.location)
)
}
}

View file

@ -0,0 +1,5 @@
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:6432/mycity
spring.datasource.username=mycity
spring.datasource.password=mycity
spring.jpa.hibernate.ddl-auto=validate

View file

@ -0,0 +1,25 @@
Configutation:
name: Default
Appenders:
Console:
name: Console_Appender
target: SYSTEM_OUT
PatternLayout:
pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"
Loggers:
Root:
level: INFO
AppenderRef:
- ref: Console_Appender
Logger:
- name: org.springframework
level: INFO
Logger:
- name: de.rpr.mycity
level: DEBUG

View file

@ -0,0 +1,12 @@
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<title>Spring Framework Guru</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<h1>Hello</h1>
<h2>Fellow Spring Framework Gurus!!!</h2>
</body>
</html>

View file

@ -0,0 +1,18 @@
package de.rpr.mycity
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.TestPropertySource
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
@SpringBootTest
@TestPropertySource(locations = arrayOf("/test-application.properties"))
class ApplicationTests {
@Test
fun contextLoads() {
}
}

View file

@ -0,0 +1,93 @@
package de.rpr.mycity.web
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.reset
import com.nhaarman.mockito_kotlin.verify
import de.rpr.mycity.domain.city.api.CityService
import de.rpr.mycity.domain.city.api.dto.CityDto
import de.rpr.mycity.domain.location.api.CoordinateDto
import org.hamcrest.CoreMatchers.equalTo
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito
import org.mockito.Mockito.`when`
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.context.annotation.Bean
import org.springframework.http.MediaType
import org.springframework.test.context.junit4.SpringRunner
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.*
import java.time.LocalDateTime
@RunWith(SpringRunner::class)
@WebMvcTest(CityController::class)
class CityControllerTest {
@Autowired
lateinit var mockMvc: MockMvc
@Autowired
lateinit var cityService: CityService
@TestConfiguration
class Config {
@Bean
fun cityService(): CityService = Mockito.mock(CityService::class.java)
}
@Before
fun setup() {
reset(cityService)
}
@Test
fun `Retrieving an unknown city should result in status 404`() {
mockMvc.perform(get("/cities/unknown")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound)
}
@Test
fun `Creating a city with an invalid request body should result in status 400 `() {
mockMvc.perform(post("/cities")
.contentType(MediaType.APPLICATION_JSON)
.content("{}"))
.andExpect(status().isBadRequest)
}
@Test
fun `Creating a city with a valid request body should result in status 201 and a location header`() {
`when`(cityService.addCity(any()))
.thenReturn(CityDto("city", "cityname", null, CoordinateDto.origin(), LocalDateTime.now(), LocalDateTime.now()))
mockMvc.perform(post("/cities")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"id\":\"city\", \"name\":\"Cityname\", \"location\": {\"longitude\": 0.0, \"latitude\": 0.0}}"))
.andExpect(status().isCreated)
.andExpect(header().string("location", "http://localhost/cities/city"))
verify(cityService).addCity(any())
}
@Test
fun `Successfully updating a city should result in status 200`() {
`when`(cityService.updateCity(any(), any()))
.thenReturn(CityDto("cityId", "name", "description", CoordinateDto(1.0, -1.0), LocalDateTime.now(), LocalDateTime.now()))
mockMvc.perform(put("/cities/cityId")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"Cityname\", \"location\": {\"longitude\": 0.0, \"latitude\": 0.0}}"))
.andExpect(status().isOk)
.andExpect(jsonPath("$.id", equalTo("cityId")))
.andExpect(jsonPath("$.name", equalTo("name")))
.andExpect(jsonPath("$.desc", equalTo("description")))
.andExpect(jsonPath("$.loc.long", equalTo(1.0)))
.andExpect(jsonPath("$.loc.lat", equalTo(-1.0)))
verify(cityService).updateCity(eq("cityId"), any())
}
}

View file

@ -0,0 +1 @@
mock-maker-inline

View file

@ -0,0 +1,5 @@
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=validate