This commit is contained in:
Jonathan Cook
2019-10-23 15:01:44 +02:00
parent db85c8f275
commit 684ec0d2e3
20486 changed files with 1642483 additions and 0 deletions
@@ -0,0 +1,7 @@
package com.baeldung.kotlin.allopen
import org.springframework.context.annotation.Configuration
@Configuration
class SimpleConfiguration {
}
@@ -0,0 +1,21 @@
package com.baeldung.kotlin.jpa
import javax.persistence.CascadeType
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.persistence.OneToMany
@Entity
data class Person @JvmOverloads constructor(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Int,
@Column(nullable = false)
val name: String,
@Column(nullable = true)
val email: String? = null,
@OneToMany(cascade = [CascadeType.ALL])
val phoneNumbers: List<PhoneNumber>? = null)
@@ -0,0 +1,15 @@
package com.baeldung.kotlin.jpa
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
@Entity
data class PhoneNumber(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Int,
@Column(nullable = false)
val number: String)
@@ -0,0 +1,26 @@
package com.baeldung.kotlin.mockmvc
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/mockmvc")
class MockMvcController {
@RequestMapping(value = ["/validate"], method = [RequestMethod.POST], produces = [MediaType.APPLICATION_JSON_VALUE])
fun validate(@RequestBody request: Request): Response {
val error = if (request.name.first == "admin") {
null
} else {
ERROR
}
return Response(error)
}
companion object {
const val ERROR = "invalid user"
}
}
@@ -0,0 +1,10 @@
package com.baeldung.kotlin.mockmvc
import com.fasterxml.jackson.annotation.JsonInclude
data class Name(val first: String, val last: String)
data class Request(val name: Name)
@JsonInclude(JsonInclude.Include.NON_NULL)
data class Response(val error: String?)
@@ -0,0 +1,52 @@
package com.baeldung.kotlin.mvc
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.EnableWebMvc
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
import org.thymeleaf.spring4.SpringTemplateEngine
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver
import org.thymeleaf.spring4.view.ThymeleafViewResolver
import org.thymeleaf.templatemode.TemplateMode
@EnableWebMvc
@Configuration
open class ApplicationWebConfig : WebMvcConfigurerAdapter(), ApplicationContextAware {
private var applicationContext: ApplicationContext? = null
override fun setApplicationContext(applicationContext: ApplicationContext?) {
this.applicationContext = applicationContext
}
override fun addViewControllers(registry: ViewControllerRegistry?) {
super.addViewControllers(registry)
registry!!.addViewController("/welcome.html")
}
@Bean
open fun templateResolver(): SpringResourceTemplateResolver {
return SpringResourceTemplateResolver()
.apply { prefix = "/WEB-INF/view/" }
.apply { suffix = ".html"}
.apply { templateMode = TemplateMode.HTML }
.apply { setApplicationContext(applicationContext) }
}
@Bean
open fun templateEngine(): SpringTemplateEngine {
return SpringTemplateEngine()
.apply { setTemplateResolver(templateResolver()) }
}
@Bean
open fun viewResolver(): ThymeleafViewResolver {
return ThymeleafViewResolver()
.apply { templateEngine = templateEngine() }
.apply { order = 1 }
}
}
@@ -0,0 +1,18 @@
package com.baeldung.kotlin.mvc
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer
class ApplicationWebInitializer : AbstractAnnotationConfigDispatcherServletInitializer() {
override fun getRootConfigClasses(): Array<Class<*>>? {
return null
}
override fun getServletMappings(): Array<String> {
return arrayOf("/")
}
override fun getServletConfigClasses(): Array<Class<*>> {
return arrayOf(ApplicationWebConfig::class.java)
}
}
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,37 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<context:component-scan base-package="com.baeldung.kotlin.mvc" />
<mvc:view-controller path="/welcome.html"/>
<mvc:annotation-driven />
<bean id="templateResolver"
class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML" />
</bean>
<bean id="templateEngine"
class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<property name="order" value="1" />
</bean>
</beans>
@@ -0,0 +1,7 @@
<html>
<head>Welcome</head>
<body>
<h1>This is the body of the welcome view</h1>
</body>
</html>
+24
View File
@@ -0,0 +1,24 @@
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Spring Kotlin MVC Application</display-name>
<servlet>
<servlet-name>spring-web-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-web-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>spring-web-mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
@@ -0,0 +1,19 @@
package com.baeldung.kotlin.allopen
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner
import org.springframework.test.context.support.AnnotationConfigContextLoader
@RunWith(SpringJUnit4ClassRunner::class)
@ContextConfiguration(
loader = AnnotationConfigContextLoader::class,
classes = arrayOf(SimpleConfiguration::class))
class SimpleConfigurationTest {
@Test
fun contextLoads() {
}
}
@@ -0,0 +1,66 @@
package com.baeldung.kotlin.jpa
import org.hibernate.cfg.Configuration
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase
import org.hibernate.testing.transaction.TransactionUtil.doInHibernate
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.IOException
import java.util.*
class HibernateKotlinIntegrationTest : BaseCoreFunctionalTestCase() {
private val properties: Properties
@Throws(IOException::class)
get() {
val properties = Properties()
properties.load(javaClass.classLoader.getResourceAsStream("hibernate.properties"))
return properties
}
override fun getAnnotatedClasses(): Array<Class<*>> {
return arrayOf(Person::class.java, PhoneNumber::class.java)
}
override fun configure(configuration: Configuration) {
super.configure(configuration)
configuration.properties = properties
}
@Test
fun givenPersonWithFullData_whenSaved_thenFound() {
doInHibernate(({ this.sessionFactory() }), { session ->
val personToSave = Person(0, "John", "jhon@test.com", Arrays.asList(PhoneNumber(0, "202-555-0171"), PhoneNumber(0, "202-555-0102")))
session.persist(personToSave)
val personFound = session.find(Person::class.java, personToSave.id)
session.refresh(personFound)
assertTrue(personToSave == personFound)
})
}
@Test
fun givenPerson_whenSaved_thenFound() {
doInHibernate(({ this.sessionFactory() }), { session ->
val personToSave = Person(0, "John")
session.persist(personToSave)
val personFound = session.find(Person::class.java, personToSave.id)
session.refresh(personFound)
assertTrue(personToSave == personFound)
})
}
@Test
fun givenPersonWithNullFields_whenSaved_thenFound() {
doInHibernate(({ this.sessionFactory() }), { session ->
val personToSave = Person(0, "John", null, null)
session.persist(personToSave)
val personFound = session.find(Person::class.java, personToSave.id)
session.refresh(personFound)
assertTrue(personToSave == personFound)
})
}
}
@@ -0,0 +1,61 @@
package com.baeldung.kotlin.mockmvc
import com.fasterxml.jackson.databind.ObjectMapper
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity.status
import org.springframework.test.context.junit4.SpringRunner
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.post
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import org.springframework.test.web.servlet.result.MockMvcResultHandlers
import org.springframework.test.web.servlet.result.MockMvcResultMatchers
@RunWith(SpringRunner::class)
@WebMvcTest
class MockMvcControllerTest {
@Autowired lateinit var mockMvc: MockMvc
@Autowired lateinit var mapper: ObjectMapper
@Test
fun `when supported user is given then raw MockMvc-based validation is successful`() {
mockMvc.perform(MockMvcRequestBuilders
.post("/mockmvc/validate")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsString(Request(Name("admin", "")))))
.andExpect(MockMvcResultMatchers.status().isOk)
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.content().string("{}"))
}
@Test
fun `when supported user is given then kotlin DSL-based validation is successful`() {
doTest(Request(Name("admin", "")), Response(null))
}
@Test
fun `when unsupported user is given then validation is failed`() {
doTest(Request(Name("some-name", "some-surname")), Response(MockMvcController.ERROR))
}
private fun doTest(input: Request, expectation: Response) {
mockMvc.post("/mockmvc/validate") {
contentType = MediaType.APPLICATION_JSON
content = mapper.writeValueAsString(input)
accept = MediaType.APPLICATION_JSON
}.andExpect {
status { isOk }
content { contentType(MediaType.APPLICATION_JSON) }
content { json(mapper.writeValueAsString(expectation)) }
}
}
}
@SpringBootApplication
class MockMvcApplication
@@ -0,0 +1,9 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
hibernate.connection.autocommit=true
jdbc.password=
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop