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