content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.hm.hyeonminshinlottospring.domain.user.service
import com.hm.hyeonminshinlottospring.domain.user.repository.UserRepository
import com.hm.hyeonminshinlottospring.domain.user.repository.findByUserId
import com.hm.hyeonminshinlottospring.support.TEST_INVALID_MONEY
import com.hm.hyeonminshinlottospring.support.TEST_MONEY_10
import com.hm.hyeonminshinlottospring.support.TEST_USER_ID
import com.hm.hyeonminshinlottospring.support.createUser
import com.hm.hyeonminshinlottospring.support.createUserCreateRequest
import com.hm.hyeonminshinlottospring.support.createUserMoneyPatchRequest
import io.kotest.assertions.throwables.shouldNotThrowAny
import io.kotest.assertions.throwables.shouldThrowExactly
import io.kotest.core.spec.style.DescribeSpec
import io.mockk.every
import io.mockk.mockk
class UserServiceTest : DescribeSpec(
{
val userRepository = mockk<UserRepository>()
val userService = UserService(userRepository)
describe("createUser") {
context("μ ν¨ν λ°μ΄ν°κ° μ£Όμ΄μ§ κ²½μ°") {
val user = createUser()
val userCreateRequest = createUserCreateRequest(user)
every { userRepository.save(any()) } returns user
it("μ μ μ’
λ£νλ€") {
shouldNotThrowAny {
userService.createUser(userCreateRequest)
}
}
}
}
describe("getUserInformation") {
context("μ‘΄μ¬νλ μ μ IDκ° μ£Όμ΄μ§ κ²½μ°") {
every { userRepository.findByUserId(any()) } returns createUser()
it("μ μ μ’
λ£νλ€") {
shouldNotThrowAny {
userService.getUserInformation(TEST_USER_ID)
}
}
}
}
describe("addUserMoney") {
val user = createUser()
context("μ ν¨ν λ°μ΄ν°κ° μ£Όμ΄μ§ κ²½μ°") {
val request = createUserMoneyPatchRequest()
every { userRepository.findByUserId(any()) } returns user
it("μ μ μ’
λ£νλ€") {
shouldNotThrowAny {
userService.addUserMoney(request)
}
}
}
context("λμ΄ 0 μ΄νλ‘ μ£Όμ΄μ§ κ²½μ°") {
val request = createUserMoneyPatchRequest(money = TEST_INVALID_MONEY)
every { userRepository.findByUserId(any()) } returns user
it("[IllegalArgumentException] μμΈ λ°μνλ€") {
shouldThrowExactly<IllegalArgumentException> {
userService.addUserMoney(request)
}
}
}
}
describe("withdrawUserMoney") {
val user = createUser()
context("μ ν¨ν λ°μ΄ν°κ° μ£Όμ΄μ§ κ²½μ°") {
val request = createUserMoneyPatchRequest()
every { userRepository.findByUserId(any()) } returns user
it("μ μ μ’
λ£νλ€") {
shouldNotThrowAny {
userService.withdrawUserMoney(request)
}
}
}
context("λμ΄ 0 μ΄νλ‘ μ£Όμ΄μ§ κ²½μ°") {
val request = createUserMoneyPatchRequest(money = TEST_INVALID_MONEY)
every { userRepository.findByUserId(any()) } returns user
it("[IllegalArgumentException] μμΈ λ°μνλ€") {
shouldThrowExactly<IllegalArgumentException> {
userService.withdrawUserMoney(request)
}
}
}
context("μμ§ν κΈμ‘ μ΄μμΌλ‘ μ£Όμ΄μ§ κ²½μ°") {
val request = createUserMoneyPatchRequest(money = TEST_MONEY_10 + 1)
every { userRepository.findByUserId(any()) } returns user
it("[IllegalArgumentException] μμΈ λ°μνλ€") {
shouldThrowExactly<IllegalArgumentException> {
userService.withdrawUserMoney(request)
}
}
}
}
},
)
| HyeonminShin-LottoSpring/src/test/kotlin/com/hm/hyeonminshinlottospring/domain/user/service/UserServiceTest.kt | 4024671338 |
package com.hm.hyeonminshinlottospring.domain.lotto.repository
import com.hm.hyeonminshinlottospring.domain.user.repository.UserRepository
import com.hm.hyeonminshinlottospring.support.TEST_DEFAULT_PAGEABLE
import com.hm.hyeonminshinlottospring.support.TEST_INVALID_LOTTO_ID
import com.hm.hyeonminshinlottospring.support.TEST_NOT_EXIST_ROUND
import com.hm.hyeonminshinlottospring.support.TEST_ROUND
import com.hm.hyeonminshinlottospring.support.createLotto
import com.hm.hyeonminshinlottospring.support.createOtherLotto
import com.hm.hyeonminshinlottospring.support.createOtherUser
import com.hm.hyeonminshinlottospring.support.createUser
import com.hm.hyeonminshinlottospring.support.test.BaseTests.RepositoryTest
import io.kotest.assertions.throwables.shouldThrowExactly
import io.kotest.core.spec.style.ExpectSpec
import io.kotest.matchers.ints.shouldBeGreaterThan
import io.kotest.matchers.shouldBe
@RepositoryTest
class LottoRepositoryTest(
private val lottoRepository: LottoRepository,
private val userRepository: UserRepository,
) : ExpectSpec(
{
val user1 = userRepository.save(createUser())
val user2 = userRepository.save(createOtherUser())
val lotto1 = lottoRepository.save(createLotto(user1))
val sameLotto1 = lottoRepository.save(createLotto(user1))
val lotto2 = lottoRepository.save(createOtherLotto(user2))
val pageable = TEST_DEFAULT_PAGEABLE
// μμ μ£Όμ!
afterSpec {
lottoRepository.deleteAll()
userRepository.deleteAll()
}
context("λ¨μ λ‘λ μ‘°ν") {
expect("λ‘λ IDμ μΌμΉνλ λ‘λ μ‘°ν") {
val result = lottoRepository.findByLottoId(lotto1.id)
result.user.userName shouldBe user1.userName
}
expect("μ‘΄μ¬νμ§ μλ λ‘λ IDλ‘ μ‘°ν") {
shouldThrowExactly<NoSuchElementException> {
lottoRepository.findByLottoId(TEST_INVALID_LOTTO_ID)
}
}
expect("μ μ μ μΌμΉνλ λͺ¨λ λ‘λ μ‘°ν") {
val result = lottoRepository.findSliceByUserId(user2.id, pageable)
result.content.size shouldBe 1
}
}
context("λΌμ΄λμ ν΄λΉνλ λ‘λκ° μλμ§ μ‘°ν") {
expect("μ‘΄μ¬νλ λΌμ΄λλ‘ μ‘°ν") {
val result = lottoRepository.findSliceByRound(TEST_ROUND, pageable)
result.content.size shouldBeGreaterThan 0
}
expect("μ‘΄μ¬νμ§ μλ λΌμ΄λλ‘ μ‘°ν") {
val result = lottoRepository.findSliceByRound(TEST_NOT_EXIST_ROUND, pageable)
result.content.size shouldBe 0
}
}
context("μ μ μ λΌμ΄λλ₯Ό μ΄μ©ν μ‘°ν") {
expect("Slice: μ μ μ λΌμ΄λκ° μ‘΄μ¬ν λ") {
val result = lottoRepository.findSliceByUserIdAndRound(user1.id, lotto1.round, pageable)
result.content.size shouldBe 2
}
expect("List: μ μ μ λΌμ΄λκ° μ‘΄μ¬ν λ") {
val result = lottoRepository.findListByUserIdAndRound(user1.id, lotto1.round)
result.size shouldBe 2
}
}
},
)
| HyeonminShin-LottoSpring/src/test/kotlin/com/hm/hyeonminshinlottospring/domain/lotto/repository/LottoRepositoryTest.kt | 2844766641 |
package com.hm.hyeonminshinlottospring.domain.lotto.controller
import com.hm.hyeonminshinlottospring.domain.lotto.domain.GenerateMode
import com.hm.hyeonminshinlottospring.domain.lotto.domain.info.LottoPrice
import com.hm.hyeonminshinlottospring.domain.lotto.service.LottoService
import com.hm.hyeonminshinlottospring.support.PAGE_PARAM
import com.hm.hyeonminshinlottospring.support.ROUND_PARAM
import com.hm.hyeonminshinlottospring.support.SIZE_PARAM
import com.hm.hyeonminshinlottospring.support.TEST_ADMIN_USER_ID
import com.hm.hyeonminshinlottospring.support.TEST_GENERATE_COUNT_10
import com.hm.hyeonminshinlottospring.support.TEST_INVALID_MONEY
import com.hm.hyeonminshinlottospring.support.TEST_INVALID_ROUND
import com.hm.hyeonminshinlottospring.support.TEST_INVALID_USER_ID
import com.hm.hyeonminshinlottospring.support.TEST_MONEY_10
import com.hm.hyeonminshinlottospring.support.TEST_NOT_EXIST_USER_ID
import com.hm.hyeonminshinlottospring.support.TEST_PAGE
import com.hm.hyeonminshinlottospring.support.TEST_PAGEABLE
import com.hm.hyeonminshinlottospring.support.TEST_ROUND
import com.hm.hyeonminshinlottospring.support.TEST_SIZE
import com.hm.hyeonminshinlottospring.support.TEST_USER_ID
import com.hm.hyeonminshinlottospring.support.createLottoCreateRequest
import com.hm.hyeonminshinlottospring.support.createLottoCreateResponse
import com.hm.hyeonminshinlottospring.support.createLottoNumbers
import com.hm.hyeonminshinlottospring.support.createSliceLottoNumberResponse
import com.hm.hyeonminshinlottospring.support.test.BaseTests.UnitControllerTestEnvironment
import com.hm.hyeonminshinlottospring.support.test.ControllerTestHelper.Companion.jsonContent
import com.hm.hyeonminshinlottospring.support.test.RestDocsHelper
import com.hm.hyeonminshinlottospring.support.test.RestDocsHelper.Companion.createDocument
import com.hm.hyeonminshinlottospring.support.test.RestDocsHelper.Companion.createPathDocument
import com.hm.hyeonminshinlottospring.support.test.RestDocsHelper.Companion.requestBody
import com.hm.hyeonminshinlottospring.support.test.RestDocsHelper.Companion.responseBody
import com.hm.hyeonminshinlottospring.support.test.example
import com.hm.hyeonminshinlottospring.support.test.isOptional
import com.hm.hyeonminshinlottospring.support.test.parameterDescription
import com.hm.hyeonminshinlottospring.support.test.pathDescription
import com.hm.hyeonminshinlottospring.support.test.type
import com.ninjasquad.springmockk.MockkBean
import io.kotest.core.spec.style.DescribeSpec
import io.mockk.coEvery
import io.mockk.every
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.restdocs.ManualRestDocumentation
import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders
import org.springframework.restdocs.payload.JsonFieldType
import org.springframework.restdocs.request.RequestDocumentation.pathParameters
import org.springframework.restdocs.request.RequestDocumentation.queryParameters
import org.springframework.test.web.servlet.post
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
import org.springframework.web.context.WebApplicationContext
@UnitControllerTestEnvironment
@WebMvcTest(LottoController::class)
class LottoControllerTest(
private val context: WebApplicationContext,
@MockkBean private val lottoService: LottoService,
) : DescribeSpec(
{
val restDocumentation = ManualRestDocumentation()
val restDocMockMvc = RestDocsHelper.generateRestDocMockMvc(context, restDocumentation)
beforeEach {
restDocumentation.beforeTest(javaClass, it.name.testName)
}
describe("POST /api/v1/lotto") {
val targetUri = "/api/v1/lotto"
context("μ ν¨ν μμ²μ΄λ©΄μ λλ€ μμ±μΈ κ²½μ°") {
val request = createLottoCreateRequest(mode = GenerateMode.RANDOM, numbers = null)
val response = createLottoCreateResponse()
coEvery { lottoService.createLottos(request) } returns response
it("201 μλ΅νλ€.") {
restDocMockMvc.post(targetUri) {
jsonContent(request)
}.andExpect {
status { isCreated() }
}.andDo {
createDocument(
"create-lottos-success-random",
requestBody(
"userId" type JsonFieldType.NUMBER description "μμ²ν μ μ ID" example request.userId,
"mode" type JsonFieldType.STRING description "μμ± λͺ¨λ" example request.mode,
"insertedMoney" type JsonFieldType.NUMBER description "ν¬μ
ν κΈμ‘" example request.insertedMoney,
"numbers" type JsonFieldType.NULL description "λλ€μΌ λ μλ―Έμλ μ§μ λ‘λ λ²νΈ" example request.numbers isOptional true,
),
responseBody(
"userId" type JsonFieldType.NUMBER description "μμ²ν μ μ ID" example response.userId,
"round" type JsonFieldType.NUMBER description "μμ± μμ²λ λΌμ΄λ" example response.round,
"createdLottoCount" type JsonFieldType.NUMBER description "μ μ μμ±λ λ‘λ κ°μ" example response.createdLottoCount,
),
)
}
}
}
context("μ ν¨ν μμ²μ΄λ©΄μ μλ μμ±μΈ κ²½μ°") {
val request = createLottoCreateRequest(
mode = GenerateMode.MANUAL,
numbers = createLottoNumbers(
TEST_GENERATE_COUNT_10,
),
)
val response = createLottoCreateResponse()
coEvery { lottoService.createLottos(request) } returns response
it("201 μλ΅νλ€.") {
restDocMockMvc.post(targetUri) {
jsonContent(request)
}.andExpect {
status { isCreated() }
}.andDo {
createDocument(
"create-lottos-success-manual",
requestBody(
"userId" type JsonFieldType.NUMBER description "μμ²ν μ μ ID" example request.userId,
"mode" type JsonFieldType.STRING description "μμ± λͺ¨λ" example request.mode,
"insertedMoney" type JsonFieldType.NUMBER description "ν¬μ
ν κΈμ‘" example request.insertedMoney,
"numbers[][]" type JsonFieldType.ARRAY description "μλμΌλ‘ μ§μ ν λ‘λ λ²νΈ 리μ€νΈ" example request.numbers isOptional true,
),
responseBody(
"userId" type JsonFieldType.NUMBER description "μμ²ν μ μ ID" example response.userId,
"round" type JsonFieldType.NUMBER description "μμ± μμ²λ λΌμ΄λ" example response.round,
"createdLottoCount" type JsonFieldType.NUMBER description "μ μ μμ±λ λ‘λ κ°μ" example response.createdLottoCount,
),
)
}
}
}
context("μ μ IDκ° μμμΈ κ²½μ°") {
val request = createLottoCreateRequest(userId = TEST_INVALID_USER_ID)
it("400 μλ΅νλ€.") {
restDocMockMvc.post(targetUri) {
jsonContent(request)
}.andExpect {
status { isBadRequest() }
}.andDo {
createDocument(
"create-lottos-fail-user-id-negative",
requestBody(
"userId" type JsonFieldType.NUMBER description "μμ²ν μμμ μ μ ID" example request.userId,
"mode" type JsonFieldType.STRING description "μμ± λͺ¨λ" example request.mode,
"insertedMoney" type JsonFieldType.NUMBER description "ν¬μ
ν κΈμ‘" example request.insertedMoney,
"numbers" type JsonFieldType.NULL description "μ§μ ν λ‘λ λ²νΈ" example request.numbers isOptional true,
),
)
}
}
}
context("μμ²ν μ μ IDκ° μ‘΄μ¬νμ§ μμ κ²½μ°") {
val request = createLottoCreateRequest()
coEvery { lottoService.createLottos(request) } throws NoSuchElementException("$TEST_USER_ID: μ¬μ©μκ° μ‘΄μ¬νμ§ μμ΅λλ€.")
it("404 μλ΅νλ€.") {
restDocMockMvc.post(targetUri) {
jsonContent(request)
}.andExpect {
status { isNotFound() }
}.andDo {
createDocument(
"create-lottos-fail-user-id-not-exist",
requestBody(
"userId" type JsonFieldType.NUMBER description "μ‘΄μ¬νμ§ μλ μ μ ID" example request.userId,
"mode" type JsonFieldType.STRING description "μμ± λͺ¨λ" example request.mode,
"insertedMoney" type JsonFieldType.NUMBER description "ν¬μ
ν κΈμ‘" example request.insertedMoney,
"numbers" type JsonFieldType.NULL description "μ§μ ν λ‘λ λ²νΈ" example request.numbers isOptional true,
),
)
}
}
}
context("ν¬μ
ν κΈμ‘μ΄ μμμΈ κ²½μ°") {
val request = createLottoCreateRequest(insertedMoney = TEST_INVALID_MONEY)
it("400 μλ΅νλ€.") {
restDocMockMvc.post(targetUri) {
jsonContent(request)
}.andExpect {
status { isBadRequest() }
}.andDo {
createDocument(
"create-lottos-fail-inserted-money-negative",
requestBody(
"userId" type JsonFieldType.NUMBER description "μμ²ν μ μ ID" example request.userId,
"mode" type JsonFieldType.STRING description "μμ± λͺ¨λ" example request.mode,
"insertedMoney" type JsonFieldType.NUMBER description "μμμ ν¬μ
ν κΈμ‘" example request.insertedMoney,
"numbers" type JsonFieldType.NULL description "μ§μ ν λ‘λ λ²νΈ" example request.numbers isOptional true,
),
)
}
}
}
context("ν¬μ
ν κΈμ‘μ΄ μ μ κ° κ°μ§ λλ³΄λ€ λ§μ κ²½μ°") {
val request = createLottoCreateRequest(insertedMoney = TEST_MONEY_10 * 2)
coEvery { lottoService.createLottos(request) } throws IllegalStateException("${request.userId}: νμ¬ μμ§ν κΈμ‘($TEST_MONEY_10${LottoPrice.UNIT})λ³΄λ€ μ μ κΈμ‘μ μ
λ ₯ν΄μ£ΌμΈμ.")
it("400 μλ΅νλ€.") {
restDocMockMvc.post(targetUri) {
jsonContent(request)
}.andExpect {
status { isBadRequest() }
}.andDo {
createDocument(
"create-lottos-fail-inserted-money-bigger-than-having",
requestBody(
"userId" type JsonFieldType.NUMBER description "μμ²ν μ μ ID" example request.userId,
"mode" type JsonFieldType.STRING description "μμ± λͺ¨λ" example request.mode,
"insertedMoney" type JsonFieldType.NUMBER description "μμ§κΈμ‘λ³΄λ€ λ§μ΄ ν¬μ
ν κΈμ‘" example request.insertedMoney,
"numbers" type JsonFieldType.NULL description "μ§μ ν λ‘λ λ²νΈ" example request.numbers isOptional true,
),
)
}
}
}
}
describe("GET /api/v1/lotto/{userId}") {
val targetUri = "/api/v1/lotto/{userId}"
context("μ ν¨ν νλΌλ―Έν°λ€μ΄ λμ΄μ€λ κ²½μ°") {
val response = createSliceLottoNumberResponse()
every { lottoService.getLottosByUserAndRound(TEST_USER_ID, TEST_ROUND, TEST_PAGEABLE) } returns response
it("200 μλ΅νλ€.") {
restDocMockMvc.perform(
RestDocumentationRequestBuilders
.get(targetUri, TEST_USER_ID)
.param(ROUND_PARAM, TEST_ROUND.toString())
.param(PAGE_PARAM, TEST_PAGE.toString())
.param(SIZE_PARAM, TEST_SIZE.toString()),
).andExpect(
status().isOk,
).andDo(
createPathDocument(
"get-lottos-by-user-round-success",
pathParameters(
"userId" pathDescription "μ‘°νν μ μ ID" example TEST_USER_ID,
),
queryParameters(
ROUND_PARAM parameterDescription "μ‘°νν λΌμ΄λ" example TEST_ROUND,
PAGE_PARAM parameterDescription "λ°μ΄ν° μ‘°ν μμμ (default = 0)" example TEST_PAGE isOptional true,
SIZE_PARAM parameterDescription "λ°μ΄ν° κ°μ (default = 10)" example TEST_SIZE isOptional true,
),
responseBody(
"userId" type JsonFieldType.NUMBER description "μ‘°ν μμ²ν μ μ ID" example response.userId isOptional true,
"round" type JsonFieldType.NUMBER description "μ‘°νν λ‘λ λΌμ΄λ" example response.round isOptional true,
"hasNext" type JsonFieldType.BOOLEAN description "μ‘°ν κ°λ₯ν μΆκ°μ μΈ λ°μ΄ν° μ‘΄μ¬ μ¬λΆ" example response.hasNext,
"numberOfElements" type JsonFieldType.NUMBER description "νμ¬ κ°μ Έμ¨ λ°μ΄ν° κ°μ" example response.numberOfElements,
"numberList" type JsonFieldType.ARRAY description "μ‘°νλ κ°μλ§νΌμ λ‘λ λ²νΈ 리μ€νΈ" example response.numberList,
),
),
)
}
}
context("μμμ μ μ IDκ° μ£Όμ΄μ§ κ²½μ°") {
it("400 μλ΅νλ€.") {
restDocMockMvc.perform(
RestDocumentationRequestBuilders
.get(targetUri, TEST_INVALID_USER_ID)
.param(ROUND_PARAM, TEST_ROUND.toString())
.param(PAGE_PARAM, TEST_PAGE.toString())
.param(SIZE_PARAM, TEST_SIZE.toString()),
).andExpect(
status().isBadRequest,
).andDo(
createPathDocument(
"get-lottos-by-user-round-fail-user-id-negative",
pathParameters(
"userId" pathDescription "μμμ μ‘°νν μ μ ID" example TEST_INVALID_USER_ID,
),
queryParameters(
ROUND_PARAM parameterDescription "μ‘°νν λΌμ΄λ" example TEST_ROUND,
PAGE_PARAM parameterDescription "λ°μ΄ν° μ‘°ν μμμ (default = 0)" example TEST_PAGE isOptional true,
SIZE_PARAM parameterDescription "λ°μ΄ν° κ°μ (default = 10)" example TEST_SIZE isOptional true,
),
),
)
}
}
context("μμμ λΌμ΄λκ° μ£Όμ΄μ§ κ²½μ°") {
it("400 μλ΅νλ€.") {
restDocMockMvc.perform(
RestDocumentationRequestBuilders
.get(targetUri, TEST_USER_ID)
.param(ROUND_PARAM, TEST_INVALID_ROUND.toString())
.param(PAGE_PARAM, TEST_PAGE.toString())
.param(SIZE_PARAM, TEST_SIZE.toString()),
).andExpect(
status().isBadRequest,
).andDo(
createPathDocument(
"get-lottos-by-user-round-fail-round-negative",
pathParameters(
"userId" pathDescription "μ‘°νν μ μ ID" example TEST_USER_ID,
),
queryParameters(
ROUND_PARAM parameterDescription "μμμ μ‘°νν λΌμ΄λ" example TEST_INVALID_ROUND,
PAGE_PARAM parameterDescription "λ°μ΄ν° μ‘°ν μμμ (default = 0)" example TEST_PAGE isOptional true,
SIZE_PARAM parameterDescription "λ°μ΄ν° κ°μ (default = 10)" example TEST_SIZE isOptional true,
),
),
)
}
}
context("Admin μ μ IDκ° μ£Όμ΄μ§ κ²½μ°") {
every {
lottoService.getLottosByUserAndRound(
TEST_ADMIN_USER_ID,
TEST_ROUND,
TEST_PAGEABLE,
)
} throws IllegalStateException("$TEST_ADMIN_USER_ID: μ£Όμ΄μ§ μ μ IDλ μ‘°νν μ μμ΅λλ€.")
it("400 μλ΅νλ€.") {
restDocMockMvc.perform(
RestDocumentationRequestBuilders
.get(targetUri, TEST_ADMIN_USER_ID)
.param(ROUND_PARAM, TEST_ROUND.toString())
.param(PAGE_PARAM, TEST_PAGE.toString())
.param(SIZE_PARAM, TEST_SIZE.toString()),
).andExpect(
status().isBadRequest,
).andDo(
createPathDocument(
"get-lottos-by-user-round-fail-user-id-admin",
pathParameters(
"userId" pathDescription "Admin μ μ ID" example TEST_ADMIN_USER_ID,
),
queryParameters(
ROUND_PARAM parameterDescription "μ‘°νν λΌμ΄λ" example TEST_ROUND,
PAGE_PARAM parameterDescription "λ°μ΄ν° μ‘°ν μμμ (default = 0)" example TEST_PAGE isOptional true,
SIZE_PARAM parameterDescription "λ°μ΄ν° κ°μ (default = 10)" example TEST_SIZE isOptional true,
),
),
)
}
}
context("μ‘΄μ¬νμ§ μλ μ μ IDκ° μ£Όμ΄μ§ κ²½μ°") {
every {
lottoService.getLottosByUserAndRound(
TEST_NOT_EXIST_USER_ID,
TEST_ROUND,
TEST_PAGEABLE,
)
} throws NoSuchElementException("$TEST_NOT_EXIST_USER_ID: μ¬μ©μκ° μ‘΄μ¬νμ§ μμ΅λλ€.")
it("404 μλ΅νλ€.") {
restDocMockMvc.perform(
RestDocumentationRequestBuilders
.get(targetUri, TEST_NOT_EXIST_USER_ID)
.param(ROUND_PARAM, TEST_ROUND.toString())
.param(PAGE_PARAM, TEST_PAGE.toString())
.param(SIZE_PARAM, TEST_SIZE.toString()),
).andExpect(
status().isNotFound,
).andDo(
createPathDocument(
"get-lottos-by-user-round-fail-user-id-not-exist",
pathParameters(
"userId" pathDescription "μ‘΄μ¬νμ§ μλ μ μ ID" example TEST_NOT_EXIST_USER_ID,
),
queryParameters(
ROUND_PARAM parameterDescription "μ‘°νν λΌμ΄λ" example TEST_ROUND,
PAGE_PARAM parameterDescription "λ°μ΄ν° μ‘°ν μμμ (default = 0)" example TEST_PAGE isOptional true,
SIZE_PARAM parameterDescription "λ°μ΄ν° κ°μ (default = 10)" example TEST_SIZE isOptional true,
),
),
)
}
}
}
afterTest {
restDocumentation.afterTest()
}
},
)
| HyeonminShin-LottoSpring/src/test/kotlin/com/hm/hyeonminshinlottospring/domain/lotto/controller/LottoControllerTest.kt | 4187193136 |
package com.hm.hyeonminshinlottospring.domain.lotto.service
import com.hm.hyeonminshinlottospring.domain.lotto.domain.GenerateMode
import com.hm.hyeonminshinlottospring.domain.lotto.domain.Lotto
import com.hm.hyeonminshinlottospring.domain.lotto.repository.LottoRepository
import com.hm.hyeonminshinlottospring.domain.lotto.service.generator.RandomLottoNumbersGenerator
import com.hm.hyeonminshinlottospring.domain.user.repository.UserRepository
import com.hm.hyeonminshinlottospring.domain.user.repository.findByUserId
import com.hm.hyeonminshinlottospring.domain.winninglotto.domain.WinningLottoInformation
import com.hm.hyeonminshinlottospring.support.TEST_DEFAULT_PAGEABLE
import com.hm.hyeonminshinlottospring.support.TEST_GENERATE_COUNT_10
import com.hm.hyeonminshinlottospring.support.TEST_GENERATE_COUNT_2
import com.hm.hyeonminshinlottospring.support.TEST_NUMBER
import com.hm.hyeonminshinlottospring.support.TEST_ROUND
import com.hm.hyeonminshinlottospring.support.TEST_USER_ID
import com.hm.hyeonminshinlottospring.support.createAdmin
import com.hm.hyeonminshinlottospring.support.createAllLotto
import com.hm.hyeonminshinlottospring.support.createLottoCreateRequest
import com.hm.hyeonminshinlottospring.support.createLottoNumbers
import com.hm.hyeonminshinlottospring.support.createUser
import io.kotest.assertions.throwables.shouldNotThrowAny
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.DescribeSpec
import io.mockk.coEvery
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.sync.Mutex
import org.springframework.data.domain.Slice
class LottoServiceTest : DescribeSpec(
{
val randomLottoNumbersGenerator = mockk<RandomLottoNumbersGenerator>()
val winningLottoInformation = mockk<WinningLottoInformation>()
val lottoRepository = mockk<LottoRepository>()
val userRepository = mockk<UserRepository>()
val lottoService =
LottoService(
randomLottoNumbersGenerator,
winningLottoInformation,
lottoRepository,
userRepository,
)
describe("createLottos") {
context("λͺ¨λ λλ€ μμ± μμ²") {
val user = createUser()
val lottoCreateRequest =
createLottoCreateRequest(numbers = createLottoNumbers(TEST_GENERATE_COUNT_10))
every { userRepository.findByUserId(TEST_USER_ID) } returns user
every { winningLottoInformation.round } returns TEST_ROUND
coEvery { winningLottoInformation.roundMutex } returns Mutex()
coEvery { randomLottoNumbersGenerator.generate() } returns TEST_NUMBER
every { lottoRepository.saveAll(any<List<Lotto>>()) } returns createAllLotto(user)
it("μμ²ν λ‘λμ κ°μλ§νΌ μμ±νλ€") {
shouldNotThrowAny {
lottoService.createLottos(
lottoCreateRequest,
)
}
}
}
context("λͺ¨λ μλ μμ± μμ²") {
val user = createUser()
val lottoCreateRequest =
createLottoCreateRequest(
numbers = createLottoNumbers(TEST_GENERATE_COUNT_10),
mode = GenerateMode.MANUAL,
)
every { userRepository.findByUserId(TEST_USER_ID) } returns user
every { winningLottoInformation.round } returns TEST_ROUND
coEvery { winningLottoInformation.roundMutex } returns Mutex()
coEvery { randomLottoNumbersGenerator.generate() } returns TEST_NUMBER
every { lottoRepository.saveAll(any<List<Lotto>>()) } returns createAllLotto(user)
it("μμ²ν λ‘λμ κ°μλ§νΌ μμ±νλ€") {
shouldNotThrowAny {
lottoService.createLottos(
lottoCreateRequest,
)
}
}
}
}
describe("getLottosByUserAndRound") {
context("μ ν¨ν λ°μ΄ν°κ° μ£Όμ΄μ§ κ²½μ°") {
val user = createUser()
val mockSlice = mockk<Slice<Lotto>>()
every { userRepository.findByUserId(TEST_USER_ID) } returns createUser()
every {
lottoRepository.findSliceByUserIdAndRound(
TEST_USER_ID,
TEST_ROUND,
TEST_DEFAULT_PAGEABLE,
)
} returns mockSlice
every { mockSlice.numberOfElements } returns TEST_GENERATE_COUNT_2
every { mockSlice.content } returns createAllLotto(user)
every { mockSlice.hasNext() } returns true
it("μ μ μ’
λ£νλ€.") {
shouldNotThrowAny {
lottoService.getLottosByUserAndRound(
TEST_USER_ID,
TEST_ROUND,
TEST_DEFAULT_PAGEABLE,
)
}
}
}
context("Admin μ μ κ° μ£Όμ΄μ§ κ²½μ°") {
every { userRepository.findByUserId(TEST_USER_ID) } returns createAdmin()
it("[IllegalStateException] λ°μνλ€.") {
shouldThrow<IllegalStateException> {
lottoService.getLottosByUserAndRound(
TEST_USER_ID,
TEST_ROUND,
TEST_DEFAULT_PAGEABLE,
)
}
}
}
}
// μλ ν
μ€νΈλ‘ coroutine μΈ‘μ μ΄ μ μλΌμ μΌλ¨ postmanμΌλ‘ λ°μμ¨ κ²°κ³Όλ‘ μ λλ€.
/**
* (κΈ°μ€: RANDOM μμ±)
* || μκ° (λ¨μ: ms) ||
* μμ± κ°μ || legacy | coroutine(Default) | coroutine(LOOM) ||
* =====================================================================
* 100 || 183 | 39 | 187 ||
* 1,000 || 740 | 279 | 513 ||
* 10,000 || 3180 | 3760 | 3170 ||
* 100,000 || 32930 | 35840 | 32020 ||
*
*
*/
// TODO: coroutine ν
μ€νΈ λ°©λ² μ νν μκ² λλ©΄ λ€μ μ μ©νκΈ°
// describe("createLottos - Performance Test") {
// val insertedMoney = 1_000_000
//
// context("κΈ°μ‘΄ blocking λ£¨ν΄ μ¬μ©") {
// val user = createUser(money = insertedMoney)
// val lottoCreateRequest = createLottoCreateRequest(insertedMoney = insertedMoney)
// every { userRepository.findByUserId(TEST_USER_ID) } returns user
// every { winningLottoInformation.round } returns TEST_ROUND
// every { lottoRepository.saveAll(any<List<Lotto>>()) } returns emptyList()
// it("μκ° μΈ‘μ ") {
// val time = measureTimeMillis {
// shouldNotThrowAny {
// lottoService.createLottosLegacy(
// lottoCreateRequest,
// )
// }
// }
// println("legacy: $time ms")
// }
// }
//
// context("coroutine μ¬μ©") {
// val user = createUser(money = insertedMoney)
// val lottoCreateRequest = createLottoCreateRequest(insertedMoney = insertedMoney)
// every { userRepository.findByUserId(TEST_USER_ID) } returns user
// every { winningLottoInformation.round } returns TEST_ROUND
// coEvery { winningLottoInformation.roundMutex } returns Mutex()
// coEvery { randomLottoNumbersGenerator.generate() } returns TEST_NUMBER
// every { lottoRepository.saveAll(any<List<Lotto>>()) } returns emptyList()
// it("μκ° μΈ‘μ ") {
// runTest {
// val time = measureTimeMillis {
// shouldNotThrowAny {
// lottoService.createLottos(
// lottoCreateRequest,
// )
// }
// }
// println("coroutine: $time ms")
// }
// }
// }
// }
},
)
| HyeonminShin-LottoSpring/src/test/kotlin/com/hm/hyeonminshinlottospring/domain/lotto/service/LottoServiceTest.kt | 1682825478 |
package com.hm.hyeonminshinlottospring.domain.winninglotto.repository
import com.hm.hyeonminshinlottospring.domain.lotto.repository.LottoRepository
import com.hm.hyeonminshinlottospring.domain.user.domain.UserRole
import com.hm.hyeonminshinlottospring.domain.user.repository.UserRepository
import com.hm.hyeonminshinlottospring.domain.winninglotto.domain.WinningLotto
import com.hm.hyeonminshinlottospring.support.TEST_INVALID_ROUND
import com.hm.hyeonminshinlottospring.support.createAdmin
import com.hm.hyeonminshinlottospring.support.createLotto
import com.hm.hyeonminshinlottospring.support.createUser
import com.hm.hyeonminshinlottospring.support.test.BaseTests.RepositoryTest
import io.kotest.assertions.fail
import io.kotest.core.spec.style.ExpectSpec
import io.kotest.matchers.shouldBe
@RepositoryTest
class WinningLottoRepositoryTest(
private val userRepository: UserRepository,
private val lottoRepository: LottoRepository,
private val winningLottoRepository: WinningLottoRepository,
) : ExpectSpec(
{
val user = userRepository.save(createUser())
val admin = userRepository.save(createAdmin())
val lotto1 = lottoRepository.save(createLotto(admin))
val winLotto1 = winningLottoRepository.save(
WinningLotto(
round = lotto1.round,
lotto = lotto1,
),
)
// μμ μ£Όμ!
afterSpec {
winningLottoRepository.deleteAll()
lottoRepository.deleteAll()
userRepository.deleteAll()
}
context("λΉμ²¨ λ‘λ λ²νΈ μ‘°ν") {
expect("μ‘΄μ¬νλ λΌμ΄λ μ‘°ν") {
val result = winningLottoRepository.findByRound(lotto1.round)
if (result != null) {
result.lotto.user.userRole shouldBe UserRole.ROLE_ADMIN
} else {
fail("μ‘΄μ¬νλ λΌμ΄λλ₯Ό μ 곡ν΄μ£ΌμΈμ.")
}
}
expect("μ‘΄μ¬νμ§ μλ λΌμ΄λ μ‘°ν") {
val result = winningLottoRepository.findByRound(TEST_INVALID_ROUND)
result shouldBe null
}
}
},
)
| HyeonminShin-LottoSpring/src/test/kotlin/com/hm/hyeonminshinlottospring/domain/winninglotto/repository/WinningLottoRepositoryTest.kt | 4281904813 |
package com.hm.hyeonminshinlottospring.domain.winninglotto.cotroller
import com.hm.hyeonminshinlottospring.domain.winninglotto.service.WinningLottoService
import com.hm.hyeonminshinlottospring.support.TEST_ADMIN_USER_ID
import com.hm.hyeonminshinlottospring.support.TEST_INVALID_ROUND
import com.hm.hyeonminshinlottospring.support.TEST_INVALID_USER_ID
import com.hm.hyeonminshinlottospring.support.TEST_NOT_EXIST_ROUND
import com.hm.hyeonminshinlottospring.support.TEST_ROUND
import com.hm.hyeonminshinlottospring.support.TEST_USER_ID
import com.hm.hyeonminshinlottospring.support.USER_ID_PARAM
import com.hm.hyeonminshinlottospring.support.createAdmin
import com.hm.hyeonminshinlottospring.support.createLotto
import com.hm.hyeonminshinlottospring.support.createTotalMatchResponse
import com.hm.hyeonminshinlottospring.support.createWinningLotto
import com.hm.hyeonminshinlottospring.support.createWinningLottoRoundResponse
import com.hm.hyeonminshinlottospring.support.test.BaseTests.UnitControllerTestEnvironment
import com.hm.hyeonminshinlottospring.support.test.RestDocsHelper
import com.hm.hyeonminshinlottospring.support.test.RestDocsHelper.Companion.createPathDocument
import com.hm.hyeonminshinlottospring.support.test.RestDocsHelper.Companion.responseBody
import com.hm.hyeonminshinlottospring.support.test.example
import com.hm.hyeonminshinlottospring.support.test.parameterDescription
import com.hm.hyeonminshinlottospring.support.test.pathDescription
import com.hm.hyeonminshinlottospring.support.test.type
import com.ninjasquad.springmockk.MockkBean
import io.kotest.core.spec.style.DescribeSpec
import io.mockk.coEvery
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.restdocs.ManualRestDocumentation
import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders
import org.springframework.restdocs.payload.JsonFieldType
import org.springframework.restdocs.request.RequestDocumentation.pathParameters
import org.springframework.restdocs.request.RequestDocumentation.queryParameters
import org.springframework.test.web.servlet.get
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
import org.springframework.web.context.WebApplicationContext
@UnitControllerTestEnvironment
@WebMvcTest(controllers = [WinningLottoController::class])
class WinningLottoControllerTest(
private val context: WebApplicationContext,
@MockkBean private val winningLottoService: WinningLottoService,
) : DescribeSpec(
{
val restDocumentation = ManualRestDocumentation()
val restDocMockMvc = RestDocsHelper.generateRestDocMockMvc(context, restDocumentation)
beforeEach {
restDocumentation.beforeTest(javaClass, it.name.testName)
}
describe("GET /api/v1/winninglotto/{round}") {
val targetUri = "/api/v1/winninglotto/{round}"
context("νμ¬ λΌμ΄λλ©΄μ, AdminμΈ κ²½μ°") {
val admin = createAdmin()
val lotto = createLotto(user = admin)
val winningLotto = createWinningLotto(lotto)
val response = createWinningLottoRoundResponse(winningLotto)
coEvery { winningLottoService.getWinningLottoByRound(TEST_ADMIN_USER_ID, TEST_ROUND) } returns response
it("200 μλ΅νλ€.") {
restDocMockMvc.perform(
RestDocumentationRequestBuilders
.get(targetUri, TEST_ROUND)
.param(USER_ID_PARAM, TEST_ADMIN_USER_ID.toString()),
).andExpect(
status().isOk,
).andDo(
createPathDocument(
"get-winning-lotto-round-success-admin-current-round",
pathParameters(
"round" pathDescription "μ‘°νν λΌμ΄λ μ 보" example TEST_ROUND,
),
queryParameters(
USER_ID_PARAM parameterDescription "μ‘°ννλ €λ Admin μ μ ID" example TEST_ADMIN_USER_ID,
),
responseBody(
"round" type JsonFieldType.NUMBER description "μ‘°νν λΌμ΄λ μ 보" example TEST_ROUND,
"numbers" type JsonFieldType.ARRAY description "ν΄λΉ λΌμ΄λμ λΉμ²¨ λ²νΈ 리μ€νΈ" example lotto.numbers,
),
),
)
}
}
context("νμ¬ μ§νμ€μΈ λΌμ΄λ μ΄μ λΌμ΄λλ©΄μ, μΌλ° μ μ μΈ κ²½μ°") {
val admin = createAdmin()
val lotto = createLotto(user = admin)
val winningLotto = createWinningLotto(lotto)
val response = createWinningLottoRoundResponse(winningLotto)
coEvery { winningLottoService.getWinningLottoByRound(TEST_USER_ID, TEST_ROUND) } returns response
it("200 μλ΅νλ€.") {
restDocMockMvc.perform(
RestDocumentationRequestBuilders
.get(targetUri, TEST_ROUND)
.param(USER_ID_PARAM, TEST_USER_ID.toString()),
).andExpect(
status().isOk,
).andDo(
createPathDocument(
"get-winning-lotto-round-success-user-not-current-round",
pathParameters(
"round" pathDescription "μ‘°νν λΌμ΄λ μ 보(νμ¬ μ§νμ€μΈ λΌμ΄λκ° μλ)" example TEST_ROUND,
),
queryParameters(
USER_ID_PARAM parameterDescription "μ‘°ννλ €λ μΌλ° μ μ ID" example TEST_USER_ID,
),
responseBody(
"round" type JsonFieldType.NUMBER description "μ‘°νν λΌμ΄λ μ 보" example TEST_ROUND,
"numbers" type JsonFieldType.ARRAY description "ν΄λΉ λΌμ΄λμ λΉμ²¨ λ²νΈ 리μ€νΈ" example lotto.numbers,
),
),
)
}
}
context("νμ¬ μ§νμ€μΈ λΌμ΄λλ₯Ό μ‘°ννλ μΌλ° μ μ μΈ κ²½μ°") {
coEvery {
winningLottoService.getWinningLottoByRound(
TEST_USER_ID,
TEST_ROUND,
)
} throws IllegalArgumentException("νμ¬ μ§νμ€μΈ λΌμ΄λλ μ‘°νν μ μμ΅λλ€.")
it("400 μλ΅νλ€.") {
restDocMockMvc.perform(
RestDocumentationRequestBuilders
.get(targetUri, TEST_ROUND)
.param(USER_ID_PARAM, TEST_USER_ID.toString()),
).andExpect(
status().isBadRequest,
).andDo(
createPathDocument(
"get-winning-lotto-round-fail-user-current-round",
pathParameters(
"round" pathDescription "μ‘°νν λΌμ΄λ μ 보(νμ¬ μ§νμ€μΈ λΌμ΄λ!)" example TEST_ROUND,
),
queryParameters(
USER_ID_PARAM parameterDescription "μ‘°ννλ €λ μΌλ° μ μ ID" example TEST_USER_ID,
),
),
)
}
}
context("μμμ μ μ IDκ° μ£Όμ΄μ§ κ²½μ°") {
it("400 μλ΅νλ€.") {
restDocMockMvc.perform(
RestDocumentationRequestBuilders
.get(targetUri, TEST_ROUND)
.param(USER_ID_PARAM, TEST_INVALID_USER_ID.toString()),
).andExpect(
status().isBadRequest,
).andDo(
createPathDocument(
"get-winning-lotto-round-fail-user-id-negative",
pathParameters(
"round" pathDescription "μ‘°νν λΌμ΄λ μ 보(νμ¬ μ§νμ€μΈ λΌμ΄λκ° μλ)" example TEST_ROUND,
),
queryParameters(
USER_ID_PARAM parameterDescription "μμμ μ μ ID" example TEST_INVALID_USER_ID,
),
),
)
}
}
context("μμμ λΌμ΄λκ° μ£Όμ΄μ§ κ²½μ°") {
it("400 μλ΅νλ€.") {
restDocMockMvc.perform(
RestDocumentationRequestBuilders
.get(targetUri, TEST_INVALID_ROUND)
.param(USER_ID_PARAM, TEST_USER_ID.toString()),
).andExpect(
status().isBadRequest,
).andDo(
createPathDocument(
"get-winning-lotto-round-fail-round-negative",
pathParameters(
"round" pathDescription "μμμ μ‘°νν λΌμ΄λ μ 보" example TEST_INVALID_ROUND,
),
queryParameters(
USER_ID_PARAM parameterDescription "μ μ ID" example TEST_USER_ID,
),
),
)
}
}
context("μ‘΄μ¬νμ§ μλ λΌμ΄λκ° μ£Όμ΄μ§ κ²½μ°") {
coEvery {
winningLottoService.getWinningLottoByRound(
TEST_USER_ID,
TEST_NOT_EXIST_ROUND,
)
} throws NoSuchElementException("$TEST_NOT_EXIST_ROUND λΌμ΄λμ ν΄λΉνλ λΉμ²¨ λ²νΈκ° μ‘΄μ¬νμ§ μμ΅λλ€.")
it("404 μλ΅νλ€.") {
restDocMockMvc.perform(
RestDocumentationRequestBuilders
.get(targetUri, TEST_NOT_EXIST_ROUND)
.param(USER_ID_PARAM, TEST_USER_ID.toString()),
).andExpect(
status().isNotFound,
).andDo(
createPathDocument(
"get-winning-lotto-round-fail-round-not-exist",
pathParameters(
"round" pathDescription "μ‘΄μ¬νμ§ μλ λΌμ΄λ μ 보" example TEST_NOT_EXIST_ROUND,
),
queryParameters(
USER_ID_PARAM parameterDescription "μ μ ID" example TEST_USER_ID,
),
),
)
}
}
}
describe("GET /api/v1/winninglotto/{round}/match") {
val targetUri = "/api/v1/winninglotto/{round}/match"
context("μ ν¨ν λ°μ΄ν°κ° μ£Όμ΄μ§ κ²½μ°") {
val response = createTotalMatchResponse()
coEvery { winningLottoService.matchUserLottoByRound(TEST_USER_ID, TEST_ROUND) } returns response
it("200 μλ΅νλ€.") {
restDocMockMvc.perform(
RestDocumentationRequestBuilders
.get(targetUri, TEST_ROUND)
.param(USER_ID_PARAM, TEST_USER_ID.toString()),
).andExpect(
status().isOk,
).andDo(
createPathDocument(
"match-user-lotto-success",
pathParameters(
"round" pathDescription "μ‘°νν λΌμ΄λ μ 보(νμ¬ μ§νμ€μΈ λΌμ΄λ μλ!)" example TEST_ROUND,
),
queryParameters(
USER_ID_PARAM parameterDescription "ν΄λΉ λΌμ΄λμ λ§€μΉν μΌλ° μ μ ID" example TEST_USER_ID,
),
responseBody(
"size" type JsonFieldType.NUMBER description "λΉμ²¨λ λ‘λ κ°μ" example response.size,
"matchResult[].numbers" type JsonFieldType.ARRAY description "λΉμ²¨λ μ μ μ λ‘λ λ²νΈ" example response.matchResult[0].numbers,
"matchResult[].matched" type JsonFieldType.ARRAY description "ν΄λΉ λΌμ΄λμ λΉμ²¨ λ²νΈμ κ²ΉμΉλ λ‘λ λ²νΈ" example response.matchResult[0].matched,
"matchResult[].rankString" type JsonFieldType.STRING description "λ±μ λ¬Έμμ΄" example response.matchResult[0].rankString,
"matchResult[].prize" type JsonFieldType.NUMBER description "μ»μ μκΈ" example response.matchResult[0].prize,
),
),
)
}
}
context("μμμ μ μ IDκ° μ£Όμ΄μ§ κ²½μ°") {
it("400 μλ΅νλ€.") {
restDocMockMvc.perform(
RestDocumentationRequestBuilders
.get(targetUri, TEST_ROUND)
.param(USER_ID_PARAM, TEST_INVALID_USER_ID.toString()),
).andExpect(
status().isBadRequest,
).andDo(
createPathDocument(
"match-user-lotto-fail-user-id-negative",
pathParameters(
"round" pathDescription "μ‘°νν λΌμ΄λ μ 보(νμ¬ μ§νμ€μΈ λΌμ΄λ μλ!)" example TEST_ROUND,
),
queryParameters(
USER_ID_PARAM parameterDescription "μμμ μ μ ID" example TEST_INVALID_USER_ID,
),
),
)
}
}
context("μμμ λΌμ΄λκ° μ£Όμ΄μ§ κ²½μ°") {
it("400 μλ΅νλ€.") {
restDocMockMvc.perform(
RestDocumentationRequestBuilders
.get(targetUri, TEST_INVALID_ROUND)
.param(USER_ID_PARAM, TEST_USER_ID.toString()),
).andExpect(
status().isBadRequest,
).andDo(
createPathDocument(
"match-user-lotto-fail-round-negative",
pathParameters(
"round" pathDescription "μμμ λΌμ΄λ μ 보" example TEST_INVALID_ROUND,
),
queryParameters(
USER_ID_PARAM parameterDescription "μ‘°νν μ μ ID" example TEST_USER_ID,
),
),
)
}
}
context("μ‘΄μ¬νμ§ μλ λΌμ΄λκ° μ£Όμ΄μ§ κ²½μ°") {
coEvery {
winningLottoService.matchUserLottoByRound(
TEST_USER_ID,
TEST_NOT_EXIST_ROUND,
)
} throws IllegalArgumentException("μ‘΄μ¬νμ§ μλ λΌμ΄λλ μ‘°νν μ μμ΅λλ€.")
it("400 μλ΅νλ€.") {
restDocMockMvc.perform(
RestDocumentationRequestBuilders
.get(targetUri, TEST_NOT_EXIST_ROUND)
.param(USER_ID_PARAM, TEST_USER_ID.toString()),
).andExpect(
status().isBadRequest,
).andDo(
createPathDocument(
"match-user-lotto-fail-round-not-exist",
pathParameters(
"round" pathDescription "μ‘΄μ¬νμ§ μλ λΌμ΄λ μ 보" example TEST_NOT_EXIST_ROUND,
),
queryParameters(
USER_ID_PARAM parameterDescription "μ‘°νν μ μ ID" example TEST_USER_ID,
),
),
)
}
}
context("μ ν¨ν λΌμ΄λμ§λ§, Admin μ μ IDκ° μ£Όμ΄μ§ κ²½μ°") {
coEvery {
winningLottoService.matchUserLottoByRound(
TEST_ADMIN_USER_ID,
TEST_ROUND,
)
} throws IllegalStateException("μ£Όμ΄μ§ μ μ IDλ λ§€μΉν μ μμ΅λλ€.")
it("400 μλ΅νλ€.") {
restDocMockMvc.perform(
RestDocumentationRequestBuilders
.get(targetUri, TEST_ROUND)
.param(USER_ID_PARAM, TEST_ADMIN_USER_ID.toString()),
).andExpect(
status().isBadRequest,
).andDo(
createPathDocument(
"match-user-lotto-fail-user-id-admin",
pathParameters(
"round" pathDescription "μ‘°νν λΌμ΄λ μ 보" example TEST_ROUND,
),
queryParameters(
USER_ID_PARAM parameterDescription "Admin μ μ ID" example TEST_ADMIN_USER_ID,
),
),
)
}
}
context("μΌλ° μ μ IDμ§λ§, νμ¬ μ§ν μ€μΈ λΌμ΄λλ₯Ό μ‘°ννλ €λ κ²½μ°") {
coEvery {
winningLottoService.matchUserLottoByRound(
TEST_USER_ID,
TEST_ROUND,
)
} throws IllegalArgumentException("νμ¬ μ§νμ€μΈ λΌμ΄λλ μ‘°νν μ μμ΅λλ€.")
it("400 μλ΅νλ€.") {
restDocMockMvc.perform(
RestDocumentationRequestBuilders
.get(targetUri, TEST_ROUND)
.param(USER_ID_PARAM, TEST_USER_ID.toString()),
).andExpect(
status().isBadRequest,
).andDo(
createPathDocument(
"match-user-lotto-fail-user-access-current-round",
pathParameters(
"round" pathDescription "μ‘°νν λΌμ΄λ μ 보" example TEST_ROUND,
),
queryParameters(
USER_ID_PARAM parameterDescription "μ‘°νν μΌλ° μ μ ID" example TEST_USER_ID,
),
),
)
}
}
}
afterTest {
restDocumentation.afterTest()
}
},
)
| HyeonminShin-LottoSpring/src/test/kotlin/com/hm/hyeonminshinlottospring/domain/winninglotto/cotroller/WinningLottoControllerTest.kt | 245658613 |
package com.hm.hyeonminshinlottospring.domain.winninglotto.service
import com.hm.hyeonminshinlottospring.domain.lotto.repository.LottoRepository
import com.hm.hyeonminshinlottospring.domain.lotto.service.generator.RandomLottoNumbersGenerator
import com.hm.hyeonminshinlottospring.domain.user.repository.UserRepository
import com.hm.hyeonminshinlottospring.domain.user.repository.findByUserId
import com.hm.hyeonminshinlottospring.domain.winninglotto.domain.WinningLotto
import com.hm.hyeonminshinlottospring.domain.winninglotto.domain.WinningLottoInformation
import com.hm.hyeonminshinlottospring.domain.winninglotto.repository.WinningLottoRepository
import com.hm.hyeonminshinlottospring.support.TEST_ADMIN_USER_ID
import com.hm.hyeonminshinlottospring.support.TEST_INVALID_ROUND
import com.hm.hyeonminshinlottospring.support.TEST_ROUND
import com.hm.hyeonminshinlottospring.support.createAdmin
import com.hm.hyeonminshinlottospring.support.createAllLotto
import com.hm.hyeonminshinlottospring.support.createLotto
import com.hm.hyeonminshinlottospring.support.createUser
import io.kotest.assertions.throwables.shouldNotThrowAny
import io.kotest.assertions.throwables.shouldThrowExactly
import io.kotest.core.spec.style.DescribeSpec
import io.mockk.coEvery
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.sync.Mutex
class WinningLottoServiceTest : DescribeSpec(
{
val winningLottoInformation = mockk<WinningLottoInformation>()
val randomLottoNumbersGenerator = mockk<RandomLottoNumbersGenerator>()
val lottoRepository = mockk<LottoRepository>()
val winningLottoRepository = mockk<WinningLottoRepository>()
val userRepository = mockk<UserRepository>()
val winningLottoService =
WinningLottoService(
winningLottoInformation,
lottoRepository,
winningLottoRepository,
userRepository,
)
describe("getWinningLottoByRound") {
val user = createUser()
val admin = createAdmin()
context("Adminμ΄ μμ²ν λ") {
val lotto = createLotto(admin)
val winLotto =
WinningLotto(
round = TEST_ROUND,
lotto = lotto,
)
every { userRepository.findByUserId(any()) } returns admin
every { winningLottoInformation.round } returns TEST_ROUND
coEvery { winningLottoInformation.roundMutex } returns Mutex()
it("μ μ μ’
λ£: μ‘΄μ¬νλ λΌμ΄λ") {
every { winningLottoRepository.findByRound(any()) } returns winLotto
shouldNotThrowAny {
winningLottoService.getWinningLottoByRound(TEST_ADMIN_USER_ID, TEST_ROUND)
}
}
it("[IllegalArgumentException] μμΈ λ°μ: μ‘΄μ¬νμ§ μλ λΌμ΄λ") {
shouldThrowExactly<IllegalArgumentException> {
winningLottoService.getWinningLottoByRound(TEST_ADMIN_USER_ID, TEST_INVALID_ROUND)
}
}
}
context("μΌλ° μ μ κ° μμ²ν λ") {
val lotto = createLotto(user)
val winLotto =
WinningLotto(
round = TEST_ROUND,
lotto = lotto,
)
every { userRepository.findByUserId(any()) } returns user
every { winningLottoInformation.round } returns TEST_ROUND
coEvery { winningLottoInformation.roundMutex } returns Mutex()
it("μ μ μ’
λ£: νμ¬ λΌμ΄λ μ΄μ λΌμ΄λ μ κ·Ό") {
every { winningLottoRepository.findByRound(any()) } returns winLotto
shouldNotThrowAny {
winningLottoService.getWinningLottoByRound(user.id, TEST_ROUND - 1)
}
}
it("[IllegalArgumentException] μμΈ λ°μ: νμ¬ λΌμ΄λ μ κ·Όμ") {
shouldThrowExactly<IllegalArgumentException> {
winningLottoService.getWinningLottoByRound(user.id, TEST_ROUND)
}
}
it("[IllegalArgumentException] μμΈ λ°μ: μ‘΄μ¬νμ§ μλ λΌμ΄λ") {
shouldThrowExactly<IllegalArgumentException> {
winningLottoService.getWinningLottoByRound(user.id, TEST_INVALID_ROUND)
}
}
}
}
describe("matchUserLottoByRound") {
val user = createUser()
val admin = createAdmin()
val winLotto =
WinningLotto(
round = TEST_ROUND,
lotto = createLotto(admin),
)
context("μ ν¨ν λ°μ΄ν°κ° μ£Όμ΄μ§ κ²½μ°") {
every { userRepository.findByUserId(any()) } returns user
every { winningLottoInformation.round } returns TEST_ROUND + 1
every { lottoRepository.findListByUserIdAndRound(user.id, TEST_ROUND) } returns createAllLotto(user)
every { winningLottoRepository.findByRound(TEST_ROUND) } returns winLotto
it("μ μ μ’
λ£") {
shouldNotThrowAny {
winningLottoService.matchUserLottoByRound(user.id, TEST_ROUND)
}
}
}
context("μ μ κ° ν΄λΉ λΌμ΄λμ ꡬ맀ν λ‘λκ° μμ κ²½μ°") {
every { userRepository.findByUserId(any()) } returns user
every { winningLottoInformation.round } returns TEST_ROUND + 1
every { lottoRepository.findListByUserIdAndRound(user.id, TEST_ROUND) } returns emptyList()
it("[IllegalStateException] μμΈ λ°μ") {
shouldThrowExactly<IllegalStateException> {
winningLottoService.matchUserLottoByRound(user.id, TEST_ROUND)
}
}
}
// TODO: Admin κ΄λ ¨ μΆκ°ν΄μΌ ν¨
}
},
)
| HyeonminShin-LottoSpring/src/test/kotlin/com/hm/hyeonminshinlottospring/domain/winninglotto/service/WinningLottoServiceTest.kt | 1377755084 |
package com.hm.hyeonminshinlottospring.domain.winninglotto.domain
import com.hm.hyeonminshinlottospring.domain.lotto.repository.LottoRepository
import com.hm.hyeonminshinlottospring.support.TEST_ROUND
import com.hm.hyeonminshinlottospring.support.createLotto
import com.hm.hyeonminshinlottospring.support.createUser
import io.kotest.core.spec.style.ExpectSpec
import io.kotest.matchers.shouldBe
import io.mockk.every
import io.mockk.mockk
class WinningLottoInformationTest : ExpectSpec(
{
val lottoRepository = mockk<LottoRepository>()
context("μ΄μ λΌμ΄λ μ λ³΄κ° μ‘΄μ¬νμ§ μμ λ") {
every { lottoRepository.findFirstByOrderByRoundDesc() } returns null
val winningLottoInformation = WinningLottoInformation(lottoRepository)
expect("round 1 λΆν° μμ") {
winningLottoInformation.round shouldBe 1
}
}
context("μ΄μ λΌμ΄λ μ λ³΄κ° μ‘΄μ¬ν λ") {
every { lottoRepository.findFirstByOrderByRoundDesc() } returns createLotto(createUser())
val winningLottoInformation = WinningLottoInformation(lottoRepository)
expect("λ§μ§λ§ round λ€μλΆν° μμ") {
winningLottoInformation.round shouldBe TEST_ROUND + 1
}
}
},
)
| HyeonminShin-LottoSpring/src/test/kotlin/com/hm/hyeonminshinlottospring/domain/winninglotto/domain/WinningLottoInformationTest.kt | 1107232796 |
package com.hm.hyeonminshinlottospring
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.properties.ConfigurationPropertiesScan
import org.springframework.boot.runApplication
@ConfigurationPropertiesScan
@SpringBootApplication
class HyeonminShinLottoSpringApplication
fun main(args: Array<String>) {
runApplication<HyeonminShinLottoSpringApplication>(*args)
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/HyeonminShinLottoSpringApplication.kt | 3861212931 |
package com.hm.hyeonminshinlottospring.domain.user.dto
import com.hm.hyeonminshinlottospring.domain.user.domain.User
import com.hm.hyeonminshinlottospring.domain.user.domain.UserRole
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.NotNull
import jakarta.validation.constraints.PositiveOrZero
data class UserCreateRequest(
@field:NotBlank(message = "μ μ μ΄λ¦μ νμ μ
λ ₯ κ°μ
λλ€.")
val userName: String,
@field:NotNull(message = "λμ νμ μ
λ ₯ κ°μ
λλ€.")
@field:PositiveOrZero(message = "λμ νμ 0 μ΄μμ μ μμ¬μΌ ν©λλ€.")
val money: Int,
val userRole: UserRole?,
) {
fun toEntity() =
User(
userName = this.userName,
money = this.money,
userRole = this.userRole ?: UserRole.ROLE_USER,
)
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/user/dto/UserCreateRequest.kt | 636257082 |
package com.hm.hyeonminshinlottospring.domain.user.dto
import com.hm.hyeonminshinlottospring.domain.user.domain.User
import com.hm.hyeonminshinlottospring.domain.user.domain.UserRole
data class UserResponse(
val userName: String,
val userRole: UserRole,
val money: Int,
) {
companion object {
fun from(user: User) =
UserResponse(
userName = user.userName,
userRole = user.userRole,
money = user.money,
)
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/user/dto/UserResponse.kt | 1569638561 |
package com.hm.hyeonminshinlottospring.domain.user.dto
import jakarta.validation.constraints.NotNull
import jakarta.validation.constraints.Positive
data class UserMoneyPatchRequest(
@field:NotNull(message = "μ μ IDλ νμ μ
λ ₯ κ°μ
λλ€.")
@field:Positive(message = "μ μ IDλ 0λ³΄λ€ μ»€μΌ ν©λλ€.")
val userId: Long,
@field:NotNull(message = "ν¬μ
ν λμ νμ μ
λ ₯ κ°μ
λλ€.")
@field:Positive(message = "ν¬μ
ν λμ μμμ¬μΌ ν©λλ€.")
val money: Int,
)
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/user/dto/UserMoneyPatchRequest.kt | 167280947 |
package com.hm.hyeonminshinlottospring.domain.user.repository
import com.hm.hyeonminshinlottospring.domain.user.domain.User
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Repository
fun UserRepository.findByUserId(userId: Long): User = findByIdOrNull(userId) ?: throw NoSuchElementException("$userId: μ¬μ©μκ° μ‘΄μ¬νμ§ μμ΅λλ€.")
@Repository
interface UserRepository : JpaRepository<User, Long> {
fun existsByUserName(userName: String): Boolean
fun findByUserName(userName: String): User?
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/user/repository/UserRepository.kt | 3754887084 |
package com.hm.hyeonminshinlottospring.domain.user.controller
import com.hm.hyeonminshinlottospring.domain.user.dto.UserCreateRequest
import com.hm.hyeonminshinlottospring.domain.user.dto.UserMoneyPatchRequest
import com.hm.hyeonminshinlottospring.domain.user.dto.UserResponse
import com.hm.hyeonminshinlottospring.domain.user.service.UserService
import jakarta.validation.Valid
import jakarta.validation.constraints.Positive
import org.springframework.http.ResponseEntity
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PatchMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.net.URI
@Validated
@RestController
@RequestMapping("/api/v1/user")
class UserController(
private val userService: UserService,
) {
@PostMapping
fun createUser(
@Valid
@RequestBody
userCreateRequest: UserCreateRequest,
): ResponseEntity<Void> {
val userId = userService.createUser(userCreateRequest)
return ResponseEntity.created(URI.create("/api/v1/user/$userId")).build()
}
@GetMapping("/{userId}")
fun getUserInformation(
@Positive(message = "μ μ IDλ 0λ³΄λ€ μ»€μΌ ν©λλ€.")
@PathVariable("userId")
userId: Long,
): ResponseEntity<UserResponse> {
val response = userService.getUserInformation(userId)
return ResponseEntity.ok(response)
}
@PatchMapping("/addMoney")
fun addUserMoney(
@Valid
@RequestBody
userMoneyPatchRequest: UserMoneyPatchRequest,
): ResponseEntity<Void> {
userService.addUserMoney(userMoneyPatchRequest)
return ResponseEntity.noContent().build()
}
@PatchMapping("/withdrawMoney")
fun withdrawUserMoney(
@Valid
@RequestBody
userMoneyPatchRequest: UserMoneyPatchRequest,
): ResponseEntity<Void> {
userService.withdrawUserMoney(userMoneyPatchRequest)
return ResponseEntity.noContent().build()
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/user/controller/UserController.kt | 2602683703 |
package com.hm.hyeonminshinlottospring.domain.user.service
import com.hm.hyeonminshinlottospring.domain.user.dto.UserCreateRequest
import com.hm.hyeonminshinlottospring.domain.user.dto.UserMoneyPatchRequest
import com.hm.hyeonminshinlottospring.domain.user.dto.UserResponse
import com.hm.hyeonminshinlottospring.domain.user.repository.UserRepository
import com.hm.hyeonminshinlottospring.domain.user.repository.findByUserId
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
class UserService(
private val userRepository: UserRepository,
) {
// TODO: λμ€μ λ°μμ Admin "λ§λ€μ§λ, μ κ·Όνμ§λ λͺ»νλλ‘" μΈμ¦ μμ€ν
λμ
νκΈ°
fun createUser(request: UserCreateRequest): Long {
val savedUser = userRepository.save(request.toEntity())
return savedUser.id
}
fun getUserInformation(userId: Long): UserResponse {
val user = userRepository.findByUserId(userId)
return UserResponse.from(user)
}
@Transactional
fun addUserMoney(request: UserMoneyPatchRequest): Int {
val user = userRepository.findByUserId(request.userId)
return user.addMoney(request.money)
}
@Transactional
fun withdrawUserMoney(request: UserMoneyPatchRequest): Int {
val user = userRepository.findByUserId(request.userId)
return user.withdrawMoney(request.money)
}
// TODO: User μμ μΆκ°
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/user/service/UserService.kt | 1393442018 |
package com.hm.hyeonminshinlottospring.domain.user.domain
enum class UserRole(val description: String) {
ROLE_USER("μ¬μ©μ"),
ROLE_ADMIN("κ΄λ¦¬μ"),
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/user/domain/UserRole.kt | 2795320969 |
package com.hm.hyeonminshinlottospring.domain.user.domain
import com.hm.hyeonminshinlottospring.domain.lotto.domain.info.LottoPrice
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.EnumType
import jakarta.persistence.Enumerated
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.Table
@Table(name = "users")
@Entity
class User(
// νμ¬λ μ μ κ° μ΄λ¦μΌλ‘ ꡬλΆλμ΄μ§κ²λ λ§λ€μμ΅λλ€. μ΄ν λ‘κ·ΈμΈ IDλ‘ κ΅¬λΆνλ©΄ μ’μκ² κ°μ΅λλ€.
@Column(nullable = false, updatable = false, unique = true)
val userName: String,
@Enumerated(EnumType.STRING)
@Column(nullable = false)
val userRole: UserRole = UserRole.ROLE_USER,
money: Int = 0,
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0L,
) {
@Column(nullable = false)
var money: Int = money
protected set
fun addMoney(addMoney: Int): Int {
require(addMoney > 0) { "0μ μ΄μμ κΈμ‘μ μ
λ ₯ν΄μ£ΌμΈμ." }
money += addMoney
return money
}
fun withdrawMoney(withdrawMoney: Int): Int {
require(withdrawMoney > 0) { "μΆκΈν κ°μ μμλ‘ μ
λ ₯ν΄μ£ΌμΈμ." }
require(withdrawMoney <= money) { "${this.id}: νμ¬ μμ§ν κΈμ‘($money${LottoPrice.UNIT})λ³΄λ€ μ κ±°λ κ°μ κΈμ‘μ μ
λ ₯ν΄μ£ΌμΈμ." }
money -= withdrawMoney
return money
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/user/domain/User.kt | 3245809067 |
package com.hm.hyeonminshinlottospring.domain.lotto.dto
import com.hm.hyeonminshinlottospring.domain.lotto.domain.Lotto
import com.hm.hyeonminshinlottospring.domain.user.domain.User
import org.springframework.data.domain.Slice
data class SliceLottoNumberResponse(
val userId: Long?,
val round: Int?,
val hasNext: Boolean,
val numberOfElements: Int,
val numberList: List<String>,
) {
companion object {
fun from(slice: Slice<Lotto>): SliceLottoNumberResponse {
val lotto1: Lotto? = if (slice.numberOfElements != 0) slice.content[0] else null
val user: User? = lotto1?.user
return SliceLottoNumberResponse(
userId = user?.id,
round = lotto1?.round,
hasNext = slice.hasNext(),
numberOfElements = slice.numberOfElements,
numberList = slice.content.map {
it.numbers.toString()
},
)
}
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/lotto/dto/SliceLottoNumberResponse.kt | 2158747310 |
package com.hm.hyeonminshinlottospring.domain.lotto.dto
import com.hm.hyeonminshinlottospring.domain.lotto.domain.GenerateMode
import jakarta.validation.constraints.NotNull
import jakarta.validation.constraints.Positive
data class LottoCreateRequest(
@field:NotNull(message = "μ μ IDλ νμ μ
λ ₯ κ°μ
λλ€.")
@field:Positive(message = "μ μ IDλ 0λ³΄λ€ μ»€μΌ ν©λλ€.")
val userId: Long,
@field:NotNull(message = "μμ± λͺ¨λλ νμ μ
λ ₯ κ°μ
λλ€.")
val mode: GenerateMode,
@field:NotNull(message = "ν¬μ
ν λμ νμ μ
λ ₯ κ°μ
λλ€.")
@field:Positive(message = "ν¬μ
ν λμ μμμ¬μΌ ν©λλ€.")
val insertedMoney: Int,
val numbers: List<List<Int>>? = null,
)
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/lotto/dto/LottoCreateRequest.kt | 321426208 |
package com.hm.hyeonminshinlottospring.domain.lotto.dto
data class LottoCreateResponse(
val userId: Long,
val round: Int,
val createdLottoCount: Int,
)
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/lotto/dto/LottoCreateResponse.kt | 788156690 |
package com.hm.hyeonminshinlottospring.domain.lotto.repository
import com.hm.hyeonminshinlottospring.domain.lotto.domain.Lotto
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Slice
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Repository
fun LottoRepository.findByLottoId(lottoId: Long): Lotto =
findByIdOrNull(lottoId) ?: throw NoSuchElementException("$lottoId: ν΄λΉ λ‘λκ° μ‘΄μ¬νμ§ μμ΅λλ€.")
@Repository
interface LottoRepository : JpaRepository<Lotto, Long> {
fun findSliceByUserId(
userId: Long,
pageable: Pageable,
): Slice<Lotto>
fun findSliceByRound(
round: Int,
pageable: Pageable,
): Slice<Lotto>
fun findSliceByUserIdAndRound(
userId: Long,
round: Int,
pageable: Pageable,
): Slice<Lotto>
fun findListByUserIdAndRound(
userId: Long,
round: Int,
): List<Lotto>
fun findFirstByOrderByRoundDesc(): Lotto?
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/lotto/repository/LottoRepository.kt | 3698302922 |
package com.hm.hyeonminshinlottospring.domain.lotto.controller
import com.hm.hyeonminshinlottospring.domain.lotto.dto.LottoCreateRequest
import com.hm.hyeonminshinlottospring.domain.lotto.dto.LottoCreateResponse
import com.hm.hyeonminshinlottospring.domain.lotto.dto.SliceLottoNumberResponse
import com.hm.hyeonminshinlottospring.domain.lotto.service.LottoService
import jakarta.validation.Valid
import jakarta.validation.constraints.Positive
import org.springframework.data.domain.Pageable
import org.springframework.data.web.PageableDefault
import org.springframework.http.ResponseEntity
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.net.URI
@Validated
@RestController
@RequestMapping("/api/v1/lotto")
class LottoController(
private val lottoService: LottoService,
) {
@PostMapping
fun createLottos(
@Valid
@RequestBody
lottoCreateRequest: LottoCreateRequest,
): ResponseEntity<LottoCreateResponse> {
val response = lottoService.createLottos(lottoCreateRequest)
return ResponseEntity.created(URI.create("/api/v1/lotto/${response.userId}"))
.body(response)
}
@GetMapping("/{userId}")
fun getlottosByUserAndRound(
@Positive(message = "μ μ IDλ 0λ³΄λ€ μ»€μΌ ν©λλ€.")
@PathVariable("userId")
userId: Long,
@Positive(message = "λΌμ΄λλ μμμ¬μΌ ν©λλ€.")
@RequestParam("round")
round: Int,
@PageableDefault(page = 0, size = 10)
pageable: Pageable,
): ResponseEntity<SliceLottoNumberResponse> {
val response = lottoService.getLottosByUserAndRound(userId, round, pageable)
return ResponseEntity.ok(response)
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/lotto/controller/LottoController.kt | 2548147208 |
package com.hm.hyeonminshinlottospring.domain.lotto.service
import com.hm.hyeonminshinlottospring.domain.lotto.domain.GenerateMode
import com.hm.hyeonminshinlottospring.domain.lotto.domain.Lotto
import com.hm.hyeonminshinlottospring.domain.lotto.domain.LottoNumbers
import com.hm.hyeonminshinlottospring.domain.lotto.domain.info.LottoPrice
import com.hm.hyeonminshinlottospring.domain.lotto.dto.LottoCreateRequest
import com.hm.hyeonminshinlottospring.domain.lotto.dto.LottoCreateResponse
import com.hm.hyeonminshinlottospring.domain.lotto.dto.SliceLottoNumberResponse
import com.hm.hyeonminshinlottospring.domain.lotto.repository.LottoRepository
import com.hm.hyeonminshinlottospring.domain.lotto.service.generator.RandomLottoNumbersGenerator
import com.hm.hyeonminshinlottospring.domain.user.domain.User
import com.hm.hyeonminshinlottospring.domain.user.domain.UserRole
import com.hm.hyeonminshinlottospring.domain.user.repository.UserRepository
import com.hm.hyeonminshinlottospring.domain.user.repository.findByUserId
import com.hm.hyeonminshinlottospring.domain.winninglotto.domain.WinningLottoInformation
import com.hm.hyeonminshinlottospring.global.config.LOOM
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.withLock
import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
class LottoService(
private val randomLottoNumbersGenerator: RandomLottoNumbersGenerator,
private val winningLottoInformation: WinningLottoInformation,
private val lottoRepository: LottoRepository,
private val userRepository: UserRepository,
) {
/**
* ### μ£Όμν΄μΌν μ
*
* Springμ Transactionalμ AOP κΈ°λ°μΌλ‘ λμνλλ° λ΄λΆμ μΌλ‘ μλ 컀λ°μ λΉνμ±ννκ³ νΈλμμ
μ μμνλ€.
* νμ§λ§ ν΄λΉ 컀λ₯μ
μ νλμ μ€λ λμμ 곡μ ν μ μλ ThreadLocal λ³μλ₯Ό μ¬μ©νλλ°,
* μ΄κ²μ 'λ¨μΌ μ€λ λ' λ΄μμλ§ μ ν¨νλ€.
*
* λ°λΌμ μ΄λ₯Ό ν΄κ²°νκΈ° μν λ°©λ²μΌλ‘ λ€μ 2κ°μ§κ° μμ κ²μ΄λ€.
* 1. νΈλμμ
μ΄ λ°μνλ λΆλΆκ³Ό λΉμ¦λμ€ λ‘μ§(λΉλκΈ° λΆλΆ)μ λΆλ¦¬νκΈ°
* - @Transactionalμ΄ λΆμΌλ©΄ ν΄λΉ ν¨μλ₯Ό suspendλ‘ λ§λ€μ΄μ μλλ€. κ·Έλ μ§ μμΌλ©΄ Dirty Checking μλ€.
* 2. λ λΆλΆμ ν©μΉλ€λ©΄, νΈλμμ
μ λ€λ£¨λ λΆλΆ(λ‘€λ°±μ ν¬ν¨ν¨)κ³Ό DB lock λΆλΆμ μΈλ°ν μ‘°μ ν κ²
*
* μλλ λ‘λ λ²νΈ μμ± λΆλΆλ§μ coroutineμΌλ‘ λΉλκΈ° μ²λ¦¬νλ€.
*/
@Transactional
fun createLottos(
request: LottoCreateRequest,
): LottoCreateResponse = runBlocking {
val userId = request.userId
val user = userRepository.findByUserId(userId)
check(request.insertedMoney <= user.money) { "${request.userId}: νμ¬ μμ§ν κΈμ‘(${user.money}${LottoPrice.UNIT})λ³΄λ€ μ μ κΈμ‘μ μ
λ ₯ν΄μ£ΌμΈμ." }
val generateCount = request.insertedMoney / LottoPrice.PER_PRICE
val round = winningLottoInformation.roundMutex.withLock {
winningLottoInformation.round
}
val lottoListDeferred = async(Dispatchers.LOOM) {
when (request.mode) {
GenerateMode.MANUAL -> createManualLottos(request, round, user)
GenerateMode.RANDOM -> createRandomLottos(generateCount, round, user)
}
}
val savedLottos = lottoRepository.saveAll(lottoListDeferred.await())
val successCount = savedLottos.size
user.withdrawMoney(successCount * LottoPrice.PER_PRICE)
LottoCreateResponse(userId, round, successCount)
}
@Transactional(readOnly = true)
fun getLottosByUserAndRound(
userId: Long,
round: Int,
pageable: Pageable,
): SliceLottoNumberResponse {
val user = userRepository.findByUserId(userId)
check(user.userRole != UserRole.ROLE_ADMIN) { "$userId: μ£Όμ΄μ§ μ μ IDλ μ‘°νν μ μμ΅λλ€." }
val slice = lottoRepository.findSliceByUserIdAndRound(userId, round, pageable)
return SliceLottoNumberResponse.from(slice)
}
private suspend fun createManualLottos(
request: LottoCreateRequest,
round: Int,
user: User,
) = request.numbers?.asFlow()
?.mapNotNull {
try {
Lotto(
round = round,
user = user,
numbers = it,
)
} catch (e: Exception) {
null
}
}
?.toList()
?: emptyList()
private suspend fun createRandomLottos(
generateCount: Int,
round: Int,
user: User,
): List<Lotto> = coroutineScope {
val resultDeferred = List(generateCount) {
async {
Lotto(
round = round,
user = user,
numbers = randomLottoNumbersGenerator.generate(),
)
}
}
resultDeferred.awaitAll()
}
/**
* ν
μ€νΈ μ μ±λ₯ λΉκ΅μ© λ κ±°μ μ½λ.
* pr merge λκΈ° μ μ μ§μΈ μμ !
*/
@Transactional
@Deprecated("Blocking IO method")
fun createLottosLegacy(
request: LottoCreateRequest,
): LottoCreateResponse {
val userId = request.userId
val user = userRepository.findByUserId(userId)
user.withdrawMoney(request.insertedMoney)
val round = winningLottoInformation.round
val savedLottos = lottoRepository.saveAll(request.toEntities(user, round))
return LottoCreateResponse(userId, round, savedLottos.size)
}
/**
* ν
μ€νΈμ© λ κ±°μ μ½λ 2.
* μ§μΈ μμ !
*/
@Deprecated("Blocking IO method")
private fun LottoCreateRequest.toEntities(
user: User,
round: Int,
): List<Lotto> {
val result = mutableListOf<Lotto>()
val generateCount = this.insertedMoney / LottoPrice.PER_PRICE
when (this.mode) {
GenerateMode.RANDOM ->
repeat(generateCount) {
result.add(
Lotto(
round = round,
user = user,
numbers =
(LottoNumbers.LOTTO_MIN_NUMBER..LottoNumbers.LOTTO_MAX_NUMBER)
.shuffled()
.take(LottoNumbers.NUM_OF_LOTTO_NUMBERS),
),
)
}
GenerateMode.MANUAL -> {
val numbersIterator = this.numbers?.listIterator() ?: listOf<List<Int>>().listIterator()
while (numbersIterator.hasNext()) {
result.add(
Lotto(
round = round,
user = user,
numbers = numbersIterator.next(),
),
)
}
}
}
return result.toList()
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/lotto/service/LottoService.kt | 4170440287 |
package com.hm.hyeonminshinlottospring.domain.lotto.service.generator
import com.hm.hyeonminshinlottospring.domain.lotto.domain.LottoNumbers
import org.springframework.stereotype.Component
@Component
class RandomLottoNumbersGenerator {
suspend fun generate() =
(LottoNumbers.LOTTO_MIN_NUMBER..LottoNumbers.LOTTO_MAX_NUMBER)
.shuffled()
.take(LottoNumbers.NUM_OF_LOTTO_NUMBERS)
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/lotto/service/generator/RandomLottoNumbersGenerator.kt | 403192187 |
package com.hm.hyeonminshinlottospring.domain.lotto.domain
import java.util.SortedSet
@JvmInline
value class LottoNumbers private constructor(private val numbers: SortedSet<Int>) {
init {
require(numbers.size == NUM_OF_LOTTO_NUMBERS) { "μ€λ³΅μ μ μΈν ${NUM_OF_LOTTO_NUMBERS}κ°μ λ²νΈκ° νμν©λλ€." }
require(numbers.all { it in VALID_RANGE }) { NUMBER_RANGE_ERROR_MESSAGE }
}
constructor(number: Collection<Int>) : this(number.toSortedSet())
fun joinToString() = this.numbers.joinToString(DELIMITER)
fun intersect(other: LottoNumbers) = this.numbers.intersect(other.numbers)
fun count(other: LottoNumbers) = this.numbers.count { it in other.numbers }
companion object {
const val LOTTO_MIN_NUMBER = 1
const val LOTTO_MAX_NUMBER = 45
const val NUM_OF_LOTTO_NUMBERS = 6
private val VALID_RANGE: IntRange = LOTTO_MIN_NUMBER..LOTTO_MAX_NUMBER
const val DELIMITER = ","
const val NUMBER_RANGE_ERROR_MESSAGE =
"λ‘λ λ²νΈλ [$LOTTO_MIN_NUMBER ~ $LOTTO_MAX_NUMBER] λ²μμ¬μΌ ν©λλ€."
@JvmStatic
fun from(number: Collection<Int>) = LottoNumbers(number.toSortedSet())
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/lotto/domain/LottoNumbers.kt | 1882071335 |
package com.hm.hyeonminshinlottospring.domain.lotto.domain.converter
import jakarta.persistence.AttributeConverter
import jakarta.persistence.Converter
import java.util.SortedSet
@Converter
class LottoNumberAttributeConverter : AttributeConverter<SortedSet<Int>, String> {
override fun convertToDatabaseColumn(entityValue: SortedSet<Int>?): String? {
return entityValue?.joinToString(",")
}
override fun convertToEntityAttribute(databaseValue: String?): SortedSet<Int>? {
return databaseValue?.split(",")?.map { it.toInt() }?.toSortedSet()
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/lotto/domain/converter/LottoNumberAttributeConverter.kt | 1996887760 |
package com.hm.hyeonminshinlottospring.domain.lotto.domain
enum class GenerateMode {
MANUAL,
RANDOM,
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/lotto/domain/GenerateMode.kt | 3547163524 |
package com.hm.hyeonminshinlottospring.domain.lotto.domain.info
class LottoPrice {
companion object CurrencyUnit {
const val PER_PRICE = 1
const val UNIT = "KW" // μΉ΄μΉ΄μ€ μ
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/lotto/domain/info/LottoPrice.kt | 3049354220 |
package com.hm.hyeonminshinlottospring.domain.lotto.domain.info
import com.hm.hyeonminshinlottospring.domain.lotto.domain.LottoNumbers
/**
* **ordinal**: λ±μλ₯Ό λνλ΄λ μ§νλ‘ μ¬μ© from 0
*/
enum class LottoRank(val rankString: String, val prize: Int) {
FIRST("1λ±", 100_000),
SECOND("2λ±", 5_000),
THIRD("3λ±", 100),
FOURTH("4λ±", 5),
LOSE("λ첨", 0),
;
companion object Checker {
fun getRank(countMatched: Int) = entries.getOrNull(LottoNumbers.NUM_OF_LOTTO_NUMBERS - countMatched) ?: LOSE
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/lotto/domain/info/LottoRank.kt | 1006601101 |
package com.hm.hyeonminshinlottospring.domain.lotto.domain
import com.hm.hyeonminshinlottospring.domain.lotto.domain.converter.LottoNumberAttributeConverter
import com.hm.hyeonminshinlottospring.domain.user.domain.User
import com.hm.hyeonminshinlottospring.global.support.doamin.BaseTimeEntity
import jakarta.persistence.Column
import jakarta.persistence.Convert
import jakarta.persistence.Entity
import jakarta.persistence.FetchType
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.Index
import jakarta.persistence.JoinColumn
import jakarta.persistence.ManyToOne
import jakarta.persistence.Table
// TODO: μ΅μ ν μ루μ
) numbersλ₯Ό bitsetμΌλ‘ λ€λ£¨κΈ°!!
@Table(
indexes = [
Index(name = "user_id_index", columnList = "user_id"),
],
)
@Entity
class Lotto(
@Column(nullable = false, updatable = false)
val round: Int,
@Convert(converter = LottoNumberAttributeConverter::class)
val numbers: LottoNumbers,
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", updatable = false)
val user: User,
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0L,
) : BaseTimeEntity() {
// TODO: bonus λ²νΈ νλ‘νΌν°λ₯Ό μΆκ°νκΈ°
constructor(
round: Int,
numbers: Collection<Int>,
user: User,
id: Long = 0L,
) : this(
round = round,
user = user,
numbers = LottoNumbers(numbers),
id = id,
)
fun match(other: Lotto): List<Int> {
val intersect = this.numbers.intersect(other.numbers)
return intersect.toList()
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/lotto/domain/Lotto.kt | 3576695355 |
package com.hm.hyeonminshinlottospring.domain.winninglotto.dto
import com.hm.hyeonminshinlottospring.domain.lotto.domain.LottoNumbers
import com.hm.hyeonminshinlottospring.domain.winninglotto.domain.WinningLotto
class WinningLottoRoundResponse(
val round: Int,
val numbers: LottoNumbers,
) {
companion object {
fun from(winningLotto: WinningLotto) =
WinningLottoRoundResponse(
round = winningLotto.round,
numbers = winningLotto.lotto.numbers,
)
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/winninglotto/dto/WinningLottoRoundResponse.kt | 4269525738 |
package com.hm.hyeonminshinlottospring.domain.winninglotto.dto
import com.hm.hyeonminshinlottospring.domain.lotto.domain.Lotto
import com.hm.hyeonminshinlottospring.domain.lotto.domain.LottoNumbers
import com.hm.hyeonminshinlottospring.domain.lotto.domain.info.LottoRank
class WinningLottoMatchResponse(
val numbers: LottoNumbers,
val matched: List<Int>,
val rankString: String,
val prize: Int,
) {
companion object {
fun from(
lotto: Lotto,
matched: List<Int>,
rank: LottoRank,
) = WinningLottoMatchResponse(
numbers = lotto.numbers,
matched = matched,
rankString = rank.rankString,
prize = rank.prize,
)
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/winninglotto/dto/WinningLottoMatchResponse.kt | 3475935042 |
package com.hm.hyeonminshinlottospring.domain.winninglotto.dto
data class TotalMatchResponse(
val size: Int,
val matchResult: List<WinningLottoMatchResponse>,
) {
companion object {
fun from(matchResult: List<WinningLottoMatchResponse>) =
TotalMatchResponse(
size = matchResult.size,
matchResult = matchResult,
)
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/winninglotto/dto/TotalMatchResponse.kt | 2455550625 |
package com.hm.hyeonminshinlottospring.domain.winninglotto.repository
import com.hm.hyeonminshinlottospring.domain.winninglotto.domain.WinningLotto
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
@Repository
interface WinningLottoRepository : JpaRepository<WinningLotto, Long> {
fun findByRound(round: Int): WinningLotto?
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/winninglotto/repository/WinningLottoRepository.kt | 434638098 |
package com.hm.hyeonminshinlottospring.domain.winninglotto.cotroller
import com.hm.hyeonminshinlottospring.domain.winninglotto.dto.TotalMatchResponse
import com.hm.hyeonminshinlottospring.domain.winninglotto.dto.WinningLottoRoundResponse
import com.hm.hyeonminshinlottospring.domain.winninglotto.service.WinningLottoService
import jakarta.validation.constraints.Positive
import org.springframework.http.ResponseEntity
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
@Validated
@RestController
@RequestMapping("/api/v1/winninglotto")
class WinningLottoController(
private val winningLottoService: WinningLottoService,
) {
@GetMapping("/{round}")
fun getWinningLottoByRound(
@Positive(message = "μ μ IDλ 0λ³΄λ€ μ»€μΌ ν©λλ€.")
@RequestParam("userId")
userId: Long,
@Positive(message = "λΌμ΄λλ μμμ¬μΌ ν©λλ€.")
@PathVariable("round")
round: Int,
): ResponseEntity<WinningLottoRoundResponse> {
val response = winningLottoService.getWinningLottoByRound(userId, round)
return ResponseEntity.ok(response)
}
@GetMapping("/{round}/match")
fun matchUserLottoByRound(
@Positive(message = "μ μ IDλ 0λ³΄λ€ μ»€μΌ ν©λλ€.")
@RequestParam("userId")
userId: Long,
@Positive(message = "λΌμ΄λλ μμμ¬μΌ ν©λλ€.")
@PathVariable("round")
round: Int,
): ResponseEntity<TotalMatchResponse> {
val response = winningLottoService.matchUserLottoByRound(userId, round)
return ResponseEntity.ok(response)
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/winninglotto/cotroller/WinningLottoController.kt | 3780568732 |
package com.hm.hyeonminshinlottospring.domain.winninglotto.service
import com.hm.hyeonminshinlottospring.domain.lotto.domain.Lotto
import com.hm.hyeonminshinlottospring.domain.lotto.repository.LottoRepository
import com.hm.hyeonminshinlottospring.domain.lotto.service.generator.RandomLottoNumbersGenerator
import com.hm.hyeonminshinlottospring.domain.user.domain.User
import com.hm.hyeonminshinlottospring.domain.user.domain.UserRole
import com.hm.hyeonminshinlottospring.domain.user.repository.UserRepository
import com.hm.hyeonminshinlottospring.domain.winninglotto.domain.WinningLotto
import com.hm.hyeonminshinlottospring.domain.winninglotto.domain.WinningLottoInformation
import com.hm.hyeonminshinlottospring.domain.winninglotto.repository.WinningLottoRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
@Component
class WinningLottoScheduler(
private val winningLottoInformation: WinningLottoInformation,
private val randomLottoNumbersGenerator: RandomLottoNumbersGenerator,
private val lottoRepository: LottoRepository,
private val userRepository: UserRepository,
private val winningLottoRepository: WinningLottoRepository,
) {
@Scheduled(cron = "\${schedule.cron}")
suspend fun createWinningLotto() {
coroutineScope {
withContext(Dispatchers.IO) {
winningLottoInformation.roundMutex.withLock {
val round = winningLottoInformation.round
winningLottoInformation.increaseRound()
val adminDeferred =
async {
userRepository.save(
User(
userName = "LG-R$round",
userRole = UserRole.ROLE_ADMIN,
),
)
}
val savedLottoDeferred =
async {
lottoRepository.save(
Lotto(
round = round,
user = adminDeferred.await(),
numbers = randomLottoNumbersGenerator.generate(),
),
)
}
launch {
winningLottoRepository.save(WinningLotto(round, savedLottoDeferred.await()))
}
}
}
}
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/winninglotto/service/WinningLottoScheduler.kt | 1410141784 |
package com.hm.hyeonminshinlottospring.domain.winninglotto.service
import com.hm.hyeonminshinlottospring.domain.lotto.domain.Lotto
import com.hm.hyeonminshinlottospring.domain.lotto.domain.info.LottoRank
import com.hm.hyeonminshinlottospring.domain.lotto.repository.LottoRepository
import com.hm.hyeonminshinlottospring.domain.user.domain.UserRole
import com.hm.hyeonminshinlottospring.domain.user.repository.UserRepository
import com.hm.hyeonminshinlottospring.domain.user.repository.findByUserId
import com.hm.hyeonminshinlottospring.domain.winninglotto.domain.WinningLottoInformation
import com.hm.hyeonminshinlottospring.domain.winninglotto.dto.TotalMatchResponse
import com.hm.hyeonminshinlottospring.domain.winninglotto.dto.WinningLottoMatchResponse
import com.hm.hyeonminshinlottospring.domain.winninglotto.dto.WinningLottoRoundResponse
import com.hm.hyeonminshinlottospring.domain.winninglotto.repository.WinningLottoRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.withLock
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
class WinningLottoService(
private val winningLottoInformation: WinningLottoInformation,
private val lottoRepository: LottoRepository,
private val winningLottoRepository: WinningLottoRepository,
private val userRepository: UserRepository,
) {
// Admin can access the current winning lotto numbers.
@Transactional(readOnly = true)
fun getWinningLottoByRound(
userId: Long,
round: Int,
): WinningLottoRoundResponse = runBlocking {
val user = userRepository.findByUserId(userId)
launch(Dispatchers.Default) { validateRoundWithUseRole(user.userRole, round) }.join()
val winningLotto = getWinningLottoByRound(round)
WinningLottoRoundResponse.from(winningLotto)
}
/**
* μκΈμ μ»μ λ‘λλ§μ 리ν΄νλ€.
*/
@Transactional(readOnly = true)
fun matchUserLottoByRound(
userId: Long,
round: Int,
): TotalMatchResponse = runBlocking {
val user = userRepository.findByUserId(userId)
check(user.userRole == UserRole.ROLE_USER) { "μ£Όμ΄μ§ μ μ IDλ λ§€μΉν μ μμ΅λλ€." }
launch(Dispatchers.Default) { validateRoundWithUseRole(user.userRole, round) }.join()
val resultDeferred = async { lottoRepository.findListByUserIdAndRound(userId, round) }
check(resultDeferred.await().isNotEmpty()) { "$userId: ν΄λΉ μ μ κ° $round λΌμ΄λμ ꡬ맀ν λ‘λκ° μ‘΄μ¬νμ§ μμ΅λλ€." }
val winningLotto = getWinningLottoByRound(round)
getTotalMatchResponse(resultDeferred.await(), winningLotto.lotto)
}
private fun getWinningLottoByRound(round: Int) =
winningLottoRepository.findByRound(round) ?: throw NoSuchElementException("$round λΌμ΄λμ ν΄λΉνλ λΉμ²¨ λ²νΈκ° μ‘΄μ¬νμ§ μμ΅λλ€.")
private suspend fun getTotalMatchResponse(
userLottos: List<Lotto>,
winLotto: Lotto,
): TotalMatchResponse = TotalMatchResponse.from(
userLottos.asFlow()
.filter { lotto -> winLotto.numbers.count(lotto.numbers) > 0 }
.map { lotto ->
val matched = lotto.match(winLotto)
val rank = LottoRank.getRank(matched.size)
WinningLottoMatchResponse.from(
lotto,
matched,
rank,
)
}
.toList(),
)
private suspend fun validateRoundWithUseRole(
userRole: UserRole,
round: Int,
) {
winningLottoInformation.roundMutex.withLock {
if (userRole == UserRole.ROLE_USER) {
require(round != winningLottoInformation.round) { "νμ¬ μ§νμ€μΈ λΌμ΄λλ μ‘°νν μ μμ΅λλ€." }
}
require(round in 1..winningLottoInformation.round) { "μ‘΄μ¬νμ§ μλ λΌμ΄λλ μ‘°νν μ μμ΅λλ€." }
}
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/winninglotto/service/WinningLottoService.kt | 3583901379 |
package com.hm.hyeonminshinlottospring.domain.winninglotto.domain
import com.hm.hyeonminshinlottospring.domain.lotto.repository.LottoRepository
import kotlinx.coroutines.sync.Mutex
import org.springframework.stereotype.Component
@Component
class WinningLottoInformation(
lottoRepository: LottoRepository,
) {
val roundMutex = Mutex()
var round: Int = (lottoRepository.findFirstByOrderByRoundDesc()?.round ?: 0) + 1
protected set
fun increaseRound() {
round += 1
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/winninglotto/domain/WinningLottoInformation.kt | 631532657 |
package com.hm.hyeonminshinlottospring.domain.winninglotto.domain
import com.hm.hyeonminshinlottospring.domain.lotto.domain.Lotto
import jakarta.persistence.Entity
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.Index
import jakarta.persistence.JoinColumn
import jakarta.persistence.OneToOne
import jakarta.persistence.Table
@Table(
indexes = [
Index(name = "lotto_id_index", columnList = "lotto_id"),
],
)
@Entity
class WinningLotto(
val round: Int,
@OneToOne
@JoinColumn(name = "lotto_id", updatable = false, nullable = false)
val lotto: Lotto,
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0L,
)
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/domain/winninglotto/domain/WinningLotto.kt | 3967030204 |
package com.hm.hyeonminshinlottospring.global.config
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.datatype.hibernate6.Hibernate6Module
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.KotlinFeature
import com.fasterxml.jackson.module.kotlin.KotlinModule
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
/**
* μ¬μ©λ²:
* val objectMapper = JacksonConfig().objectMapper()
*/
@Configuration
class JacksonConfig {
@Bean
fun objectMapper(): ObjectMapper {
val objectMapper = ObjectMapper()
val javaTimeModule = JavaTimeModule()
// LocalDateTime 컀μ€ν
ν¬λ©§μΌλ‘ μ§λ ¬ν/μμ§λ ¬ν
// javaTimeModule.addSerializer(LocalDateTime::class, CustomLocalDateTimeSerializer())
// javaTimeModule.addDeserializer(LocalDateTime::class, CustomLocalDateTimeDeserializer())
objectMapper.registerModule(javaTimeModule)
// μμ§ λΆλ¬μ€μ§ μμ μν°ν°μ λν΄ null κ° λ΄λ €μ£Όλ λͺ¨λ - lazy loading
objectMapper.registerModule(Hibernate6Module())
// λͺ¨λ₯΄λ propertyμ λν΄ λ¬΄μνκ³ λμ΄κ°λ€.
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
objectMapper.registerModule(
KotlinModule.Builder()
.withReflectionCacheSize(512)
.configure(KotlinFeature.NullToEmptyCollection, false)
.configure(KotlinFeature.NullToEmptyMap, false)
.configure(KotlinFeature.NullIsSameAsDefault, false)
.configure(KotlinFeature.SingletonSupport, false)
.configure(KotlinFeature.StrictNullChecks, false)
.build(),
)
// μκ° κ΄λ ¨ κ°μ²΄(LocalDateTime, java.util.Date)λ₯Ό μ§λ ¬νν λ timestamp μ«μκ°μ΄ μλ ν¬λ§·ν
λ¬Έμμ΄λ‘ νλ€.
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
return objectMapper
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/global/config/JacksonConfig.kt | 3758860813 |
package com.hm.hyeonminshinlottospring.global.config
import org.slf4j.MDC
import org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.task.AsyncTaskExecutor
import org.springframework.core.task.TaskDecorator
import org.springframework.core.task.support.TaskExecutorAdapter
import org.springframework.scheduling.annotation.EnableAsync
import java.util.concurrent.Executors
/**
* @Async μ¬μ©μ virtual thread μ¬μ©νλλ‘ λ°κΎΈλ μ€μ .
*
* ### μ¬μ© μμ
* ```kotlin
* import org.springframework.scheduling.annotation.Async
* import org.springframework.stereotype.Service
*
* @Service
* class FooService {
*
* @Async(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME)
* fun doSomething() {
* // doSomething
* }
* }
* ```
*/
@Configuration
@EnableAsync
class AsyncConfig {
@Bean(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME)
fun asyncTaskExecutor(): AsyncTaskExecutor {
val taskExecutor = TaskExecutorAdapter(Executors.newVirtualThreadPerTaskExecutor())
taskExecutor.setTaskDecorator(LoggingTaskDecorator())
return taskExecutor
}
}
class LoggingTaskDecorator : TaskDecorator {
override fun decorate(task: Runnable): Runnable {
val callerThreadContext = MDC.getCopyOfContextMap()
return Runnable {
callerThreadContext?.let {
MDC.setContextMap(it)
}
task.run()
}
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/global/config/AsyncConfig.kt | 3664665968 |
package com.hm.hyeonminshinlottospring.global.config
import org.apache.coyote.ProtocolHandler
import org.springframework.boot.web.embedded.tomcat.TomcatProtocolHandlerCustomizer
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import java.util.concurrent.Executors
/**
* TomcatμΌλ‘ λ€μ΄μ€λ requestλ€μ platform threadλ₯Ό μ¬μ©νλ λμ virtual threadλ₯Ό μ¬μ©νκ² λ§λλ μ€μ
*/
@Configuration
class TomcatConfig {
@Bean
fun protocolHandlerVirtualThreadExecutorCustomizer(): TomcatProtocolHandlerCustomizer<*>? {
return TomcatProtocolHandlerCustomizer<ProtocolHandler> { protocolHandler: ProtocolHandler ->
protocolHandler.executor = Executors.newVirtualThreadPerTaskExecutor()
}
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/global/config/TomcatConfig.kt | 4289504796 |
package com.hm.hyeonminshinlottospring.global.config
import org.springframework.context.annotation.Configuration
import org.springframework.data.jpa.repository.config.EnableJpaAuditing
@Configuration
@EnableJpaAuditing
class JpaAuditingConfig
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/global/config/JpaAuditingConfig.kt | 2620410305 |
package com.hm.hyeonminshinlottospring.global.config
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asCoroutineDispatcher
import java.util.concurrent.Executors
/**
* Dispatchers.IO λμ μ virtual threadλ‘ μμ
ν μ μκ² ν΄μ£Όλ Dispatchers νμ₯ ν¨μ.
*/
val Dispatchers.LOOM: CoroutineDispatcher
get() = Executors.newVirtualThreadPerTaskExecutor().asCoroutineDispatcher()
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/global/config/DispatcherConfig.kt | 3398737401 |
package com.hm.hyeonminshinlottospring.global.config
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.scheduling.TaskScheduler
import org.springframework.scheduling.annotation.EnableScheduling
import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler
@Configuration
@EnableScheduling
class SchedulingConfig {
/**
* @Scheduled μ μ©λ ν
μ€ν¬μ virtual thread μ¬μ© μ€μ .
*/
@Bean
fun taskScheduler(): TaskScheduler {
return SimpleAsyncTaskScheduler().apply {
this.setVirtualThreads(true)
this.setTaskTerminationTimeout(30 * 1000)
}
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/global/config/SchedulingConfig.kt | 2692187157 |
package com.hm.hyeonminshinlottospring.global.support.doamin
import jakarta.persistence.Column
import jakarta.persistence.EntityListeners
import jakarta.persistence.MappedSuperclass
import org.springframework.data.annotation.CreatedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.time.LocalDateTime
@MappedSuperclass
@EntityListeners(AuditingEntityListener::class)
abstract class BaseTimeEntity {
@CreatedDate
@Column(updatable = false, nullable = false)
lateinit var createdDate: LocalDateTime
protected set
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/global/support/doamin/BaseTimeEntity.kt | 4249679408 |
package com.hm.hyeonminshinlottospring.global.support.doamin
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class NoArgsConstructor
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/global/support/doamin/NoArgsConstructor.kt | 4102301711 |
package com.hm.hyeonminshinlottospring.global.exception
// import org.springframework.web.ErrorResponse κ° λ°λ‘ μκΈ΄ νλ€.
open class ErrorResponse private constructor(val code: Int, val errorMessage: String) {
protected constructor(errorCode: ErrorCode) : this(errorCode.code, errorCode.errorMessage)
companion object {
fun of(
errorCode: ErrorCode,
errorMessage: String?,
) = ErrorResponse(
code = errorCode.code,
errorMessage = errorMessage ?: errorCode.errorMessage,
)
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/global/exception/ErrorResponse.kt | 3418442352 |
package com.hm.hyeonminshinlottospring.global.exception
import org.springframework.http.HttpStatus
/**
* 1xxx : Common
* 2xxx : Database
* 3xxx : Client
*/
enum class ErrorCode(val httpStatus: HttpStatus, val code: Int, val errorMessage: String) {
// Common
INVALID_REQUEST(HttpStatus.BAD_REQUEST, 1000, "Invalid request"),
INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, 1001, "Internal server error"),
NO_SUCH_ELEMENT(HttpStatus.NOT_FOUND, 1002, "No such element"),
// Database
// Client
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/global/exception/ErrorCode.kt | 4069017721 |
package com.hm.hyeonminshinlottospring.global.exception
import com.fasterxml.jackson.databind.exc.InvalidFormatException
import com.fasterxml.jackson.databind.exc.MismatchedInputException
import jakarta.validation.ConstraintViolationException
import org.springframework.dao.DataIntegrityViolationException
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.HttpStatusCode
import org.springframework.http.ResponseEntity
import org.springframework.http.converter.HttpMessageNotReadableException
import org.springframework.web.HttpMediaTypeNotSupportedException
import org.springframework.web.HttpRequestMethodNotSupportedException
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.MissingPathVariableException
import org.springframework.web.bind.MissingServletRequestParameterException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.context.request.WebRequest
import org.springframework.web.multipart.support.MissingServletRequestPartException
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
@RestControllerAdvice
class GlobalExceptionHandler : ResponseEntityExceptionHandler() {
override fun handleMethodArgumentNotValid(
ex: MethodArgumentNotValidException,
headers: HttpHeaders,
status: HttpStatusCode,
request: WebRequest,
): ResponseEntity<Any>? {
logger.error("[MethodArgumentNotValidException], ex")
val bindingResult = ex.bindingResult
var errorMessage = ""
for (fieldError in bindingResult.fieldErrors) {
errorMessage += (fieldError.field + ":")
errorMessage += fieldError.defaultMessage
errorMessage += ", "
}
return getInvalidRequestResponse(errorMessage)
}
override fun handleHttpMessageNotReadable(
ex: HttpMessageNotReadableException,
headers: HttpHeaders,
status: HttpStatusCode,
request: WebRequest,
): ResponseEntity<Any>? {
logger.error("[HttpMessageNotReadableException] ${ex.message}")
val errorMessage =
when (val cause = ex.cause) {
is InvalidFormatException -> "${cause.path.joinToString(separator = ".") { it?.fieldName.orEmpty() }}: ${ex.message}"
is MismatchedInputException -> {
"${cause.path.joinToString(separator = ".") { it?.fieldName.orEmpty() }}: ${ex.message}"
}
else -> "μ ν¨νμ§ μμ μμ²μ
λλ€"
}
return getInvalidRequestResponse(errorMessage)
}
override fun handleHttpRequestMethodNotSupported(
ex: HttpRequestMethodNotSupportedException,
headers: HttpHeaders,
status: HttpStatusCode,
request: WebRequest,
): ResponseEntity<Any>? {
logger.error("[HttpRequestMethodNotSupportedException] ${ex.message}")
return getInvalidRequestResponse(ex.message)
}
override fun handleMissingServletRequestPart(
ex: MissingServletRequestPartException,
headers: HttpHeaders,
status: HttpStatusCode,
request: WebRequest,
): ResponseEntity<Any>? {
logger.error("[MissingServletRequestPart] ${ex.message}")
return getInvalidRequestResponse(ex.message)
}
override fun handleMissingServletRequestParameter(
ex: MissingServletRequestParameterException,
headers: HttpHeaders,
status: HttpStatusCode,
request: WebRequest,
): ResponseEntity<Any>? {
logger.error("[MissingServletRequestParameter] ${ex.message}")
return getInvalidRequestResponse(ex.message)
}
override fun handleMissingPathVariable(
ex: MissingPathVariableException,
headers: HttpHeaders,
status: HttpStatusCode,
request: WebRequest,
): ResponseEntity<Any>? {
logger.error("[MissingPathVariable] ${ex.message}")
return getInvalidRequestResponse(ex.message)
}
override fun handleHttpMediaTypeNotSupported(
ex: HttpMediaTypeNotSupportedException,
headers: HttpHeaders,
status: HttpStatusCode,
request: WebRequest,
): ResponseEntity<Any>? {
logger.error("[HttpMediaTypeNotSupported] ${ex.message}")
return getInvalidRequestResponse(ex.message, HttpStatus.UNSUPPORTED_MEDIA_TYPE)
}
@ExceptionHandler(
IllegalArgumentException::class,
IllegalStateException::class,
ConstraintViolationException::class,
DataIntegrityViolationException::class,
)
fun invalidRequestException(ex: RuntimeException): ResponseEntity<Any>? {
logger.error("[InvalidRequestException]", ex)
return getInvalidRequestResponse(ex.message)
}
@ExceptionHandler(NoSuchElementException::class)
fun noSuchElementException(ex: NoSuchElementException): ResponseEntity<ErrorResponse> {
logger.error("[NoSuchElementException]", ex)
val noSuchElementErrorCode = ErrorCode.NO_SUCH_ELEMENT
return ResponseEntity.status(noSuchElementErrorCode.httpStatus)
.body(ErrorResponse.of(noSuchElementErrorCode, ex.message))
}
@ExceptionHandler(Exception::class)
fun exception(ex: Exception): ResponseEntity<ErrorResponse> {
logger.error("[Exception]", ex)
val internalServerErrorCode = ErrorCode.INTERNAL_SERVER_ERROR
return ResponseEntity.status(internalServerErrorCode.httpStatus)
.body(ErrorResponse.of(internalServerErrorCode, ex.message))
}
private fun getInvalidRequestResponse(
errorMessage: String?,
httpStatus: HttpStatus = HttpStatus.BAD_REQUEST,
): ResponseEntity<Any> {
val invalidRequestErrorCode = ErrorCode.INVALID_REQUEST
return ResponseEntity.status(httpStatus)
.body(ErrorResponse.of(invalidRequestErrorCode, errorMessage))
}
}
| HyeonminShin-LottoSpring/src/main/kotlin/com/hm/hyeonminshinlottospring/global/exception/GlobalExceptionHandler.kt | 3744165366 |
package com.example.myapplication
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.myapplication", appContext.packageName)
}
} | Save-Retrieve-Contact/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt | 1188990709 |
package com.example.myapplication
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | Save-Retrieve-Contact/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt | 2019423820 |
package com.example.myapplication.fragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.example.myapplication.R
import com.example.myapplication.activities.MainActivity
import com.example.myapplication.databinding.FragmentSaveContactBinding
import com.example.myapplication.utils.SaveContactUtil
import com.example.myapplication.utils.getByteArray
import com.google.android.material.textfield.TextInputLayout
class SaveContactFragment : Fragment() {
private lateinit var binding : FragmentSaveContactBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentSaveContactBinding.inflate(inflater, container, false)
setListeners()
return binding.root
}
private fun saveToPhonebook() {
binding.apply {
val mails = mutableListOf(getData(etEmail1), getData(etEmail2), getData(etEmail3))
val phones = mutableListOf(getData(etPhone), getData(etPhone2), getData(etPhone3))
SaveContactUtil.saveToPhoneBook(
context,
getData(etName),
phones,
mails,
getData(etTitle),
getData(etLocation),
getData(etCompany),
getByteArray(imgPerson)
)
}
}
private fun setListeners() {
binding.apply {
fabEdit.setOnClickListener {
(activity as MainActivity).showImgBs(binding.imgPerson)
}
btnSave.setOnClickListener {
saveToPhonebook()
}
fabSwipe.setOnClickListener {
findNavController().navigate(R.id.action_saveContactFragment_to_fetchContactFragment)
}
}
}
private fun getData(layout: TextInputLayout): String {
return layout.editText?.text.toString().trim()
}
} | Save-Retrieve-Contact/app/src/main/java/com/example/myapplication/fragments/SaveContactFragment.kt | 3540461253 |
package com.example.myapplication.fragments
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.example.myapplication.R
import com.example.myapplication.activities.MainActivity
import com.example.myapplication.adapter.ContactsAdapter
import com.example.myapplication.databinding.FragmentFetchContactBinding
import com.example.myapplication.utils.Communicator
import com.example.myapplication.utils.RetrieveContact
import com.example.myapplication.utils.RetrieveContact.DATA_CONTACT
class FetchContactFragment : Fragment() {
private lateinit var binding: FragmentFetchContactBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentFetchContactBinding.inflate(inflater, container, false)
setObserver()
callLauncher()
return binding.root
}
private fun setObserver() {
RetrieveContact.contactsLiveData.observe(viewLifecycleOwner) {
it?.apply {
showContacts(this as MutableList<RetrieveContact.Contact>)
}
}
}
private fun callLauncher() {
(activity as MainActivity).requestContactPermissions(object : Communicator{
override fun onFetch() {
getData()
}
})
}
private fun getData() {
context?.apply {
RetrieveContact.fetchContacts(lifecycleScope,this)
}
}
private fun showContacts(list: MutableList<RetrieveContact.Contact>) {
val dataList = ArrayList<RetrieveContact.Contact>()
list.forEach {
dataList.add(it)
}
context?.apply {
val conAdapter = ContactsAdapter(this, dataList, object : ContactsAdapter.OnClickItem{
override fun onShowItem(data: RetrieveContact.Contact) {
showItem(data)
}
})
binding.rvAllContacts.apply {
adapter = conAdapter
setHasFixedSize(true)
}
}
}
private fun showItem(data: RetrieveContact.Contact) {
val action = R.id.action_fetchContactFragment_to_displayContactFragment
findNavController().navigate(action, bundleOf(DATA_CONTACT to data))
}
} | Save-Retrieve-Contact/app/src/main/java/com/example/myapplication/fragments/FetchContactFragment.kt | 3041079092 |
package com.example.myapplication.fragments
import android.net.Uri
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.example.myapplication.R
import com.example.myapplication.adapter.DisplayContactAdapter
import com.example.myapplication.databinding.FragmentDisplayContactBinding
import com.example.myapplication.utils.BundleUtils
import com.example.myapplication.utils.RetrieveContact
import com.example.myapplication.utils.RetrieveContact.DATA_CONTACT
class DisplayContactFragment : Fragment() {
private lateinit var binding: FragmentDisplayContactBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentDisplayContactBinding.inflate(inflater, container, false)
getArg()
return binding.root
}
private fun getArg() {
arguments?.let { it ->
BundleUtils.getSerializable(it,DATA_CONTACT, RetrieveContact.Contact::class.java)?.apply {
val dataList = mutableListOf<RetrieveContact.ContactView>()
dataList.add(RetrieveContact.ContactView("Name",name))
var counter = 0
phones?.forEach {
counter++
dataList.add(RetrieveContact.ContactView("Phone $counter",it))
}
counter = 0
mails?.forEach {
counter++
dataList.add(RetrieveContact.ContactView("Mail $counter",it))
}
title?.let {
dataList.add(RetrieveContact.ContactView("Job Title",it))
}
company?.let {
dataList.add(RetrieveContact.ContactView("Organization",it))
}
setImage(image)
setAdapter(dataList)
}
}
}
private fun setImage(image: Uri?) {
if(image != null)
binding.imgPerson.setImageURI(image)
}
private fun setAdapter(dataList: MutableList<RetrieveContact.ContactView>) {
context?.let {
val adapterItem = DisplayContactAdapter(it,dataList)
binding.rvAllInformation.apply {
adapter = adapterItem
setHasFixedSize(true)
}
}
}
} | Save-Retrieve-Contact/app/src/main/java/com/example/myapplication/fragments/DisplayContactFragment.kt | 666758149 |
package com.example.myapplication.utils
import android.graphics.Bitmap
import android.graphics.Canvas
import android.view.View
import java.io.ByteArrayOutputStream
/**
* This method can convert bitmap to byte array
* @param bitmap is that bitmap that need to be converted
* @return [ByteArray] is the result ..
*/
private fun bitmapToByteArray(bitmap: Bitmap?): ByteArray? {
if(bitmap == null) return null
val stream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream)
return stream.toByteArray()
}
/**
* This method will help to get byte array directly from image view
* Because image can be uri, url, file , bitmap ,
* so if any thing is present to view then image will be load and send
* @param view is any [View] ... here shapable image view will perform better
* @return [ByteArray]
*/
fun getByteArray(view: View): ByteArray?{
val bitmap =
Bitmap.createBitmap(view.layoutParams.width, view.layoutParams.height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
view.layout(view.left, view.top, view.right, view.bottom)
view.draw(canvas)
return bitmapToByteArray(bitmap)
} | Save-Retrieve-Contact/app/src/main/java/com/example/myapplication/utils/ViewImageUtil.kt | 131720564 |
package com.example.myapplication.utils
interface Communicator {
fun onFetch()
} | Save-Retrieve-Contact/app/src/main/java/com/example/myapplication/utils/Communicator.kt | 1169703207 |
package com.example.myapplication.utils
import android.content.Intent
import android.os.Build
import android.os.Build.VERSION.SDK_INT
import android.os.Bundle
import android.os.Parcelable
import java.io.Serializable
object BundleUtils {
fun <T : Serializable?> getSerializable(bundle: Bundle?, key: String, clazz: Class<T>): T? {
return if (SDK_INT >= Build.VERSION_CODES.TIRAMISU) bundle?.getSerializable(key, clazz)
else bundle?.getSerializable(key) as T
}
} | Save-Retrieve-Contact/app/src/main/java/com/example/myapplication/utils/BundleUtils.kt | 3676080501 |
package com.example.myapplication.utils
import android.app.Activity
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.provider.ContactsContract
object SaveContactUtil {
/**
* It saves specific information to phone book
* @param name name of person
* @param phones multiple phones
* @param title title of position
* @param location address of office
* @param mails multiple mails
* @param company company name
* @param contactImg con image for phone
*/
fun saveToPhoneBook(
context: Context?,
name: String?,
phones: List<String?>?, mails: List<String?>?,
title: String?,
location: String?,
company: String?, contactImg: ByteArray?
): Int {
val intent = Intent(Intent.ACTION_INSERT, ContactsContract.Contacts.CONTENT_URI).apply {
// Sets the MIME type to match the Contacts Provider
type = ContactsContract.RawContacts.CONTENT_TYPE
}
/*
* Inserts new data into the Intent. This data is passed to the
* contacts app's Insert screen
*/
intent.apply { ->
// Inserts a Name
putExtra(ContactsContract.Intents.Insert.NAME, name)
// Insert a title
putExtra(ContactsContract.Intents.Insert.JOB_TITLE, title)
// Insert a company
putExtra(ContactsContract.Intents.Insert.COMPANY, company)
// Insert a location
putExtra(ContactsContract.Intents.Insert.POSTAL, location)
if ( // phone and mails with image ..
preparePhonesMailsProfileImage(
intent, phones, mails, contactImg
)
== 0
)
context?.startActivity(intent)
}
return 0
}
/**
* take exact params and adding list of values with intent
* @param phones list of numbers
* @param mails list of emails
* @param contactImg is profile image
*/
private fun preparePhonesMailsProfileImage(
intent: Intent,
phones: List<String?>?,
mails: List<String?>?,
contactImg: ByteArray?
): Int {
val data = ArrayList<ContentValues>()
data.addAll(getNumberContents(phones))
data.addAll(getMailContents(mails))
data.addAll(getContactImgContent(contactImg))
intent.putParcelableArrayListExtra(ContactsContract.Intents.Insert.DATA, data)
return 0
}
/**
* get content values for data content item
* @param value as String
* @return [ContentValues] as object of content values
*/
private fun getContentValuesObject(value: String): ContentValues {
val row = ContentValues()
row.put(
ContactsContract.Contacts.Data.MIMETYPE,
value
)
return row
}
/**
* Adding phones string list to data ..
* @param phones as list of string
* @return [ArrayList]---- of contentValues
*/
private fun getNumberContents(phones: List<String?>?): ArrayList<ContentValues> {
val data = ArrayList<ContentValues>()
// Filling data with phone numbers
phones?.apply {
for (i in phones.indices) {
val row =
getContentValuesObject(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
phones[i]?.apply {
row.put(ContactsContract.CommonDataKinds.Phone.NUMBER, this)
}
data.add(row)
}
}
return data
}
/**
* Adding mails string list to data ..
* @param mails as list of string
* @return [ArrayList]---- of contentValues
*/
private fun getMailContents(mails: List<String?>?): ArrayList<ContentValues> {
val data = ArrayList<ContentValues>()
// Filling data with mails
mails?.apply {
for (i in mails.indices) {
val row =
getContentValuesObject(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
mails[i]?.apply {
row.put(ContactsContract.CommonDataKinds.Email.DATA, this)
}
data.add(row)
}
}
return data
}
/**
* Adding image byte array to data ..
* Image of contact will be added (single image)
* @param contactImg as Byte Array
* @return [ArrayList]---- of contentValues
*/
private fun getContactImgContent( contactImg: ByteArray?): ArrayList<ContentValues> {
val data = ArrayList<ContentValues>()
contactImg?.apply {
val row =
getContentValuesObject(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
row.put(ContactsContract.CommonDataKinds.Photo.PHOTO, this)
data.add(row)
}
return data
}
} | Save-Retrieve-Contact/app/src/main/java/com/example/myapplication/utils/SaveContactUtil.kt | 1402272213 |
package com.example.myapplication.utils
import androidx.annotation.Keep
import com.google.gson.annotations.SerializedName
import java.io.Serializable
import android.content.ContentUris
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.provider.ContactsContract
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
object RetrieveContact {
const val DATA_CONTACT = "DATA_CONTACT"
@Keep
data class Contact(
var id : String ,
var name : String,
var phones : List<String>? = null,
var mails : List<String>? = null,
var title : String? = null,
var image : Uri? = null,
var company : String? = null
) : Serializable
@Keep
data class ContactView(
val title : String,
val value : String,
): Serializable
/**
* @return the photo URI
*/
private fun getPhotoUri(mContext: Context, id: String): Uri? {
try {
val cur: Cursor? = mContext.contentResolver.query(
ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID + "=" + id + " AND "
+ ContactsContract.Data.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'", null,
null
)
if (cur != null) {
if (!cur.moveToFirst()) {
return null // no photo
}
} else {
return null // error in cursor process
}
} catch (e: Exception) {
e.printStackTrace()
return null
}
val person =
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id.toLong())
return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY)
}
private fun getContactEmails(mContext: Context): HashMap<String, ArrayList<String>> {
val contactsEmailMap = HashMap<String, ArrayList<String>>()
val emailCursor = mContext.contentResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
null,
null,
null)
if (emailCursor != null && emailCursor.count > 0) {
val contactIdIndex = emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID)
val emailIndex = emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS)
while (emailCursor.moveToNext()) {
val contactId = emailCursor.getString(contactIdIndex)
val email = emailCursor.getString(emailIndex)
//check if the map contains key or not, if not then create a new array list with email
if (contactsEmailMap.containsKey(contactId)) {
contactsEmailMap[contactId]?.add(email)
} else {
contactsEmailMap[contactId] = arrayListOf(email)
}
}
//contact contains all the emails of a particular contact
emailCursor.close()
}
return contactsEmailMap
}
private fun getContactNumbers(mContext: Context): HashMap<String, ArrayList<String>> {
val contactsNumberMap = HashMap<String, ArrayList<String>>()
val phoneCursor: Cursor? = mContext.contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
null,
null,
null
)
if (phoneCursor != null && phoneCursor.count > 0) {
val contactIdIndex = phoneCursor!!.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID)
val numberIndex = phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
while (phoneCursor.moveToNext()) {
val contactId = phoneCursor.getString(contactIdIndex)
val number: String = phoneCursor.getString(numberIndex)
//check if the map contains key or not, if not then create a new array list with number
if (contactsNumberMap.containsKey(contactId)) {
contactsNumberMap[contactId]?.add(number)
} else {
contactsNumberMap[contactId] = arrayListOf(number)
}
}
//contact contains all the number of a particular contact
phoneCursor.close()
}
return contactsNumberMap
}
private fun getPhoneContacts(mContext: Context): ArrayList<Contact> {
val contactsList = ArrayList<Contact>()
val contactsCursor = mContext.contentResolver?.query(
ContactsContract.Contacts.CONTENT_URI,
null,
null,
null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC")
if (contactsCursor != null && contactsCursor.count > 0) {
val idIndex = contactsCursor.getColumnIndex(ContactsContract.Contacts._ID)
val nameIndex = contactsCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)
while (contactsCursor.moveToNext()) {
val id = contactsCursor.getString(idIndex)
val name = contactsCursor.getString(nameIndex)
if (name != null) {
contactsList.add(Contact(id, name, title = null, company = null))
}
}
contactsCursor.close()
}
return contactsList
}
private val _contactsLiveData: MutableLiveData<List<Contact>> =
MutableLiveData()
val contactsLiveData: LiveData<List<Contact>> get() = _contactsLiveData
fun fetchContacts(scope : CoroutineScope,mContext: Context) {
scope.launch {
val contactsListAsync = async { getPhoneContacts(mContext) }
val contactNumbersAsync = async { getContactNumbers(mContext) }
val contactEmailAsync = async { getContactEmails(mContext) }
val contacts = contactsListAsync.await()
val contactNumbers = contactNumbersAsync.await()
val contactEmails = contactEmailAsync.await()
contacts.forEach {
contactNumbers[it.id]?.let { numbers ->
it.phones = numbers
}
contactEmails[it.id]?.let { emails ->
it.mails = emails
}
it.image = getPhotoUri(mContext,it.id)
}
_contactsLiveData.postValue(contacts)
}
}
} | Save-Retrieve-Contact/app/src/main/java/com/example/myapplication/utils/RetrieveContact.kt | 3114777208 |
package com.example.myapplication.utils
import android.content.Context
import android.view.LayoutInflater
import com.example.myapplication.R
import com.example.myapplication.databinding.LayoutCapturePhotoBinding
import com.google.android.material.bottomsheet.BottomSheetDialog
class OpenImageDialog(context: Context, onCapture: () -> Unit,onFolder: () -> Unit) {
private var binding : LayoutCapturePhotoBinding
private var bottomSheet: BottomSheetDialog
init {
binding =
LayoutCapturePhotoBinding.inflate(
LayoutInflater.from(context),
null,
false
).apply {
txtCapture.setOnClickListener {
onCapture()
dismiss()
}
txtFolder.setOnClickListener {
onFolder()
dismiss()
}
}
bottomSheet = BottomSheetDialog(context, R.style.BottomSheetDialog).apply {
setContentView(binding.root)
}
}
fun show() {
if (!bottomSheet.isShowing) bottomSheet.show()
}
private fun dismiss() {
if (bottomSheet.isShowing) bottomSheet.dismiss()
}
} | Save-Retrieve-Contact/app/src/main/java/com/example/myapplication/utils/OpenImageDialog.kt | 3971066728 |
package com.example.myapplication.adapter
import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.databinding.LayoutContactInfoItemBinding
import com.example.myapplication.utils.RetrieveContact
class DisplayContactAdapter (
private val context: Context,
private val dataList: List<RetrieveContact.ContactView>,
) : RecyclerView.Adapter<DisplayContactAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view =
LayoutContactInfoItemBinding.inflate(LayoutInflater.from(context), parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return dataList.size
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val data = dataList[position]
holder.binding.apply {
txtTitle.text = data.title
txtValue.text = data.value
}
}
inner class ViewHolder(val binding: LayoutContactInfoItemBinding) :
RecyclerView.ViewHolder(binding.root)
} | Save-Retrieve-Contact/app/src/main/java/com/example/myapplication/adapter/DisplayContactAdapter.kt | 590419102 |
package com.example.myapplication.adapter
import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.databinding.LayoutContactItemBinding
import com.example.myapplication.utils.RetrieveContact
class ContactsAdapter(
private val context: Context,
private val dataList: List<RetrieveContact.Contact>,
private val listener : OnClickItem
) : RecyclerView.Adapter<ContactsAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view =
LayoutContactItemBinding.inflate(LayoutInflater.from(context), parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return dataList.size
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val data = dataList[position]
holder.binding.apply {
txtPersonName.text = data.name
data.phones?.apply {
txtPersonNumber.text = this[0]
}
data.image?.apply {
imgPerson.setImageURI(this)
}
this.root.setOnClickListener {
listener.onShowItem(data)
}
}
}
inner class ViewHolder(val binding: LayoutContactItemBinding) :
RecyclerView.ViewHolder(binding.root)
interface OnClickItem{
fun onShowItem(data : RetrieveContact.Contact)
}
} | Save-Retrieve-Contact/app/src/main/java/com/example/myapplication/adapter/ContactsAdapter.kt | 2188804006 |
package com.example.myapplication.activities
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.navigation.NavController
import androidx.navigation.NavGraph
import androidx.navigation.fragment.NavHostFragment
import com.example.myapplication.R
import com.example.myapplication.databinding.ActivityMainBinding
import com.example.myapplication.utils.Communicator
import com.example.myapplication.utils.OpenImageDialog
import com.google.android.material.imageview.ShapeableImageView
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private var imageUri: Uri? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setNav()
}
private fun setNav() {
val navGraph: NavGraph
val navController: NavController
val navHostFragment =
supportFragmentManager.findFragmentById(R.id.fragment_container) as NavHostFragment
navController = navHostFragment.navController
navGraph = navController.navInflater.inflate(R.navigation.contact_nav_graph)
navGraph.apply {
setStartDestination(R.id.saveContactFragment)
}
navController.setGraph(navGraph,intent.extras)
}
private fun setImageUri(uri: Uri){
personImg?.setImageURI(uri)
}
//-------------------------------- IMAGE BOTTOM SHEET------------------------------------//
private var personImg : ShapeableImageView? = null
fun showImgBs(personImage : ShapeableImageView) {
personImg = personImage
OpenImageDialog(this, { onCapture() }, { onFolder() }).show()
}
//-------------------------------- COMMON PERMISSIONS------------------------------------//
companion object {
private val CAMERA_PERMISSIONS =
mutableListOf(
Manifest.permission.CAMERA,
).apply {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
}.toTypedArray()
private val CONTACT_PERMISSIONS = mutableListOf(Manifest.permission.READ_CONTACTS,
Manifest.permission.WRITE_CONTACTS).toTypedArray()
}
private val cameraPermissionLauncher =
registerForActivityResult(
ActivityResultContracts.RequestMultiplePermissions()
)
{ permissions ->
// Handle Permission granted/rejected
var permissionGranted = true
permissions.entries.forEach {
if (it.key in CAMERA_PERMISSIONS && !it.value)
permissionGranted = false
}
if (!permissionGranted) {
requestCameraPermissions()
} else {
// direct navigate to respective screen
onCameraLaunch()
}
}
private val contactPermissionLauncher =
registerForActivityResult(
ActivityResultContracts.RequestMultiplePermissions()
)
{ permissions ->
// Handle Permission granted/rejected
var permissionGranted = true
permissions.entries.forEach {
if (it.key in CONTACT_PERMISSIONS && !it.value)
permissionGranted = false
}
if (!permissionGranted) {
requestContactPermissions(listener)
} else {
// direct navigate to respective screen
setResultToRet()
}
}
private fun setResultToRet() {
listener?.let {
it.onFetch()
}
}
private fun allPermissionsGranted() = CAMERA_PERMISSIONS.all {
ContextCompat.checkSelfPermission(
baseContext, it
) == PackageManager.PERMISSION_GRANTED
}
private fun requestCameraPermissions() {
cameraPermissionLauncher.launch(CAMERA_PERMISSIONS)
}
private var listener : Communicator? = null
fun requestContactPermissions(obj : Communicator?){
listener = obj
contactPermissionLauncher.launch(CONTACT_PERMISSIONS)
}
//-------------------------------- CAPTURE IMAGE------------------------------------//
private var cameraLauncher: ActivityResultLauncher<Intent> =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
imageUri?.let { setImageUri(it) }
}
}
@SuppressLint("ObsoleteSdkInt")
private fun onCapture() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
// direct navigate to respective screen
onCameraLaunch()
} else {
if (allPermissionsGranted()) onCameraLaunch()
else {
requestCameraPermissions()
}
}
}
private fun onCameraLaunch() {
val values = ContentValues()
values.put(MediaStore.Images.Media.TITLE, "New Picture")
values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera")
imageUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
cameraLauncher.launch(cameraIntent)
}
//-------------------------------- GALLERY IMAGE------------------------------------//
private val galleryLauncher: ActivityResultLauncher<Intent> = registerForActivityResult(
ActivityResultContracts.StartActivityForResult(), ActivityResultCallback {
if (it.resultCode == RESULT_OK) {
imageUri = it.data?.data
imageUri?.let { it1 -> setImageUri(it1) }
}
}
)
private fun onFolder() {
galleryLauncher.launch(
Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
)
)
}
} | Save-Retrieve-Contact/app/src/main/java/com/example/myapplication/activities/MainActivity.kt | 3334319181 |
import domain.Card
import domain.Draw
import domain.Hand
import domain.Rank
import kotlinx.coroutines.*
import java.text.DecimalFormat
import java.util.concurrent.atomic.AtomicLong
import kotlin.time.TimeSource
suspend fun main() = runBlocking {
val time = TimeSource.Monotonic.markNow()
val scope = CoroutineScope(Dispatchers.Default)
val total = AtomicLong()
val work = scope.launch {
Card.collection.asSequence()
.flatMap { sequenceOf(Hand(index = 1, card = it)) }
.flatMap { it.children }
.flatMap { it.children }
.flatMap { it.children }
.flatMap { it.children }
.flatMap { it.children }
.forEach { hand ->
launch {
sequenceOf(hand)
.flatMap { it.childrenLast }
.map { it.drawHands }
.flatMap { it.rivers }
.flatMap { it.turns }
.flatMap { it.flops }
.flatMap { it.pockets }
.forEach { _ -> }
}
}
}
work.join()
println("Count: ${total.toLong().format} Elapsed: ${time.elapsedNow()}")
}
val Hand.drawHands: Hand
get() = when {
royalFlushBits >= 5 -> copy(draw = Draw.ROYAL_FLUSH)
straightFlushBits >= 5 -> copy(draw = Draw.STRAIGHT_FLUSH)
wheelFlushBits >= 5 -> copy(draw = Draw.STRAIGHT_FLUSH)
quadrupleBits == 4 -> copy(draw = Draw.QUADRUPLE)
fullHouseBits >= 5 -> copy(draw = Draw.FULL_HOUSE)
flushBits >= 5 -> copy(draw = Draw.FLUSH)
straightBits >= 5 -> copy(draw = Draw.STRAIGHT)
wheelBits >= 5 -> copy(draw = Draw.STRAIGHT)
triplesBits == 3 -> copy(draw = Draw.TRIPLE)
twoPairBits == 4 -> copy(draw = Draw.TWO_PAIR)
pairsBits == 2 -> copy(draw = Draw.PAIR)
else -> this
}
val Hand.children: Sequence<Hand>
get() = card.remaining.asSequence()
.map { copy(parent = this, baseKey = baseKey.or(it.key), card = it, index = index + 1) }
val Hand.childrenLast: Sequence<Hand>
get() = card.remaining.asSequence()
.map { copy(parent = this, baseKey = baseKey.or(it.key), card = it, index = index + 1, last = true) }
val Hand.royalFlushBits: Int get() = royalFlushKey.countOneBits()
val Hand.royalFlushKey: Long
get() {
if (index >= 5) {
return parent?.let {
val newRoyalFlushKey = baseKey.and(Rank.ROYAL_RANKS_KEY).and(card.suit.key)
if (it.royalFlushBits < 5 && newRoyalFlushKey.countOneBits() >= 5) {
return newRoyalFlushKey
}
it.royalFlushKey
} ?: 0L
}
return 0L
}
val Hand.wheelFlushBits: Int get() = wheelFlushKey.countOneBits()
val Hand.wheelFlushKey: Long
get() {
if (index >= 5) {
return parent?.let {
val newWheelFlushKey = baseKey.and(Rank.WHEEL_RANKS_KEY).and(card.suit.key)
if (it.wheelFlushBits < 5 && newWheelFlushKey.countOneBits() >= 5) {
return newWheelFlushKey
}
it.wheelFlushKey
} ?: 0L
}
return 0L
}
val Hand.straightFlushBits: Int get() = straightFlushKey.countOneBits()
val Hand.straightFlushKey: Long
get() {
if (index >= 5) {
return parent?.let {
if (it.straightFlushBits < 5) {
val newStraightFlushKey = baseKey.and(card.rank.seriesKey).and(card.suit.key)
if (newStraightFlushKey.countOneBits() > it.straightFlushBits) {
return newStraightFlushKey
}
}
it.straightFlushKey
} ?: 0L
}
return 0L
}
val Hand.quadrupleBits: Int get() = quadrupleKey.countOneBits()
val Hand.quadrupleKey: Long
get() {
if (index >= 4) {
return parent?.let {
val kindKey = baseKey.and(card.rank.key)
if (kindKey.countOneBits() == 4 && it.quadrupleBits < 4) {
return it.quadrupleKey.or(kindKey)
}
return it.quadrupleKey
} ?: 0L
}
return 0L
}
val Hand.fullHouseBits: Int get() = fullHouseKey.countOneBits()
val Hand.fullHouseKey: Long
get() {
if (index >= 5) {
return parent?.let {
if (it.fullHouseBits < 5) {
return it.fullHouseKey.or(triplesKey).or(pairsKey)
}
return it.fullHouseKey
} ?: 0L
}
return 0L
}
val Hand.flushBits get() = flushKey.countOneBits()
val Hand.flushKey: Long
get() {
if (index >= 5) {
return parent?.let {
if (it.flushBits < 5) {
val newFlushKey = baseKey.and(card.suit.key)
if (newFlushKey.countOneBits() > it.flushBits) {
return newFlushKey
}
}
return it.flushKey
} ?: 0L
}
return 0L
}
val Hand.straightBits: Int get() = straightKey.countOneBits()
val Hand.straightKey: Long
get() {
if (index >= 5) {
val cardKey = card.key
return parent?.let {
val newStraightKey = baseKey.and(card.rank.seriesKey)
if (it.straightBits < 5 && newStraightKey.countOneBits() >= 5) {
return card.rank.series[0].key.and(baseKey).takeHighestOneBit()
.or(card.rank.series[1].key.and(baseKey).takeHighestOneBit())
.or(card.rank.series[2].key.and(baseKey).takeHighestOneBit())
.or(card.rank.series[3].key.and(baseKey).takeHighestOneBit())
.or(card.rank.series[4].key.and(baseKey).takeHighestOneBit())
}
it.straightKey
} ?: cardKey
}
return 0L
}
val Hand.wheelBits: Int get() = wheelKey.countOneBits()
val Hand.wheelKey: Long
get() {
if (index >= 5) {
val cardKey = card.key
return parent?.let {
val newWheelKey = baseKey.and(Rank.WHEEL_RANKS_KEY)
if (it.wheelBits < 5 && newWheelKey.countOneBits() >= 5) {
return Rank.WHEEL_RANKS[0].key.and(baseKey).takeHighestOneBit()
.or(Rank.WHEEL_RANKS[1].key.and(baseKey).takeHighestOneBit())
.or(Rank.WHEEL_RANKS[2].key.and(baseKey).takeHighestOneBit())
.or(Rank.WHEEL_RANKS[3].key.and(baseKey).takeHighestOneBit())
.or(Rank.WHEEL_RANKS[4].key.and(baseKey).takeHighestOneBit())
}
it.wheelKey
} ?: cardKey
}
return 0L
}
val Hand.triplesBits: Int get() = triplesKey.countOneBits()
val Hand.triplesKey: Long
get() {
if (index >= 3) {
return parent?.let {
val kindKey = baseKey.and(card.rank.key)
if (it.triplesBits < 6 && kindKey.countOneBits() == 3) {
return it.triplesKey.or(kindKey)
}
return it.triplesKey
} ?: 0L
}
return 0L
}
val Hand.twoPairBits: Int get() = twoPairKey.countOneBits()
val Hand.twoPairKey: Long
get() {
if (index >= 4) {
return parent?.let {
if (it.twoPairBits < 4) {
return it.twoPairKey.or(pairsKey)
}
return it.twoPairKey
} ?: 0L
}
return 0L
}
val Hand.pairsBits: Int get() = pairsKey.countOneBits()
val Hand.pairsKey: Long
get() {
if (index >= 2) {
return parent?.let {
val kindKey = baseKey.and(card.rank.key)
if (it.pairsBits < 4 && kindKey.countOneBits() == 2) {
return it.pairsKey.or(kindKey)
}
return it.pairsKey
} ?: 0L
}
return 0L
}
val Hand.initDrawCards: List<Card>
get() = Card.collection
.filter { baseKey.and(it.key) == it.key }
.filter { parentKey.and(it.key) == 0L }
val Hand.drawCards: List<Card>
get() = initDrawCards.filter { it.key < card.key }
val Hand.drawsInit: Sequence<Hand>
get() = initDrawCards.asSequence()
.map { copy(parent = this, drawKey = it.key, parentKey = parentKey.or(it.key), card = it) }
val Hand.draws: Sequence<Hand>
get() = drawCards.asSequence()
.map { copy(parent = this, drawKey = drawKey.or(it.key), parentKey = parentKey.or(it.key), card = it) }
val Hand.pockets: Sequence<Hand>
get() = sequenceOf(this)
.flatMap { it.drawsInit }
.flatMap { it.draws }
.map { it.copy(pocketKey = it.drawKey) }
val Hand.flops: Sequence<Hand>
get() = sequenceOf(this)
.flatMap { it.drawsInit }
.flatMap { it.draws }
.flatMap { it.draws }
.map { it.copy(flopKey = it.drawKey) }
val Hand.turns: Sequence<Hand>
get() = sequenceOf(this)
.flatMap { it.drawsInit }
.map { it.copy(turnKey = it.drawKey) }
val Hand.rivers: Sequence<Hand>
get() = sequenceOf(this)
.flatMap { it.drawsInit }
.map { it.copy(riverKey = it.drawKey) }
val Hand.print: Unit
get() = println(
"""|Draw: ${draw.name}
|Bass: ${baseKey.code}
|Parent: ${parentKey.code}
|Draw: ${drawKey.code}
|Pocket: ${pocketKey.code}
|Flow: ${flopKey.code}
|Turn: ${turnKey.code}
|River: ${riverKey.code}
|Pairs ${pairsKey.code}
|Triples ${triplesKey.code}
|Quadruple ${quadrupleKey.code}
|Full House ${fullHouseKey.code}
|Two Pair ${twoPairKey.code}
|Flush ${flushKey.code}
|Straight ${straightKey.code}
|Straight Flush ${straightFlushKey.code}
|""".trimMargin()
)
val Long.cards: List<Card> get() = Card.collection.filter { (it.key and this) == it.key }
val Long.code: String get() = cards.joinToString(" ") { c -> c.code }
val formatLong = DecimalFormat("#,##0")
val Long.format: String get() = formatLong.format(this)
| kc/src/main/kotlin/Main.kt | 1969563926 |
package common.graph
interface Edge {
} | kc/src/main/kotlin/common/graph/Edge.kt | 3847424950 |
package domain
import common.graph.Edge
data class Card(
val rank: Rank,
val suit: Suit,
) {
companion object {
val collection: List<Card> = Rank.collection.flatMap { it.cards }
}
val key: Long get() = rank.key.and(suit.key)
val code: String get() = rank.code + suit.code
val remaining: List<Card>
get() = collection.filter { it.key < key }
val edge: List<CardEdge> get() = remaining.map { CardEdge(this, it) }
}
data class CardEdge(
val cardIn:Card,
val cardOut:Card,
) | kc/src/main/kotlin/domain/Card.kt | 3305507037 |
package domain
import java.util.concurrent.atomic.AtomicLong
data class Draw(val key: Long = 0L, val name: String = "", var sequence5: Int = 0, var sequence7: Long = 0) {
constructor() : this(0L)
companion object {
val empty = Draw()
val size = 10
val top = 1L shl (Card.collection.toList().size + size - 1)
val collection: List<Draw> = listOf(
Draw(top shr 0, "RoyalFlush", 4, 4_324),
Draw(top shr 1, "StraightFlush", 36, 37_260),
Draw(top shr 2, "Quadruple", 624, 224_848),
Draw(top shr 3, "FullHouse", 3_744, 3_473_184),
Draw(top shr 4, "Flush", 5_108, 4_047_644),
Draw(top shr 5, "Straight", 10_200, 6_180_020),
Draw(top shr 6, "Triple", 54_912, 6_461_620),
Draw(top shr 7, "TwoPair", 123_552, 31_433_400),
Draw(top shr 8, "Pair", 1_098_240, 58_627_800),
Draw(top shr 9, "HighCard", 1_302_540, 23_294_460)
)
val ROYAL_FLUSH get() = collection[0]
val STRAIGHT_FLUSH get() = collection[1]
val QUADRUPLE get() = collection[2]
val FULL_HOUSE get() = collection[3]
val FLUSH get() = collection[4]
val STRAIGHT get() = collection[5]
val TRIPLE get() = collection[6]
val TWO_PAIR get() = collection[7]
val PAIR get() = collection[8]
val HIGH_CARD get() = collection[9]
}
// val total = AtomicLong()
}
| kc/src/main/kotlin/domain/Draw.kt | 236844607 |
package domain
data class Rank(val index: Int, val code: String) {
companion object {
private var topRankKey: Long = 0b1111L shl (12 * 4)
val collection: List<Rank> = listOf(
Rank(0, "A"),
Rank(1, "K"),
Rank(2, "Q"),
Rank(3, "J"),
Rank(4, "T"),
Rank(5, "9"),
Rank(6, "8"),
Rank(7, "7"),
Rank(8, "6"),
Rank(9, "5"),
Rank(10, "4"),
Rank(11, "3"),
Rank(12, "2"),
)
val _A: Rank = collection[0]
val _K: Rank = collection[1]
val _Q: Rank = collection[2]
val _J: Rank = collection[3]
val _T: Rank = collection[4]
val _9: Rank = collection[5]
val _8: Rank = collection[6]
val _7: Rank = collection[7]
val _6: Rank = collection[8]
val _5: Rank = collection[9]
val _4: Rank = collection[10]
val _3: Rank = collection[11]
val _2: Rank = collection[12]
val seriesData = listOf(
listOf(_A, _A, _A, _A, _A),
listOf(_A, _A, _A, _A, _K),
listOf(_A, _A, _A, _K, _Q),
listOf(_A, _A, _K, _Q, _J),
listOf(_A, _K, _Q, _J, _T),
listOf(_K, _Q, _J, _T, _9),
listOf(_Q, _J, _T, _9, _8),
listOf(_J, _T, _9, _8, _7),
listOf(_T, _9, _8, _7, _6),
listOf(_9, _8, _7, _6, _5),
listOf(_8, _7, _6, _5, _4),
listOf(_7, _6, _5, _4, _3),
listOf(_6, _5, _4, _3, _2),
)
val ROYAL_RANKS: List<Rank> get() = listOf(_A, _K, _Q, _J, _T)
val ROYAL_RANKS_KEY: Long get() = ROYAL_RANKS.map { it.key }.reduce { acc, key -> acc.or(key)};
val WHEEL_RANKS: List<Rank> get() = listOf(_5, _4, _3, _2, _A)
val WHEEL_RANKS_KEY: Long get() = WHEEL_RANKS.map { it.key }.reduce { acc, key -> acc.or(key)};
}
val key: Long get() = topRankKey shr (index * 4)
val series: List<Rank> get() = seriesData[index]
val seriesKey: Long get() = series.map { it.key }.reduce { acc, key -> acc.or(key)}
val cards: List<Card> get() = Suit.collection.map { Card(this, it) }
val next: Rank get() = collection[(index + 1) % 13]
} | kc/src/main/kotlin/domain/Rank.kt | 2567360159 |
package domain
import java.io.Flushable
data class Hand(
val index:Int,
val card: Card,
val parent: Hand? = null,
val parentKey: Long = 0L,
val baseKey: Long = card.key,
val last: Boolean = false,
val drawKey: Long = 0L,
val pocketKey: Long = 0L,
val flopKey: Long = 0L,
val turnKey: Long = 0L,
val riverKey: Long = 0L,
val draw: Draw = Draw.HIGH_CARD
) {
}
| kc/src/main/kotlin/domain/Hand.kt | 561374296 |
package domain
data class Deck(
var key: ULong = ALL_CARDS_KEY
) {
companion object {
val ALL_CARDS_KEY: ULong = generateSequence (1UL shl 51){ it shr 1}.take(52).reduce { acc, it -> acc or it}
val empty: Deck = Deck(0UL)
}
val isEmpty: Boolean get() = key == 0UL
val takeHighestCard: ULong get() {
val takeHighestCard: ULong = key.takeHighestOneBit()
key = key and takeHighestCard.inv()
return takeHighestCard
}
} | kc/src/main/kotlin/domain/Deck.kt | 3392795509 |
package domain
data class HandData(
val index: Int,
val hands: List<Hand>
) | kc/src/main/kotlin/domain/HandData.kt | 3472504426 |
package domain
data class Suit(val index: Int, val code: String) {
companion object {
private const val topSuitKey = 0b1000100010001000100010001000100010001000100010001000L
val collection: List<Suit> = listOf(
Suit(0, "S"),
Suit(1, "H"),
Suit(2, "D"),
Suit(3, "C"),
)
val _S: Suit = collection[0];
val _H: Suit = collection[1];
val _D: Suit = collection[2];
val _C: Suit = collection[3];
}
val key: Long get() = topSuitKey shr index
} | kc/src/main/kotlin/domain/Suit.kt | 1773706822 |
package ksm.viewmodel.exceptions
public fun interface ExceptionHandler {
public fun handle(throwable: Throwable)
}
| ksm/viewmodel/src/commonMain/kotlin/ksm/viewmodel/exceptions/ExceptionHandler.kt | 2212573143 |
package ksm.viewmodel.exceptions
import ksm.context.StateContext
import ksm.viewmodel.exceptions.plugin.ExceptionHandlerPlugin
import ksm.plugin.plugin
public fun StateContext.setExceptionHandler(handler: ExceptionHandler) {
plugin(ExceptionHandlerPlugin).setExceptionHandler(
context = this,
handler = handler
)
}
public val StateContext.exceptionHandler: ExceptionHandler? get() {
return plugin(ExceptionHandlerPlugin).exceptionHandler(context = this)
}
| ksm/viewmodel/src/commonMain/kotlin/ksm/viewmodel/exceptions/StateContext.kt | 4006343185 |
package ksm.viewmodel.exceptions.plugin
import ksm.context.StateContext
import ksm.viewmodel.exceptions.ExceptionHandler
internal class ExceptionHandlerEntry(
root: ExceptionHandlerEntry? = null
) : StateContext.Element {
override val key = ExceptionHandlerEntry
var handler: ExceptionHandler? = root?.handler
companion object : StateContext.Key<ExceptionHandlerEntry>
}
| ksm/viewmodel/src/commonMain/kotlin/ksm/viewmodel/exceptions/plugin/ExceptionHandlerEntry.kt | 2601540797 |
package ksm.viewmodel.exceptions.plugin
import ksm.annotation.MutateContext
import ksm.context.StateContext
import ksm.context.configuration.interceptor.ConfigurationInterceptor
import ksm.context.configuration.interceptor.addConfigurationInterceptor
import ksm.viewmodel.exceptions.ExceptionHandler
import ksm.plugin.Plugin
public object ExceptionHandlerPlugin : Plugin.Singleton<ExceptionHandlerPlugin> {
@MutateContext
override fun install(context: StateContext): StateContext {
val entry = ExceptionHandlerEntry()
context.addConfigurationInterceptor(Configuration(entry))
return context + entry
}
private class Configuration(
val entry: ExceptionHandlerEntry
) : ConfigurationInterceptor {
@MutateContext
override fun onConfigure(context: StateContext): StateContext {
return context + ExceptionHandlerEntry(entry)
}
}
public fun setExceptionHandler(
context: StateContext,
handler: ExceptionHandler
) {
context.require(ExceptionHandlerEntry).handler = handler
}
public fun exceptionHandler(context: StateContext): ExceptionHandler? {
return context.require(ExceptionHandlerEntry).handler
}
}
| ksm/viewmodel/src/commonMain/kotlin/ksm/viewmodel/exceptions/plugin/ExceptionHandlerPlugin.kt | 4027689475 |
package ksm.viewmodel.exceptions
import ksm.StateController
public fun StateController.setExceptionHandler(handler: ExceptionHandler) {
context.setExceptionHandler(handler)
}
public inline fun <T> StateController.handleExceptions(
block: () -> Result<T>
): Result<T> {
val result = block()
result.onFailure { throwable ->
context.exceptionHandler?.handle(throwable)
}
return result
}
| ksm/viewmodel/src/commonMain/kotlin/ksm/viewmodel/exceptions/ViewModelController.kt | 1617857639 |
package ksm.viewmodel
import ksm.StateController
import ksm.annotation.LibraryConstructor
import ksm.asStateController
import ksm.builder.StateControllerBuilder
import ksm.context.StateContext
import ksm.context.createChildContext
import ksm.pluginStateController
import ksm.viewmodel.exceptions.plugin.ExceptionHandlerPlugin
@OptIn(LibraryConstructor::class)
public inline fun viewModelStateController(
context: StateContext = StateContext.Empty,
enableConfiguration: Boolean = true,
enableLifecycle: Boolean = true,
enableFinishOnce: Boolean = true,
enableExceptionHandler: Boolean = true,
builder: StateControllerBuilder.() -> Unit = {}
): StateController {
val root = pluginStateController(
context = context,
enableConfiguration = enableConfiguration,
enableLifecycle = enableLifecycle,
enableFinishOnce = enableFinishOnce
) {
if (enableExceptionHandler) install(ExceptionHandlerPlugin)
builder()
}.context
// Calls onConfigure
val built = root.createChildContext()
return built.asStateController()
}
| ksm/viewmodel/src/commonMain/kotlin/ksm/viewmodel/ViewModelController.kt | 3470385000 |
package ksm.context.configuration.plugin
import ksm.annotation.MutateContext
import ksm.context.StateContext
import ksm.context.configuration.interceptor.ConfigurationInterceptor
internal class ConfigurationStateController : StateContext.Element {
override val key = ConfigurationStateController
private val interceptors = mutableListOf<ConfigurationInterceptor>()
fun addInterceptor(interceptor: ConfigurationInterceptor) {
interceptors += interceptor
}
@MutateContext
fun onConfigure(context: StateContext): StateContext {
return interceptors.fold(context) { acc, interceptor -> interceptor.onConfigure(acc) }
}
companion object : StateContext.Key<ConfigurationStateController>
}
| ksm/core/src/commonMain/kotlin/ksm/context/configuration/plugin/ConfigurationStateController.kt | 137593157 |
package ksm.context.configuration.plugin
import ksm.annotation.MutateContext
import ksm.context.StateContext
import ksm.context.configuration.interceptor.ConfigurationInterceptor
import ksm.plugin.Plugin
public object ConfigurationPlugin : Plugin.Singleton<ConfigurationPlugin> {
@MutateContext
override fun install(context: StateContext): StateContext {
return context + ConfigurationStateController()
}
public fun addConfigurationInterceptor(
context: StateContext,
interceptor: ConfigurationInterceptor
) {
context.require(ConfigurationStateController).addInterceptor(interceptor)
}
@MutateContext
public fun onConfigure(context: StateContext): StateContext {
return context.require(ConfigurationStateController).onConfigure(context)
}
}
| ksm/core/src/commonMain/kotlin/ksm/context/configuration/plugin/ConfigurationPlugin.kt | 661931800 |
package ksm.context.configuration.interceptor
import ksm.annotation.MutateContext
import ksm.context.StateContext
public fun interface ConfigurationInterceptor {
@MutateContext
public fun onConfigure(context: StateContext): StateContext
}
| ksm/core/src/commonMain/kotlin/ksm/context/configuration/interceptor/ConfigurationInterceptor.kt | 3181316989 |
package ksm.context.configuration.interceptor
import ksm.context.StateContext
import ksm.context.configuration.plugin.ConfigurationPlugin
import ksm.plugin.plugin
public fun StateContext.addConfigurationInterceptor(interceptor: ConfigurationInterceptor) {
plugin(ConfigurationPlugin).addConfigurationInterceptor(
context = this,
interceptor = interceptor
)
}
| ksm/core/src/commonMain/kotlin/ksm/context/configuration/interceptor/StateContext.kt | 3661985718 |
package ksm.context
import ksm.annotation.MutateContext
import ksm.context.configuration.plugin.ConfigurationPlugin
import ksm.lifecycle.plugin.LifecyclePlugin
@OptIn(MutateContext::class)
public inline fun StateContext.createChildContext(
setup: (StateContext) -> Unit = {}
): StateContext {
val applied = this[ConfigurationPlugin]
?.onConfigure(context = this)
?: this
applied.apply(setup)
applied[LifecyclePlugin]?.onCreate(applied)
applied[LifecyclePlugin]?.onResume(applied)
return applied
}
| ksm/core/src/commonMain/kotlin/ksm/context/CreateChildStateContext.kt | 3849692512 |
package ksm.context
import ksm.annotation.MutateContext
import ksm.plugin.Plugin
@MutateContext
public fun StateContext.install(plugin: Plugin): StateContext {
return plugin.install(context = this + plugin)
}
| ksm/core/src/commonMain/kotlin/ksm/context/InstallPlugin.kt | 61686818 |
package ksm.context
import ksm.annotation.MutateContext
public interface StateContext {
/**
* Contract: Variable should be constant
*/
public val keys: Set<Key<*>>
public operator fun <T : Element> get(key: Key<T>): T?
public fun <T : Element> require(key: Key<T>): T = get(key) ?: error("Cannot find element with key $key")
public operator fun contains(key: Key<*>): Boolean = get(key) != null
@MutateContext
public operator fun plus(other: Element): StateContext {
return plus(other.asContext())
}
@MutateContext
public operator fun plus(other: StateContext): StateContext {
if (this === Empty) return other
return CombinedContext(left = this, right = other)
}
@MutateContext
public operator fun minus(key: Key<*>): StateContext
public interface Key<out T : Element>
public interface Element {
public val key: Key<*>
public interface Singleton<out T : Singleton<T>> : Element, Key<T> {
override val key: Key<T> get() = this
}
}
public object Empty : StateContext {
override val keys: Set<Key<*>> = emptySet()
override fun <T : Element> get(key: Key<T>): T? = null
@MutateContext
override fun minus(key: Key<*>): StateContext = this
}
}
public operator fun <T : StateContext.Element> StateContext?.get(key: StateContext.Key<T>): T? {
return this?.get(key)
}
public operator fun StateContext?.contains(key: StateContext.Key<*>): Boolean {
return this?.contains(key) ?: false
}
public fun StateContext?.orEmpty(): StateContext = this ?: StateContext.Empty
| ksm/core/src/commonMain/kotlin/ksm/context/StateContext.kt | 3971603256 |
package ksm.context
import ksm.annotation.MutateContext
/**
* [right] elements overwrite [left] elements
*/
internal class CombinedContext(
val left: StateContext,
val right: StateContext
) : StateContext {
override val keys = left.keys + right.keys
override fun <T : StateContext.Element> get(key: StateContext.Key<T>): T? {
return right[key] ?: left[key]
}
@MutateContext
override fun minus(key: StateContext.Key<*>): StateContext {
return CombinedContext(left.minus(key), right.minus(key))
}
}
| ksm/core/src/commonMain/kotlin/ksm/context/CombinedContext.kt | 332562520 |
package ksm.context
import ksm.annotation.MutateContext
public fun StateContext.Element.asContext(): StateContext {
return SingleElementContext(element = this)
}
private class SingleElementContext(val element: StateContext.Element): StateContext {
override val keys = setOf(element.key)
@Suppress("UNCHECKED_CAST")
override fun <T : StateContext.Element> get(key: StateContext.Key<T>): T? {
return if (element.key == key) (element as T) else null
}
@MutateContext
override fun minus(key: StateContext.Key<*>): StateContext {
return if (key == element.key) {
StateContext.Empty
} else {
this
}
}
}
| ksm/core/src/commonMain/kotlin/ksm/context/SingleElementContext.kt | 2263089336 |
package ksm.context
import ksm.finish.once.plugin.FinishOncePlugin
import ksm.lifecycle.plugin.LifecyclePlugin
public fun StateContext.finish(): StateContext {
this[FinishOncePlugin]?.finish(context = this)
this[LifecyclePlugin]?.onPause(context = this)
this[LifecyclePlugin]?.onFinish(context = this)
return this
}
| ksm/core/src/commonMain/kotlin/ksm/context/FinishStateContext.kt | 455598839 |
package ksm.plugin
import ksm.annotation.MutateContext
import ksm.context.StateContext
public interface Plugin : StateContext.Element {
override val key: StateContext.Key<*>
@MutateContext
public fun install(context: StateContext): StateContext
public interface Singleton<out T : Singleton<T>> : Plugin, StateContext.Element.Singleton<T> {
override val key: StateContext.Key<T> get() = this
}
}
| ksm/core/src/commonMain/kotlin/ksm/plugin/Plugin.kt | 4063444554 |
package ksm.plugin
import ksm.context.StateContext
@Deprecated(
message = "Use array access syntax instead",
replaceWith = ReplaceWith(
expression = "get(key)"
)
)
public inline fun <reified T : Plugin> StateContext.pluginOrNull(key: StateContext.Key<T>): T? {
return this[key]
}
public inline fun <reified T : Plugin> StateContext.ifPlugin(
key: StateContext.Key<T>,
block: T.() -> Unit
) {
this[key]?.run(block)
}
public inline fun <reified T : Plugin> StateContext.plugin(key: StateContext.Key<T>): T {
return this[key] ?: error("Plugin `${T::class.simpleName}` is not installed")
}
public inline fun <reified T : Plugin> StateContext.withPlugin(
key: StateContext.Key<T>,
block: T.() -> Unit
) {
plugin(key).run(block)
}
| ksm/core/src/commonMain/kotlin/ksm/plugin/StateController.kt | 99372112 |
package ksm.lifecycle
import ksm.context.StateContext
import ksm.lifecycle.plugin.LifecyclePlugin
import ksm.plugin.plugin
public fun StateContext.addLifecycleInterceptor(interceptor: LifecycleInterceptor) {
plugin(LifecyclePlugin).addLifecycleInterceptor(
context = this,
observer = interceptor
)
}
| ksm/core/src/commonMain/kotlin/ksm/lifecycle/StateContext.kt | 1507705602 |
package ksm.lifecycle.plugin
import ksm.annotation.MutateContext
import ksm.context.StateContext
import ksm.context.configuration.interceptor.ConfigurationInterceptor
import ksm.context.configuration.interceptor.addConfigurationInterceptor
import ksm.lifecycle.LifecycleInterceptor
import ksm.plugin.Plugin
public object LifecyclePlugin : Plugin.Singleton<LifecyclePlugin> {
@MutateContext
override fun install(context: StateContext): StateContext {
context.addConfigurationInterceptor(Configuration)
return context + LifecycleEntry()
}
private object Configuration : ConfigurationInterceptor {
@MutateContext
override fun onConfigure(context: StateContext): StateContext {
return context + LifecycleEntry()
}
}
public fun addLifecycleInterceptor(
context: StateContext,
observer: LifecycleInterceptor
) {
context.require(LifecycleEntry).addInterceptor(observer)
}
public fun onCreate(context: StateContext) {
context.require(LifecycleEntry).onCreate(context)
}
public fun onResume(context: StateContext) {
context.require(LifecycleEntry).onResume(context)
}
public fun onPause(context: StateContext) {
context.require(LifecycleEntry).onPause(context)
}
public fun onFinish(context: StateContext) {
context.require(LifecycleEntry).onFinish(context)
}
}
| ksm/core/src/commonMain/kotlin/ksm/lifecycle/plugin/LifecyclePlugin.kt | 2415390670 |
package ksm.lifecycle.plugin
import ksm.context.StateContext
import ksm.lifecycle.LifecycleInterceptor
internal class LifecycleEntry : StateContext.Element {
override val key = LifecycleEntry
private val observers = mutableListOf<LifecycleInterceptor>()
fun addInterceptor(observer: LifecycleInterceptor) {
observers += observer
}
fun onCreate(context: StateContext) {
for (observer in observers) {
observer.onCreate(context)
}
}
fun onResume(context: StateContext) {
for (observer in observers) {
observer.onResume(context)
}
}
fun onPause(context: StateContext) {
for (observer in observers) {
observer.onPause(context)
}
}
fun onFinish(context: StateContext) {
for (observer in observers) {
observer.onFinish(context)
}
}
companion object : StateContext.Key<LifecycleEntry>
}
| ksm/core/src/commonMain/kotlin/ksm/lifecycle/plugin/LifecycleEntry.kt | 2088797428 |
package ksm.lifecycle
import ksm.context.StateContext
public interface LifecycleInterceptor {
public fun onCreate(context: StateContext) {}
public fun onResume(context: StateContext) {}
public fun onPause(context: StateContext) {}
public fun onFinish(context: StateContext) {}
}
| ksm/core/src/commonMain/kotlin/ksm/lifecycle/LifecycleInterceptor.kt | 3661041322 |
package ksm.annotation
@RequiresOptIn(
message = "This constructor is intended to be used by library developers only, consider to use another one.",
level = RequiresOptIn.Level.ERROR
)
public annotation class LibraryConstructor
| ksm/core/src/commonMain/kotlin/ksm/annotation/LibraryConstructor.kt | 1533438651 |
package ksm.annotation
@RequiresOptIn(
message = "Indicates that the following function creates a copy of context. " +
"Do not opt-in! Only propagate this annotation"
)
public annotation class MutateContext
| ksm/core/src/commonMain/kotlin/ksm/annotation/MutateContext.kt | 3514056274 |
package ksm.finish.once.plugin
import ksm.annotation.MutateContext
import ksm.context.StateContext
import ksm.context.configuration.interceptor.ConfigurationInterceptor
import ksm.context.configuration.interceptor.addConfigurationInterceptor
import ksm.plugin.Plugin
public object FinishOncePlugin : Plugin.Singleton<FinishOncePlugin> {
@MutateContext
override fun install(context: StateContext): StateContext {
context.addConfigurationInterceptor(Configuration)
return context
}
private object Configuration : ConfigurationInterceptor {
@MutateContext
override fun onConfigure(context: StateContext): StateContext {
return context + FinishOnceEntry()
}
}
public fun checkCanCreate(context: StateContext) {
context.require(FinishOnceEntry).checkCanCreate()
}
public fun finish(context: StateContext) {
context.require(FinishOnceEntry).finish()
}
}
| ksm/core/src/commonMain/kotlin/ksm/finish/once/plugin/FinishOncePlugin.kt | 110272186 |
package ksm.finish.once.plugin
import ksm.context.StateContext
internal class FinishOnceEntry : StateContext.Element {
override val key = FinishOncePlugin
private var isFinished: Boolean = false
fun checkCanCreate() {
if (isFinished) error("Current state was already finished, cannot create a new one")
}
fun finish() {
if (isFinished) error("Current state was already finished, cannot finish it twice")
isFinished = true
}
companion object : StateContext.Key<FinishOnceEntry>
}
| ksm/core/src/commonMain/kotlin/ksm/finish/once/plugin/FinishOnceEntry.kt | 989880880 |
package ksm
import ksm.annotation.LibraryConstructor
import ksm.builder.StateControllerBuilder
import ksm.context.StateContext
import ksm.context.configuration.plugin.ConfigurationPlugin
import ksm.context.finish
import ksm.finish.once.plugin.FinishOncePlugin
import ksm.lifecycle.plugin.LifecyclePlugin
@LibraryConstructor
public inline fun pluginStateController(
context: StateContext = StateContext.Empty,
enableConfiguration: Boolean = true,
enableLifecycle: Boolean = true,
enableFinishOnce: Boolean = true,
builder: StateControllerBuilder.() -> Unit = {}
): StateController {
return StateControllerBuilder(context).apply {
if (enableConfiguration) install(ConfigurationPlugin)
if (enableLifecycle) install(LifecyclePlugin)
if (enableFinishOnce) install(FinishOncePlugin)
builder()
}.context.asStateController()
}
public interface StateController {
public val context: StateContext
}
public fun StateController.finish() {
context.finish()
}
public fun StateContext.asStateController(): StateController {
return object : StateController {
override val context = this@asStateController
}
}
| ksm/core/src/commonMain/kotlin/ksm/StateController.kt | 3242754130 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.