Skip to content

Commit

Permalink
Converting user DTOs to Entities the hard way
Browse files Browse the repository at this point in the history
  • Loading branch information
johnburbridge committed Oct 15, 2018
1 parent fae1fe4 commit e41772b
Show file tree
Hide file tree
Showing 12 changed files with 62 additions and 64 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,14 @@ import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Profile
import org.springframework.data.domain.AuditorAware
import org.springframework.data.jpa.repository.config.EnableJpaAuditing
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import java.util.*

@Configuration
@EnableWebSecurity
@EntityScan("org.burbridge.sandbox.api.domain")
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
@Profile("default")
class DefaultConfig : WebSecurityConfigurerAdapter() {
class DefaultConfig {

@Bean
fun auditorAware(): AuditorAware<String> = AuditorAware<String> { Optional.empty() }

@Throws(Exception::class)
override fun configure(http: HttpSecurity) {
http
.csrf().disable()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class DevelopmentDataInitializer {

fun initialize() {
userRepository.save(
User(1L, "jburbridge", "John", "Burbridge")
User(1L, "jburbridge", "Passw0rd")
)
val u1 = checkNotNull(userRepository.findByUsername("jburbridge"))
taskRepository.saveAll(setOf(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package org.burbridge.sandbox.api.config

import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Profile
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter

@Configuration
@EnableWebSecurity
@Profile("default")
class WebSecurityConfig : WebSecurityConfigurerAdapter() {

@Throws(Exception::class)
override fun configure(http: HttpSecurity) {
http
.csrf().disable()
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package org.burbridge.sandbox.api.controller

import mu.KotlinLogging
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ class TaskController {
content = taskDto.content!!,
author = User(id = 0L,
username = taskDto.author?.username!!,
firstName = taskDto.author?.firstName!!,
lastName = taskDto.author?.lastName!!
password = taskDto.author?.password!!
)
)
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,16 @@ class UserController {
lateinit var userRepository: UserRepository

@GetMapping("/")
fun getAllUsers(): List<User> {
return userRepository.findAll()
fun getAllUsers(): List<UserDto> {
val users = userRepository.findAll()
val usersDto = users.map { user -> convertToDto(user) }
return usersDto
}

@GetMapping("/{username}")
fun getUserByUsername(@PathVariable username: String): User {
fun getUserByUsername(@PathVariable username: String): UserDto {
try {
return userRepository.findByUsername(username)
return convertToDto(userRepository.findByUsername(username))
} catch (exception: EmptyResultDataAccessException) {
logger.error("Could not find user: $username", exception)
throw RecordNotFoundException(username)
Expand All @@ -37,13 +39,21 @@ class UserController {

@PostMapping("/")
@ResponseStatus(HttpStatus.CREATED)
fun createUser(@RequestBody userDto: UserDto): User {
return userRepository.saveAndFlush(
User(id = 0L,
username = userDto.username!!,
firstName = userDto.firstName!!,
lastName = userDto.lastName!!
)
)
fun createUser(@RequestBody userDto: UserDto): UserDto {
val user = convertToEntity(userDto)
val userCreated = userRepository.saveAndFlush(user)
return convertToDto(userCreated)
}

private fun convertToEntity(userDto: UserDto): User {
return User(id = userDto.id!!.toLong(),
username = userDto.username!!,
password = userDto.password!!)
}

private fun convertToDto(user: User): UserDto {
return UserDto(id = user.id.toInt(),
username = user.username,
password = user.password)
}
}
17 changes: 3 additions & 14 deletions api/src/main/kotlin/org/burbridge/sandbox/api/domain/User.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package org.burbridge.sandbox.api.domain

import org.burbridge.spring.common.dto.UserDto
import javax.persistence.*

@Entity
Expand All @@ -9,17 +8,7 @@ data class User(
@Id
@GeneratedValue
val id: Long,
@Column(unique = true)
@Column(unique = true, nullable = false)
val username: String,
val firstName: String,
val lastName: String
) : AuditableEntity() {
fun toDto(): UserDto {
return UserDto(
id = this.id.toInt(),
firstName = this.firstName,
lastName = this.lastName,
username = this.username
)
}
}
val password: String
) : AuditableEntity()
4 changes: 4 additions & 0 deletions api/src/main/resources/application.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ server:
enabled: true
pattern: common
spring:
security:
user:
name: user
password: test
cache:
type: simple
jpa:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,31 +45,32 @@ class TaskControllerTest {
hhere.
""".trimIndent(),
author = User(id = 1L,
firstName = "Fred",
lastName = "Flintstone",
password = "ILoveWilma",
username = "fflintstone"
)
)
`when`(taskRepository.saveAndFlush(any(Task::class.java))).thenReturn(taskStub)

//act
val taskDto = TaskDto(
id = taskStub.id.toInt(),
name = taskStub.name,
description = taskStub.description,
content = taskStub.content,
author = UserDto(
firstName = taskStub.author.firstName,
lastName = taskStub.author.lastName,
id = taskStub.author.id.toInt(),
password = taskStub.author.password,
username = taskStub.author.username
)
)
val mapper = jacksonObjectMapper()
val taskJson = mapper.writeValueAsString(taskDto)
//act
val mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(URI("http://localhost:8080/tasks/"))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.content(taskJson).with(httpBasic("user", "test")))
.andReturn()

// assert
val status = mvcResult.response.status
val taskResult = mapper.readValue<TaskDto>(mvcResult.response.contentAsString, TaskDto::class.java)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ class TaskRepositoryTest : AbstractSeededIntegrationTest() {
val tasks = taskRepository.findByAuthor_Username("jburbridge")
assertTrue(tasks.isNotEmpty())
assertEquals(3, tasks.count())
assertEquals("Burbridge", tasks.first().author.lastName)
assertEquals("Passw0rd", tasks.first().author.password)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,6 @@ class UserRepositoryTest : AbstractSeededIntegrationTest() {
fun `Can query a user by username`() {
val user = userRepository.findByUsername("jburbridge")
assertNotNull(user)
assertEquals("Burbridge", user.lastName)
}

@Test
fun `Can get a DTO from an user entity`() {
val user = userRepository.findByUsername("jburbridge")
val userDto = user.toDto()
assertNotNull(userDto)
assertEquals(user.firstName, userDto.firstName)
assertEquals(user.lastName, userDto.lastName)
assertEquals(user.username, userDto.username)
assertEquals(1L, user.id)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,12 @@ import javax.annotation.Generated
@Generated("com.robohorse.robopojogenerator")
data class UserDto(

@field:JsonProperty("firstName")
val firstName: String? = null,

@field:JsonProperty("lastName")
val lastName: String? = null,

@field:JsonProperty("id")
val id: Int? = null,

@field:JsonProperty("password", access = JsonProperty.Access.WRITE_ONLY)
val password: String? = null,

@field:JsonProperty("username")
val username: String? = null
)

0 comments on commit e41772b

Please sign in to comment.