path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
kopring_graphql_querydsl/common/lib/src/main/kotlin/kr/co/anna/lib/security/jwt/JwtProperties.kt
1263105240
package kr.co.anna.lib.security.jwt import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.boot.context.properties.ConstructorBinding @ConfigurationProperties(prefix = "jwt") @ConstructorBinding data class JwtProperties ( val base64EncodedSecret: String, // JWT ์ƒ์„ฑ/ํŒŒ์‹ฑ์— ์‚ฌ์šฉํ•˜๋Š” ๋น„๋ฐ€ํ‚ค val tokenDurationHr: Int? = 24, // ์‚ฌ์šฉ์ž ํ† ํฐ ์œ ํšจ ์‹œ๊ฐ„ val swaggerTokenDurationHr: Int? = 120, // ์Šค์›จ๊ฑฐ ํ† ํฐ ์œ ํšจ ์‹œ๊ฐ„ val generatorEnabled: Boolean = false, // ์Šค์›จ๊ฑฐ์— ํ† ํฐ ์ƒ์„ฑ๊ธฐ ํฌํ•จ ์—ฌ๋ถ€ )
kopring_graphql_querydsl/common/lib/src/main/kotlin/kr/co/anna/lib/security/jwt/JwtAuthFilter.kt
2888317905
package kr.co.anna.lib.security.jwt import org.springframework.security.core.context.SecurityContextHolder import org.springframework.web.filter.OncePerRequestFilter import javax.servlet.FilterChain import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse class JwtAuthFilter(private val jwtProcessor: JwtProcessor) : OncePerRequestFilter() { override fun doFilterInternal( request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain ) { val jwtFromRequest = getJwtFromRequest(request) try { if (!jwtFromRequest.isNullOrBlank()) { SecurityContextHolder.getContext().authentication = jwtProcessor.extractAuthentication(jwtFromRequest) // SecurityContext ์— Authentication ๊ฐ์ฒด๋ฅผ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค. } } catch (e: Exception) { SecurityContextHolder.clearContext() } filterChain.doFilter(request, response) } private val BEARER_PREFIX = "Bearer " private fun getJwtFromRequest(request: HttpServletRequest): String? { val bearerToken = request.getHeader("Authorization") return if (!bearerToken.isNullOrBlank() && bearerToken.startsWith(BEARER_PREFIX, true)) { bearerToken.substring(BEARER_PREFIX.length) } else null } }
kopring_graphql_querydsl/common/lib/src/main/kotlin/kr/co/anna/lib/security/jwt/JwtKeys.kt
2269066340
package kr.co.anna.lib.security.jwt enum class JwtKeys(val keyName: String) { UID("uid"), USER_OID("userOid") }
kopring_graphql_querydsl/common/lib/src/main/kotlin/kr/co/anna/lib/security/jwt/JwtGenerator.kt
4018073854
package kr.co.anna.lib.security.jwt import io.jsonwebtoken.Jwts import io.jsonwebtoken.SignatureAlgorithm import io.jsonwebtoken.io.Decoders import io.jsonwebtoken.security.Keys import kr.co.anna.domain.model.Role import kr.co.anna.lib.security.SignInUser import org.slf4j.LoggerFactory import org.springframework.stereotype.Component import java.util.* import javax.crypto.SecretKey /** * JWT(JSON Web Token)๋ฅผ ์ƒ์„ฑํ•˜๋Š” ์ฑ…์ž„์„ ๊ฐ€์ง„ ๊ฐ์ฒด */ @Component class JwtGenerator( private val jwtProperties: JwtProperties, ) { private val key: SecretKey = Keys.hmacShaKeyFor(Decoders.BASE64.decode(jwtProperties.base64EncodedSecret)) fun generateUserToken(signInUser: SignInUser): String { return Jwts.builder() .setSubject("kopring_graphql_querydsl") .claim(JwtKeys.UID.keyName, signInUser.username) .claim(JwtKeys.USER_OID.keyName, signInUser.userOid()) .signWith(key, SignatureAlgorithm.HS512) .setExpiration(expiration(jwtProperties.swaggerTokenDurationHr)) .compact() } private fun expiration(hour: Int?): Date = Date(Date().time + (1000 * 60 * 60 * hour!!.toInt())) }
kopring_graphql_querydsl/common/lib/src/main/kotlin/kr/co/anna/lib/security/SignInUser.kt
1144070753
package kr.co.anna.lib.security import kr.co.anna.domain.model.user.User import org.springframework.security.core.GrantedAuthority import org.springframework.security.core.authority.SimpleGrantedAuthority import org.springframework.security.core.userdetails.UserDetails class SignInUser( val user: User, ) : UserDetails { override fun getAuthorities(): MutableCollection<out GrantedAuthority> { return user.role().map { SimpleGrantedAuthority(it.getCode()) }.toMutableSet() } override fun getPassword(): String { return user.password() } override fun getUsername(): String { return user.userId() } override fun isAccountNonExpired(): Boolean { return true } override fun isAccountNonLocked(): Boolean { return true } override fun isCredentialsNonExpired(): Boolean { return true } override fun isEnabled(): Boolean { return user.checkActiveUser() } fun name() = user.name() fun email() = user.email() fun userOid() = user.oid fun roles() = user.role() }
kopring_graphql_querydsl/common/lib/src/main/kotlin/kr/co/anna/lib/security/AuthUser.kt
1635774426
package kr.co.anna.lib.security import kr.co.anna.domain.model.Role import org.springframework.security.core.GrantedAuthority /** * ๋กœ๊ทธ์ธ ํ•œ ์‚ฌ์šฉ์ž์˜ ์ •๋ณด๋ฅผ ๋‹ด๋Š” ๊ฐ์ฒด * ์ด ๊ฐ์ฒด๋Š” Spring Security Context ์— ์ €์žฅ๋˜๊ณ , * ํ•„์š”ํ•  ๋•Œ SecurityContextHolder.getContext().authentication.principal as? AuthUser ๋ฅผ ํ˜ธ์ถœํ•ด์„œ ์–ป๋“ค ์ˆ˜ ์žˆ๋‹ค. */ data class AuthUser( val userId: String, val userOid: Long, val authorities: Collection<GrantedAuthority>, val roles: List<Role> ) { constructor(signInUser: SignInUser) : this( signInUser.username, signInUser.userOid()!!, signInUser.authorities, signInUser.roles() ) fun isFreePass(): Boolean { return authorities.map { it.authority }.contains(Role.ROLE_SYS_ADMIN.getCode()) } }
kopring_graphql_querydsl/common/lib/src/main/kotlin/kr/co/anna/lib/security/UserDetailsServiceImpl.kt
2770490313
package kr.co.anna.lib.security import kr.co.anna.domain.repository.user.UserRepository import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.stereotype.Service @Service class UserDetailsServiceImpl( private val userRepository: UserRepository, ) : UserDetailsService { override fun loadUserByUsername(userId: String?): UserDetails { if (userId.isNullOrEmpty()) throw IllegalArgumentException("๋กœ๊ทธ์ธ ์•„์ด๋””๊ฐ€ ๋น„์–ด์žˆ์Šต๋‹ˆ๋‹ค.") val user = userRepository.getByUserId(userId) return SignInUser(user) } }
kopring_graphql_querydsl/common/lib/src/main/kotlin/kr/co/anna/lib/security/SecurityUtil.kt
1713036318
package kr.co.anna.lib.security import kr.co.anna.domain.model.Role import kr.co.anna.lib.utils.MessageUtil import org.springframework.security.access.AccessDeniedException import org.springframework.security.core.context.SecurityContextHolder object SecurityUtil { private fun authUser(): AuthUser { val authUser = SecurityContextHolder.getContext().authentication.principal as? AuthUser ?: throw RuntimeException(MessageUtil.getMessage("UNAUTHENTICATED_USER")) return authUser } fun checkUserOid(userOid: Long) { val authUser = authUser() if (authUser.isFreePass()) return if (authUser.userOid != userOid) { throw AccessDeniedException(MessageUtil.getMessage("UNAUTHORIZED_ACCESS")) } } fun checkUserId(userId: String) { val authUser = authUser() if (authUser.isFreePass()) return if (authUser.userId != userId) { throw AccessDeniedException(MessageUtil.getMessage("UNAUTHORIZED_ACCESS")) } } fun checkManagerRole() { val authUser = authUser() if (authUser.isFreePass()) return if (!authUser.roles.any { it.getCode().equals(Role.ROLE_MANAGER.getCode()) }) { throw AccessDeniedException(MessageUtil.getMessage("ROLE_NOT_FOUND")) } } }
kopring_graphql_querydsl/common/lib/src/main/kotlin/kr/co/anna/lib/utils/MessageUtil.kt
511224098
package kr.co.anna.lib.utils import org.springframework.context.support.MessageSourceAccessor object MessageUtil { var messageSourceAccessor: MessageSourceAccessor? = null fun getMessage(key: String?): String { return messageSourceAccessor!!.getMessage(key!!) } }
kopring_graphql_querydsl/common/lib/src/main/kotlin/kr/co/anna/lib/error/ErrorBody.kt
4263947623
package kr.co.anna.lib.error import com.fasterxml.jackson.annotation.JsonInclude import org.springframework.validation.BindingResult import java.time.ZoneId import java.time.ZonedDateTime class ErrorBody( val message: String, @JsonInclude(JsonInclude.Include.NON_NULL) val requestUrl: String? = null, val timestamp: ZonedDateTime, @JsonInclude(JsonInclude.Include.NON_NULL) val exceptionName: String? = null, @JsonInclude(JsonInclude.Include.NON_EMPTY) val errors: List<FieldErr>? = null, ) { constructor(message: String, requestUrl: String?, exceptionName: String?) : this(message, requestUrl, ZonedDateTime.now(ZoneId.of("Z")), exceptionName) constructor(message: String, requestUrl: String?, exceptionName: String?, errors: BindingResult) : this(message, requestUrl, ZonedDateTime.now(ZoneId.of("Z")), exceptionName, FieldErr.from(errors)) }
kopring_graphql_querydsl/common/lib/src/main/kotlin/kr/co/anna/lib/error/FieldErr.kt
3746848449
package kr.co.anna.lib.error import org.springframework.validation.BindingResult class FieldErr( val field: String, val value: String?, val reason: String?) { companion object { internal fun from(bindingResult: BindingResult): List<FieldErr> { return bindingResult.fieldErrors .map { FieldErr( it.field, it.rejectedValue?.toString(), it.defaultMessage ) } } } }
kopring_graphql_querydsl/common/lib/src/main/kotlin/kr/co/anna/lib/error/UnauthenticatedAccessException.kt
2612694833
package kr.co.anna.lib.error import kr.co.anna.lib.utils.MessageUtil class UnauthenticatedAccessException : RuntimeException(MessageUtil.getMessage("UNAUTHORIZED_ACCESS")) { }
kopring_graphql_querydsl/common/lib/src/main/kotlin/kr/co/anna/lib/error/ErrorResolvingFilter.kt
719353058
package kr.co.anna.lib.error import org.slf4j.LoggerFactory import org.springframework.web.filter.OncePerRequestFilter import org.springframework.web.servlet.HandlerExceptionResolver import javax.servlet.FilterChain import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse /** * Filter Chain ์•ˆ์—์„œ ๋ฐœ์ƒํ•œ ์˜ˆ์™ธ๋ฅผ GlobalExceptionHandler ์—์„œ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ฃผ๋Š” ํ•„ํ„ฐ * Security Config ์— ์ถ”๊ฐ€ํ•  ๋•Œ ํ•„ํ„ฐ ์ฒด์ธ ์•ž์ชฝ์— ๋†“์•„์•ผ ๋” ๋„“์€ ๋ฒ”์œ„์˜ ํ•„ํ„ฐ ์ฒด์ธ ์ปค๋ฒ„ ๊ฐ€๋Šฅ * ํ•„ํ„ฐ ์ฒด์ธ ๋ชฉ๋ก: https://docs.spring.io/spring-security/site/docs/current/reference/html5/#filter-stack */ class ErrorResolvingFilter( private val handlerExceptionResolver: HandlerExceptionResolver ): OncePerRequestFilter() { private val log = LoggerFactory.getLogger(javaClass) override fun doFilterInternal( request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain ) { try { filterChain.doFilter(request, response) } catch (e: Exception) { log.error("Exception in Filter Chain:", e) handlerExceptionResolver.resolveException(request, response, null, e) } } }
kopring_graphql_querydsl/common/lib/src/main/kotlin/kr/co/anna/lib/error/InvalidException.kt
1222424123
package kr.co.anna.lib.error import org.springframework.validation.BindingResult /** * ๋ฐธ๋ฆฌ๋ฐ์ด์…˜ ์—๋Ÿฌ์ฒ˜๋ฆฌ */ class InvalidException( message: String? = null, val errors: BindingResult, ) : RuntimeException( message ) { }
kopring_graphql_querydsl/common/lib/src/main/kotlin/kr/co/anna/lib/error/JwtUnauthenticatedAccessException.kt
3047460724
package kr.co.anna.lib.error import kr.co.anna.lib.utils.MessageUtil class JwtUnauthenticatedAccessException : RuntimeException(MessageUtil.getMessage("UNAUTHORIZED_ACCESS")) { }
kopring_graphql_querydsl/common/lib/src/main/kotlin/kr/co/anna/lib/error/GlobalExceptionHandler.kt
4211151565
package kr.co.anna.lib.error import kr.co.anna.domain.exception.DomainEntityNotFoundException import kr.co.anna.domain.exception.NotAllowedException import kr.co.anna.lib.security.AuthUser import org.slf4j.LoggerFactory import org.slf4j.MDC import org.springframework.core.NestedRuntimeException import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.security.access.AccessDeniedException import org.springframework.security.authentication.BadCredentialsException import org.springframework.security.core.context.SecurityContextHolder import org.springframework.web.bind.annotation.ExceptionHandler import org.springframework.web.bind.annotation.RestControllerAdvice import org.springframework.web.servlet.support.ServletUriComponentsBuilder import java.security.InvalidParameterException @RestControllerAdvice class GlobalExceptionHandler( ) { @ExceptionHandler(IllegalArgumentException::class) fun handleIllegalArgumentException(e: IllegalArgumentException): ResponseEntity<ErrorBody> { log(e,e.javaClass.simpleName) val errorBody = ErrorBody( message = e.message ?: "๋ฉ”์‹œ์ง€ ์—†๋Š” IllegalArgumentException ์ด ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.", requestUrl = ServletUriComponentsBuilder.fromCurrentRequestUri().toUriString() ,e.javaClass.simpleName ) return ResponseEntity(errorBody, HttpStatus.BAD_REQUEST) } /** * ์ธ๊ฐ€์ฒ˜๋ฆฌ */ @ExceptionHandler(AccessDeniedException::class) fun handleAccessDeniedException( e: AccessDeniedException ): ResponseEntity<ErrorBody> { log(e,e.javaClass.simpleName) val errorBody = ErrorBody( message = e.message ?: "ํ—ˆ๊ฐ€๋˜์ง€ ์•Š์€ ์ ‘๊ทผ์ž…๋‹ˆ๋‹ค.", requestUrl = ServletUriComponentsBuilder.fromCurrentRequestUri().toUriString() ,e.javaClass.simpleName ) return ResponseEntity(errorBody, HttpStatus.FORBIDDEN) } /** * ์ธ์ฆ์ฒ˜๋ฆฌ */ @ExceptionHandler( JwtUnauthenticatedAccessException::class, UnauthenticatedAccessException::class, BadCredentialsException::class ) fun handleBadCredentialsException( e: RuntimeException ): ResponseEntity<ErrorBody> { log(e,e.javaClass.simpleName) val errorBody = ErrorBody( message = e.message ?: "๋กœ๊ทธ์ธ ์ •๋ณด๊ฐ€ ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์Šต๋‹ˆ๋‹ค.", requestUrl = ServletUriComponentsBuilder.fromCurrentRequestUri().toUriString() ,e.javaClass.simpleName ) return ResponseEntity(errorBody, HttpStatus.UNAUTHORIZED) } /** * ๋น„์ฆˆ๋‹ˆ์Šค ์ •์˜ ์ต์…‰์…˜ * ๊ธฐ๋Šฅ์ œํ•œ */ @ExceptionHandler(NotAllowedException::class) fun handleNotAllowedException( e: NotAllowedException ): ResponseEntity<ErrorBody> { log(e,e.javaClass.simpleName) val errorBody = ErrorBody( message = e.message ?: "ํ—ˆ์šฉ๋˜์ง€ ์•Š๋Š” ๊ธฐ๋Šฅ์ž…๋‹ˆ๋‹ค.", requestUrl = ServletUriComponentsBuilder.fromCurrentRequestUri().toUriString() ,e.javaClass.simpleName ) return ResponseEntity(errorBody, HttpStatus.FORBIDDEN) } /** * ๋„๋ฉ”์ธ ์ต์…‰์…˜ */ @ExceptionHandler(DomainEntityNotFoundException::class) fun handleDomainEntityNotFoundException( e: DomainEntityNotFoundException ): ResponseEntity<ErrorBody> { log(e,e.entityClazz.simpleName) val errorBody = ErrorBody( message = e.message ?: "ํ•ด๋‹น์ •๋ณด๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.", requestUrl = ServletUriComponentsBuilder.fromCurrentRequestUri().toUriString() ,e.entityClazz.simpleName ) return ResponseEntity(errorBody, HttpStatus.NOT_FOUND) } @ExceptionHandler(NestedRuntimeException::class) fun handleNestedRuntimeException(e: NestedRuntimeException): ResponseEntity<ErrorBody> { log(e,e.javaClass.simpleName) val errorBody = ErrorBody( message = e.rootCause?.message ?: e.message ?: "๋ฉ”์‹œ์ง€ ์—†๋Š” NestedRuntimeException ์ด ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.", requestUrl = ServletUriComponentsBuilder.fromCurrentRequestUri().toUriString() ,e.javaClass.simpleName ) return ResponseEntity(errorBody, HttpStatus.INTERNAL_SERVER_ERROR) } /** * ๋ฐธ๋ฆฌ๋ฐ์ด์…˜ ๊ฐ’ ๊ฒ€์ฆ ์—๋Ÿฌ */ @ExceptionHandler(InvalidException::class, InvalidParameterException::class) fun handleInvaliduserException(e: InvalidException): ResponseEntity<ErrorBody> { log(e,e.javaClass.simpleName) val errorBody = ErrorBody( message = e.message ?: "๋ฉ”์‹œ์ง€ ์—†๋Š” InvalidException ์ด ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.", requestUrl = ServletUriComponentsBuilder.fromCurrentRequestUri().toUriString(), e.javaClass.simpleName, errors = e.errors, ) return ResponseEntity(errorBody, HttpStatus.BAD_REQUEST) } @ExceptionHandler(Exception::class) fun handleException(e: Exception): ResponseEntity<ErrorBody> { log(e,e.javaClass.simpleName) val errorBody = ErrorBody( message = e.message ?: "๋ฉ”์‹œ์ง€ ์—†๋Š” Exception ์ด ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.", requestUrl = ServletUriComponentsBuilder.fromCurrentRequestUri().toUriString() ,e.javaClass.simpleName ) return ResponseEntity(errorBody, HttpStatus.INTERNAL_SERVER_ERROR) } private fun setUserId() { val authUser = SecurityContextHolder.getContext().authentication.principal as? AuthUser MDC.put("userId", authUser?.userId) } private fun log( e: Exception, className : String? ) { setUserId() log.error("$className | $e") MDC.clear() } private val log = LoggerFactory.getLogger(javaClass) }
kopring_graphql_querydsl/common/domain/src/main/kotlin/kr/co/anna/domain/repository/user/UserRepository.kt
1162546284
package kr.co.anna.domain.repository.user import kr.co.anna.domain.model.user.User import org.springframework.data.jpa.repository.JpaRepository interface UserRepository : JpaRepository<User, Long>, UserRepositoryCustom
kopring_graphql_querydsl/common/domain/src/main/kotlin/kr/co/anna/domain/repository/user/UserRepositoryCustom.kt
3336776088
package kr.co.anna.domain.repository.user import kr.co.anna.domain.model.user.User import org.springframework.data.domain.Page import org.springframework.data.domain.Pageable import java.util.* interface UserRepositoryCustom { fun getByOid(oid: Long): User fun getByUserId(userId: String) : User }
kopring_graphql_querydsl/common/domain/src/main/kotlin/kr/co/anna/domain/repository/user/UserRepositoryImpl.kt
3325335043
package kr.co.anna.domain.repository.user import com.querydsl.core.types.dsl.BooleanExpression import kr.co.anna.domain._common.DomainMessageUtil import kr.co.anna.domain.exception.DomainEntityNotFoundException import kr.co.anna.domain.model.user.QUser import kr.co.anna.domain.model.user.User import org.springframework.data.jpa.repository.support.QuerydslRepositorySupport class UserRepositoryImpl : QuerydslRepositorySupport(User::class.java), UserRepositoryCustom { private val qUser = QUser.user override fun getByOid(oid: Long): User { return from(qUser) .where( isActive(), qUser.oid.eq(oid) ) .fetchOne() ?: throw DomainEntityNotFoundException(oid, User::class, DomainMessageUtil.getMessage("USER_NOT_FOUND")) } override fun getByUserId(userId: String): User { return from(qUser) .where( isActive(), qUser.userId.eq(userId) ) .fetchOne() ?: throw DomainEntityNotFoundException(userId, User::class, DomainMessageUtil.getMessage("USER_NOT_FOUND")) } private fun isActive(): BooleanExpression? { return qUser.status.eq(User.Status.ACTIVE) } }
kopring_graphql_querydsl/common/domain/src/main/kotlin/kr/co/anna/domain/converter/RoleEnumToListConvert.kt
55877664
package kr.co.anna.domain.converter import kr.co.anna.domain._common.EnumModel import kr.co.anna.domain.model.Role import javax.persistence.Convert /** * role list num ๋ณ€ํ™˜ */ @Convert class RoleEnumToListConvert(private val targetEnumClass: Class<out EnumModel> = Role::class.java) : EnumToListConverter(targetEnumClass) { }
kopring_graphql_querydsl/common/domain/src/main/kotlin/kr/co/anna/domain/converter/BooleanToYNConverter.kt
3130778124
package kr.co.anna.domain.converter import javax.persistence.AttributeConverter import javax.persistence.Converter /** * DB data 'Y/N' ๊ณผ ๊ฐ์ฒด boolean ์ปจ๋ฒ„ํ„ฐ * ๊ธ€๋กœ๋ฒŒ ์„ค์ • */ @Converter(autoApply = true) class BooleanToYNConverter: AttributeConverter<Boolean, String> { override fun convertToDatabaseColumn(attribute: Boolean?): String { if (attribute == null) return "N" return if (attribute) "Y" else "N" } override fun convertToEntityAttribute(yn: String?): Boolean { return "Y".equals(yn, true) } }
kopring_graphql_querydsl/common/domain/src/main/kotlin/kr/co/anna/domain/converter/EnumToListConverter.kt
3993624570
package kr.co.anna.domain.converter import kr.co.anna.domain._common.EnumModel import javax.persistence.AttributeConverter /** * ์ฝค๋งˆ๋กœ ๊ตฌ๋ถ„๋œ ๋ฐ์ดํ„ฐ๋“ค์„ ๊ฐ์ฒด์—์„œ ์ปฌ๋ ‰์…˜์œผ๋กœ ๋ณ€ํ™˜ */ open class EnumToListConverter(private var targetEnumClass: Class<out EnumModel>) : AttributeConverter<List<EnumModel>, String> { override fun convertToDatabaseColumn(attribute: List<EnumModel>?): String { if (attribute != null) { return attribute.joinToString(COMMA) { it.getCode() } } return "" } override fun convertToEntityAttribute(dbData: String?): List<EnumModel>? { if (!dbData.isNullOrBlank()) { return dbData.split(COMMA).toTypedArray() .map { att -> targetEnumClass.enumConstants.find { att == it.getCode() }!! } } return emptyList() } companion object { private const val COMMA: String = "," } }
kopring_graphql_querydsl/common/domain/src/main/kotlin/kr/co/anna/domain/converter/ListToPageConverter.kt
2971603361
package kr.co.anna.domain.converter import org.springframework.data.domain.Page import org.springframework.data.domain.PageImpl import org.springframework.data.domain.Pageable class ListToPageConverter { companion object { fun <E> pageFromListAndPageable( list: List<E>, pageable: Pageable, ): Page<E> { val start = pageable.offset.toInt() val end = (start + pageable.pageSize).coerceAtMost(list.size) return PageImpl(list.subList(start, end), pageable, list.size.toLong()) } } }
kopring_graphql_querydsl/common/domain/src/main/kotlin/kr/co/anna/domain/converter/StringToListConverter.kt
1887609633
package kr.co.anna.domain.converter import javax.persistence.AttributeConverter import javax.persistence.Converter @Converter class StringToListConverter : AttributeConverter<List<String>, String> { override fun convertToDatabaseColumn(recipients: List<String>): String { return recipients.joinToString(COMMA) } override fun convertToEntityAttribute(dbData: String): List<String> { return dbData.split(COMMA) } companion object { private const val COMMA: String = "," } }
kopring_graphql_querydsl/common/domain/src/main/kotlin/kr/co/anna/domain/config/P6SpyLogger.kt
2514191508
package kr.co.anna.domain.config import com.p6spy.engine.logging.Category import com.p6spy.engine.spy.appender.MessageFormattingStrategy import org.hibernate.engine.jdbc.internal.FormatStyle import java.util.* /** * JPA ๊ฐ€ ์‹คํ–‰ํ•˜๋Š” ์ฟผ๋ฆฌ์™€ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ๋ณผ ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ฃผ๋Š” P6Spy ์„ค์ • */ class P6SpyLogger : MessageFormattingStrategy { override fun formatMessage( connectionId: Int, now: String?, elapsed: Long, category: String, prepared: String?, sql: String, url: String? ): String { val callStack = Stack<String>() val stackTrace = Throwable().stackTrace for (i in stackTrace.indices) { val trace = stackTrace[i].toString() if (trace.startsWith("kr.co.anna") && !trace.contains("P6SpyLogger") && !trace.contains("$$")) { callStack.push(trace) } } val callStackBuilder = StringBuilder() var order = 1 while (callStack.size != 0) { callStackBuilder.append( """ ${order++}. ${callStack.pop()}""" ) } val message = StringBuilder() .append("\n\tExecution Time: ").append(elapsed).append(" ms\n") .append("\n----------------------------------------------------------------------------------------------------") .toString() return sqlFormat(sql, category, message) } private fun sqlFormat(sql: String, category: String, message: String): String { var sql = sql if (sql.trim { it <= ' ' }.isEmpty()) { return "" } if (Category.STATEMENT.getName().equals(category)) { val s = sql.trim { it <= ' ' }.toLowerCase(Locale.ROOT) sql = if (s.startsWith("create") || s.startsWith("alter") || s.startsWith("comment")) { FormatStyle.DDL .formatter .format(sql) } else { FormatStyle.BASIC .formatter .format(sql) } } return StringBuilder().append("\n") .append(sql) .append(message) .toString() } }
kopring_graphql_querydsl/common/domain/src/main/kotlin/kr/co/anna/domain/config/DomainMessageConfig.kt
2012719185
package kr.co.anna.domain.config import kr.co.anna.domain._common.DomainMessageUtil import org.springframework.context.MessageSource import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.support.MessageSourceAccessor import org.springframework.context.support.ReloadableResourceBundleMessageSource import org.springframework.web.servlet.LocaleResolver import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver import java.util.* @Configuration class DomainMessageConfig { @Bean fun localeResolverDomain(): LocaleResolver? { val localeResolver = AcceptHeaderLocaleResolver() localeResolver.defaultLocale = Locale.KOREA //์–ธ์–ด&๊ตญ๊ฐ€์ •๋ณด๊ฐ€ ์—†๋Š” ๊ฒฝ์šฐ ํ•œ๊ตญ์œผ๋กœ ์ธ์‹ return localeResolver } @Bean fun messageSourceDomain(): MessageSource? { val messageSource = ReloadableResourceBundleMessageSource() messageSource.setBasenames("classpath:/domain-messages/message") messageSource.setDefaultEncoding("utf-8") messageSource.setCacheSeconds(180) // ๋ฆฌ๋กœ๋”ฉ ๊ฐ„๊ฒฉ Locale.setDefault(Locale.KOREA) // ์ œ๊ณตํ•˜์ง€ ์•Š๋Š” ์–ธ์–ด๋กœ ์š”์ฒญ์ด ๋“ค์–ด์™”์„ ๋•Œ MessageSource์—์„œ ์‚ฌ์šฉํ•  ๊ธฐ๋ณธ ์–ธ์–ด์ •๋ณด. return messageSource } @Bean fun messageSourceAccessorDomain(): MessageSourceAccessor { return MessageSourceAccessor(messageSourceDomain()!!) } @Bean fun messageUtilsDomain() { DomainMessageUtil.messageSourceAccessorDomain = messageSourceAccessorDomain()!! } }
kopring_graphql_querydsl/common/domain/src/main/kotlin/kr/co/anna/domain/_common/DomainMessageUtil.kt
1375336538
package kr.co.anna.domain._common import org.springframework.context.support.MessageSourceAccessor object DomainMessageUtil { var messageSourceAccessorDomain: MessageSourceAccessor? = null fun getMessage(key: String?): String { println(messageSourceAccessorDomain) return messageSourceAccessorDomain!!.getMessage(key!!) } fun getMessage(key: String?, objs: Array<Any?>?): String { return messageSourceAccessorDomain!!.getMessage(key!!, objs) } }
kopring_graphql_querydsl/common/domain/src/main/kotlin/kr/co/anna/domain/_common/EnumModel.kt
2074747176
package kr.co.anna.domain._common interface EnumModel { fun getCode(): String fun getKorName(): String fun getEngName(): String }
kopring_graphql_querydsl/common/domain/src/main/kotlin/kr/co/anna/domain/_common/AbstractEntity.kt
12225837
package kr.co.anna.domain._common import org.springframework.data.annotation.CreatedBy import org.springframework.data.annotation.CreatedDate import org.springframework.data.annotation.LastModifiedBy import org.springframework.data.annotation.LastModifiedDate import org.springframework.data.jpa.domain.support.AuditingEntityListener import java.time.LocalDateTime import javax.persistence.* @MappedSuperclass @EntityListeners(AuditingEntityListener::class) abstract class AbstractEntity( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "OID") val oid: Long? ) { @CreatedDate @Column(name = "CREATED_DATE", updatable = false, columnDefinition = "DATETIME") protected lateinit var createdTime: LocalDateTime @Column(name = "CREATED_BY", updatable = false) @CreatedBy protected var createdBy: String? = null @LastModifiedDate @Column(name = "LAST_MODIFIED_DATE",columnDefinition = "DATETIME") protected lateinit var lastModifiedTime: LocalDateTime @Column(name = "LAST_MODIFIED_BY", updatable = true) @LastModifiedBy protected var lastModifiedBy: String? = null override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as AbstractEntity if (oid != other.oid) return false return true } override fun hashCode(): Int { return oid?.hashCode() ?: 0 } }
kopring_graphql_querydsl/common/domain/src/main/kotlin/kr/co/anna/domain/_common/EnumMapper.kt
2885664500
package kr.co.anna.domain._common class EnumMapper { private val factory: MutableMap<String, List<EnumValue>> = HashMap<String, List<EnumValue>>() private fun toEnumValues(e: Class<out EnumModel>): List<EnumValue> { return e.enumConstants.map { EnumValue(it) } } fun put(key: String, e: Class<out EnumModel>) { factory[key] = toEnumValues(e) } operator fun get(keys: String): Map<String, List<EnumValue>?> { return keys.split(",").toTypedArray().associateWith { key: String -> factory[key] } } }
kopring_graphql_querydsl/common/domain/src/main/kotlin/kr/co/anna/domain/_common/EnumValue.kt
2978858657
package kr.co.anna.domain._common data class EnumValue(val code: String, val korName: String, val engName: String) { constructor(enumModel: EnumModel) : this( enumModel.getCode(), enumModel.getKorName(), enumModel.getEngName() ) }
kopring_graphql_querydsl/common/domain/src/main/kotlin/kr/co/anna/domain/model/user/User.kt
1934470915
package kr.co.anna.domain.model.user import kr.co.anna.domain._common.AbstractEntity import kr.co.anna.domain._common.EnumModel import kr.co.anna.domain.converter.RoleEnumToListConvert import kr.co.anna.domain.model.Role import javax.persistence.* /** * ํšŒ์› */ @Entity @Table( name = "USER", indexes = [ Index(name = "IDX_USER__USER_ID", columnList = "USER_ID", unique = true), Index(name = "IDX_USER__EMAIL", columnList = "EMAIL", unique = true), ] ) class User( oid: Long? = null, //pk @Column(name = "USER_ID") private val userId: String, @Column(name = "NAME") private var name: String, @Column(name = "EMAIL") private var email: String, @Column(name = "PASSWORD") private var password: String, @Column(name = "ROLES") @Convert(converter = RoleEnumToListConvert::class) private var roles: List<Role>, @Enumerated(EnumType.STRING) @Column(name = "STATUS") private var status: Status = Status.ACTIVE, // ์‚ฌ์šฉ์ž ์ƒํƒœ ์ฝ”๋“œ ) : kr.co.anna.domain._common.AbstractEntity(oid) { fun name() = name fun email() = email fun password() = password fun status() = status fun role() = roles fun userId() = userId enum class Status(private val korName: String, private val engName: String) : EnumModel { ACTIVE("ํ™œ์„ฑ", "ACTIVE"), WITHDRAW("ํƒˆํ‡ด", "WITHDRAW"), INACTIVE("๋น„ํ™œ์„ฑ", "INACTIVE"); override fun getKorName(): String { return korName } override fun getEngName(): String { return engName } override fun getCode(): String { return name } } data class NewValue( val name: String?, val email: String? ) fun updateWith(n: NewValue) { if (!n.name.isNullOrBlank()) this.name = n.name if (!n.email.isNullOrBlank()) this.email = n.email } fun checkActiveUser(): Boolean { return status().equals(Status.ACTIVE) } }
kopring_graphql_querydsl/common/domain/src/main/kotlin/kr/co/anna/domain/model/Code.kt
3048380391
package kr.co.anna.domain.model import kr.co.anna.domain._common.EnumModel enum class Role(private val korName: String, private val engName: String) : EnumModel { ROLE_USER("์‚ฌ์šฉ์ž", "user"), ROLE_MANAGER("๋งค๋‹ˆ์ €", "MANAGER"), ROLE_SYS_ADMIN("์‹œ์Šคํ…œ๊ด€๋ฆฌ์ž", "systemAdmin"); override fun getKorName(): String { return korName } override fun getEngName(): String { return engName } override fun getCode(): String { return name } }
kopring_graphql_querydsl/common/domain/src/main/kotlin/kr/co/anna/domain/exception/DomainEntityNotFoundException.kt
576488397
package kr.co.anna.domain.exception import kr.co.anna.domain._common.AbstractEntity import kotlin.reflect.KClass class DomainEntityNotFoundException( val id: Any, val entityClazz: KClass<out kr.co.anna.domain._common.AbstractEntity>, msg: String, ) : RuntimeException(msg) { }
kopring_graphql_querydsl/common/domain/src/main/kotlin/kr/co/anna/domain/exception/NotAllowedException.kt
580457907
package kr.co.anna.domain.exception class NotAllowedException( msg: String, ) : RuntimeException(msg) { }
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/dto/user/SignInOut.kt
2977583046
package kr.co.anna.api.dto.user import kr.co.anna.domain._common.EnumValue import kr.co.anna.lib.security.SignInUser data class SignInOut( val userId: String, val accessToken: String, val roles: List<EnumValue>, val customInfo: CustomInfo, ) { data class CustomInfo( val userName: String?, val email: String?, val userOid: Long? ) companion object { fun from(signInUser: SignInUser, accessToken: String): SignInOut { return SignInOut( userId = signInUser.username, accessToken = accessToken, roles = signInUser.roles().map { EnumValue(it) }, customInfo = CustomInfo( userName = signInUser.name(), email = signInUser.email(), userOid = signInUser.userOid() ) ) } } }
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/dto/user/SignInIn.kt
2553840361
package kr.co.anna.api.dto.user import javax.validation.constraints.NotEmpty data class SignInIn( @field:NotEmpty val userId : String, @field:NotEmpty val password : String, )
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/dto/user/SignUpIn.kt
3234345290
package kr.co.anna.api.dto.user import kr.co.anna.domain.model.Role import kr.co.anna.domain.model.user.User import org.springframework.security.crypto.password.PasswordEncoder data class SignUpIn( val userId: String, val name: String, val email: String, val password: String, ) { fun toEntity(passwordEncoder: PasswordEncoder): User { return User( userId = userId, name = name, email = email, roles = listOf(Role.ROLE_USER), password = passwordEncoder.encode(password), ) } }
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/dto/user/UserUpdateIn.kt
2612062062
package kr.co.anna.api.dto.user data class UserUpdateIn( val name: String, val email: String )
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/dto/user/UserOut.kt
3495945110
package kr.co.anna.api.dto.user import kr.co.anna.domain.model.user.User data class UserOut( val oid: Long, val userId: String, val name: String, val email: String, ) { companion object { fun fromEntity(e: User): UserOut { return UserOut( oid = e.oid!!, userId = e.userId(), name = e.name(), email = e.email(), ) } } }
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/ApiApplication.kt
2260778417
package kr.co.anna.api import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.context.properties.ConfigurationPropertiesScan import org.springframework.boot.runApplication @SpringBootApplication class ApiApplication fun main(args: Array<String>) { runApplication<ApiApplication>(*args) }
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/config/CommonLibConfig.kt
3195739139
package kr.co.anna.api.config import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.Configuration /** * basePackages์— ์ง€์ •ํ•œ ํŒจํ‚ค์ง€ ์•ˆ์— @Component ๊ฐ€ ๋ถ™์–ด์žˆ๋Š” ํด๋ž˜์Šค๋ฅผ ์Šคํ”„๋ง ๋นˆ์œผ๋กœ ์ฝ์–ด์˜ฌ ์ˆ˜ ์žˆ๋„๋ก ์„ค์ • */ @Configuration @ComponentScan(basePackages = ["kr.co.anna.lib"]) class CommonLibConfig { }
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/config/WebMvcConfig.kt
992544908
package kr.co.anna.api.config import org.springframework.context.annotation.Configuration import org.springframework.web.servlet.config.annotation.InterceptorRegistry import org.springframework.web.servlet.config.annotation.WebMvcConfigurer /** * ์Šคํ”„๋ง MVC ์„ค์ • * * ํ˜„์žฌ๋Š” interceptor ์„ค์ •๋งŒ ์žˆ์œผ๋‚˜ ์ด ์™ธ์—๋„ ์—ฌ๋Ÿฌ๊ฐ€์ง€ ์„ค์ • ๊ฐ€๋Šฅ */ @Configuration class WebMvcConfig() : WebMvcConfigurer { override fun addInterceptors(registry: InterceptorRegistry) { } }
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/config/ApiMessageConfig.kt
901575569
package kr.co.anna.api.config import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.support.ReloadableResourceBundleMessageSource /** * api ๋‹ค๊ตญ์–ด ๋ฉ”์„ธ์ง€ ์„ค์ • */ @Configuration class ApiMessageConfig { @Autowired var messageSource: ReloadableResourceBundleMessageSource? = null @Bean fun addMessageBaseName() { messageSource!!.addBasenames("classpath:/api-messages/message") } }
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/config/OpenApiConfig.kt
1407749512
package kr.co.anna.api.config import io.swagger.v3.oas.annotations.OpenAPIDefinition import io.swagger.v3.oas.annotations.enums.SecuritySchemeType import io.swagger.v3.oas.annotations.security.SecurityRequirement import io.swagger.v3.oas.annotations.security.SecurityScheme import io.swagger.v3.oas.annotations.security.SecuritySchemes import org.springframework.context.annotation.Configuration /** * Open API (Swagger) ์„ค์ • */ @Configuration @OpenAPIDefinition( security = [ SecurityRequirement(name = "JWT"), ] ) @SecuritySchemes( SecurityScheme( type = SecuritySchemeType.HTTP, name = "JWT", description = "JWT Bearer Token ์ž…๋ ฅ", scheme = "bearer", bearerFormat = "JWT" ), ) class OpenApiConfig
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/config/SecurityConfig.kt
526675144
package kr.co.anna.api.config import kr.co.anna.domain.repository.user.UserRepository import kr.co.anna.lib.security.jwt.JwtAuthFilter import kr.co.anna.lib.security.jwt.JwtProcessor import kr.co.anna.lib.security.jwt.JwtProperties import kr.co.anna.lib.utils.MessageUtil import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.annotation.Bean import org.springframework.http.HttpMethod import org.springframework.security.access.AccessDeniedException import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.core.AuthenticationException import org.springframework.security.crypto.factory.PasswordEncoderFactories import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.security.web.AuthenticationEntryPoint import org.springframework.security.web.SecurityFilterChain import org.springframework.security.web.access.AccessDeniedHandler import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter import org.springframework.web.cors.CorsConfiguration import org.springframework.web.cors.CorsConfigurationSource import org.springframework.web.cors.CorsUtils import org.springframework.web.cors.UrlBasedCorsConfigurationSource import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse /** * ์Šคํ”„๋ง ์‹œํ๋ฆฌํ‹ฐ ์„ค์ • */ @EnableWebSecurity @EnableConfigurationProperties(JwtProperties::class) class SecurityConfig( private val jwtProcessor: JwtProcessor ) { @Bean fun filterChain(http: HttpSecurity) : SecurityFilterChain { http .cors().configurationSource(corsConfigurationSource()) .and() .csrf() .disable() .addFilterBefore(JwtAuthFilter(jwtProcessor), UsernamePasswordAuthenticationFilter::class.java) .exceptionHandling() .authenticationEntryPoint(JwtAuthenticationEntryPoint()) .accessDeniedHandler(CustomAccessDeniedHandler()) .and() .authorizeRequests() .requestMatchers(CorsUtils::isPreFlightRequest).permitAll() .antMatchers(HttpMethod.GET, "/").permitAll() .antMatchers(*swaggerAllowedList()).permitAll() .antMatchers(*actuatorAllowedList()).permitAll() .antMatchers(*devAllowedList()).permitAll() .antMatchers(HttpMethod.GET, *signAllowedList()).permitAll() .antMatchers(HttpMethod.POST, *signAllowedList()).permitAll() .antMatchers(HttpMethod.PUT, *signAllowedList()).permitAll() .antMatchers(HttpMethod.GET, *commCodeAllowedList()).permitAll() .antMatchers(*sysAdminAllowedList()).hasAnyRole("SYS_ADMIN") .anyRequest().authenticated() .and() .headers() .addHeaderWriter(XFrameOptionsHeaderWriter(XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN)) return http.build() } class JwtAuthenticationEntryPoint() : AuthenticationEntryPoint { override fun commence( request: HttpServletRequest?, response: HttpServletResponse?, authException: AuthenticationException? ) { response?.sendError(HttpServletResponse.SC_UNAUTHORIZED, MessageUtil.getMessage("UNAUTHENTICATED_USER")) } } /** * ์‹œํ๋ฆฌํ‹ฐ ์ธ๊ฐ€ */ class CustomAccessDeniedHandler() : AccessDeniedHandler { override fun handle( request: HttpServletRequest?, response: HttpServletResponse?, accessDeniedException: AccessDeniedException? ) { response?.sendError(HttpServletResponse.SC_FORBIDDEN,MessageUtil.getMessage("UNAUTHORIZED_ACCESS")) } } @Bean fun passwordEncoder(): PasswordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder() @Bean fun corsConfigurationSource(): CorsConfigurationSource? { val configuration = CorsConfiguration() configuration.addAllowedOriginPattern("http://localhost:3040") configuration.addAllowedMethod("*") configuration.addAllowedHeader("*") configuration.allowCredentials = true configuration.maxAge = 3600L configuration.exposedHeaders = listOf("Content-Disposition") val source = UrlBasedCorsConfigurationSource() source.registerCorsConfiguration("/**", configuration) return source } @Bean fun authenticationManager( authenticationConfiguration: AuthenticationConfiguration ): AuthenticationManager? { return authenticationConfiguration.authenticationManager } private fun commCodeAllowedList(): Array<String> { return arrayOf( "/api/api/common-code/**" ) } private fun signAllowedList(): Array<String> { return arrayOf( "/api/sign-up", "/api/sign-in" ) } private fun swaggerAllowedList(): Array<String> { return arrayOf( "/v3/api-docs/**", "/v3/api-docs.yaml", "/swagger-ui/**", "/swagger-ui.html" ) } private fun actuatorAllowedList(): Array<String> { return arrayOf( "/management/health", "/management/info", ) } private fun devAllowedList(): Array<String> { return arrayOf( "/h2-console/**" ) } private fun sysAdminAllowedList(): Array<String> { return arrayOf( "/api/admin/**", ) } }
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/config/CacheLogger.kt
836296400
package kr.co.anna.api.config import org.ehcache.event.CacheEvent import org.ehcache.event.CacheEventListener import org.slf4j.LoggerFactory import org.springframework.cache.annotation.EnableCaching import org.springframework.context.annotation.Configuration /** * ์บ์‹œ ์„ค์ • ํด๋ž˜์Šค * ์Šคํ”„๋ง ๋ถ€ํŠธ ๊ธฐ๋ณธ์ธ EhCache ์บ์‹œ ์„ค์ • */ @Configuration @EnableCaching class CacheLogger : CacheEventListener<Any, Any> { private val log = LoggerFactory.getLogger(javaClass) override fun onEvent(cacheEvent: CacheEvent<out Any, out Any>) { log.info("Key: [${cacheEvent.key}] | EventType: [${cacheEvent.type}] | Old value: [${cacheEvent.oldValue}] | New value: [${cacheEvent.newValue}]") } }
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/config/EnumMapperConfig.kt
883898207
package kr.co.anna.api.config import kr.co.anna.domain._common.EnumMapper import kr.co.anna.domain.model.Role import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration /** * enum ๋ชฉ๋ก ์กฐํšŒ์‹œ ์‚ฌ์šฉํ•  enum๋“ฑ๋ก */ @Configuration class EnumMapperConfig { @Bean fun enumMapper(): EnumMapper { val enumMapper = EnumMapper() enumMapper.put("ROLE", Role::class.java) return enumMapper } }
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/config/JpaConfig.kt
1290757598
package kr.co.anna.api.config import kr.co.anna.lib.security.AuthUser import org.springframework.boot.autoconfigure.domain.EntityScan import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.data.auditing.DateTimeProvider import org.springframework.data.domain.AuditorAware import org.springframework.data.jpa.repository.config.EnableJpaAuditing import org.springframework.data.jpa.repository.config.EnableJpaRepositories import org.springframework.security.core.context.SecurityContextHolder import java.time.LocalDateTime import java.util.* /** * JPA ์„ค์ • ํด๋ž˜์Šค * 2๊ฐœ์˜ ๋นˆ์€ ๋””๋น„ ํ…Œ์ด๋ธ”์— createdAt, createdBy ๋“ฑ audit ์ •๋ณด๋ฅผ ์ž๋™์œผ๋กœ ์ €์žฅํ•˜๋Š”๋ฐ ์‚ฌ์šฉ */ @Configuration @EntityScan(basePackages = ["kr.co.anna.domain"]) @EnableJpaRepositories(basePackages = ["kr.co.anna.domain"]) @EnableJpaAuditing(dateTimeProviderRef = "auditingDateTimeProvider") class JpaConfig { @Bean fun auditingDateTimeProvider() = DateTimeProvider { Optional.of(LocalDateTime.now()) } @Bean fun auditorAwareProvider() = AuditorAware { val authentication = SecurityContextHolder.getContext().authentication if (authentication == null) { Optional.empty() } else when (val principal: Any = authentication.principal) { is String -> Optional.of(principal) is AuthUser -> Optional.of(principal.userId) else -> Optional.empty() } } }
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/controller/HomeController.kt
837595826
package kr.co.anna.api.controller import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController @RestController class HomeController( ) { @GetMapping("/") fun index(): ResponseEntity<String> { return ResponseEntity.ok("Hello World!") } }
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/controller/restapi/commcode/CommCodeController.kt
3468934661
package kr.co.anna.api.controller.restapi.commcode import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.tags.Tag import kr.co.anna.domain._common.EnumMapper import kr.co.anna.domain._common.EnumValue import org.springframework.http.ResponseEntity 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.RestController @Tag(name = "commonCode-controller", description = "๊ณตํ†ต ์ฝ”๋“œ์„ฑ ์กฐํšŒ ์ปจํŠธ๋กค๋Ÿฌ ") @RequestMapping("/api/common-code") @RestController class CommCodeController( private val enumMapper: EnumMapper, ) { @Operation(summary = "enumMapper์— ๋“ฑ๋ก๋œ enum ๋ชฉ๋ก ์กฐํšŒ") @GetMapping("/enums/{names}") fun findByEnums(@PathVariable("names") names: String): ResponseEntity<Map<String, List<EnumValue>?>> { return ResponseEntity.ok(enumMapper[names]) } }
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/controller/restapi/user/SignController.kt
3899349757
package kr.co.anna.api.controller.restapi.user import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.tags.Tag import kr.co.anna.api.dto.user.* import kr.co.anna.api.service.command.user.UserCommandService import kr.co.anna.api.service.command.user.UserLoginService import kr.co.anna.domain._common.EnumMapper import kr.co.anna.domain._common.EnumValue import kr.co.anna.lib.error.InvalidException import kr.co.anna.lib.security.SecurityUtil import kr.co.anna.lib.utils.MessageUtil import org.springframework.http.ResponseEntity import org.springframework.validation.BindingResult import org.springframework.web.bind.annotation.* import javax.validation.Valid @Tag(name = "ํšŒ์› ๊ด€๋ฆฌ API") @RequestMapping("/api") @RestController class SignController( private val userCommandService: UserCommandService, private val userLoginService: UserLoginService, private val enumMapper: EnumMapper, ) { @Operation(summary = "ํšŒ์› ๊ฐ€์ž…") @PostMapping("/sign-up") fun createUser(@RequestBody signUpIn: SignUpIn): ResponseEntity<UserOut> { val userOut = userCommandService.createUser(signUpIn) return ResponseEntity.ok(userOut) } @Operation(summary = "๋กœ๊ทธ์ธ") @PostMapping("/sign-in") fun login(@Valid @RequestBody signIn: SignInIn, bindingResult: BindingResult): ResponseEntity<SignInOut> { if (bindingResult.hasErrors()) throw InvalidException(MessageUtil.getMessage("INVALID_USER_INFO"), bindingResult) return ResponseEntity.ok(userLoginService.login(signIn)) } }
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/controller/graphql/user/UserGraphController.kt
1381181072
package kr.co.anna.api.controller.graphql.user import graphql.kickstart.tools.GraphQLMutationResolver import graphql.kickstart.tools.GraphQLQueryResolver import kr.co.anna.api.dto.user.SignUpIn import kr.co.anna.api.dto.user.UserUpdateIn import kr.co.anna.domain.model.user.User import kr.co.anna.domain.repository.user.UserRepository import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.stereotype.Controller import org.springframework.transaction.annotation.Transactional import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestParam /** * Url: http://localhost:8080/graphql * Https Method: POST * Header: 'Content-Type : application/json' * **/ @Controller @Transactional class UserGraphController ( private val userRepository: UserRepository, private val passwordEncoder: PasswordEncoder ) : GraphQLQueryResolver, GraphQLMutationResolver { /** { "query": "{ findAllUsers { oid userId name email } }" } **/ fun findAllUsers(): List<User> = userRepository.findAll() /** { "query": "query ($userId: String!) { getByUserId(userId: $userId) { oid, userId, name, email } }", "variables": { "userId": "userId" } } **/ fun getByUserId( @RequestParam userId: String ) = userRepository.getByUserId(userId) /** { "query": "mutation ($signUpIn: SignUpIn!) { createUser(signUpIn: $signUpIn) { oid, userId, name, email } }", "variables": { "signUpIn": { "userId": "newUserID", "name": "New User", "email": "[email protected]", "password": "NewPassword" } } } **/ fun createUser( @RequestBody signUpIn: SignUpIn ) = userRepository.save(signUpIn.toEntity(passwordEncoder)) /** { "query": "mutation ($userOid: ID!) { deleteUserByUserOid(userOid: $userOid) }", "variables": { "userOid": "Some UserOid" } } **/ fun deleteUserByUserOid( @RequestParam userOid: Long ) = userRepository.delete(userRepository.getByOid(userOid)) /** { "query": "mutation updateUserByUserOid($userOid: ID!, $userUpdateIn: UserUpdateIn!) { updateUserByUserOid(userOid: $userOid, userUpdateIn: $userUpdateIn) { oid, userId, name, email } }", "variables": { "userOid": "1", "userUpdateIn": { "name": "NewName", "email": "[email protected]" } } } **/ fun updateUserByUserOid( @RequestParam userOid: Long, @RequestBody userUpdateIn: UserUpdateIn ) { val user = userRepository.getByOid(userOid) user.updateWith(User.NewValue( name = userUpdateIn.name, email = userUpdateIn.email )) } }
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/filter/CustomServletWrapperFilter.kt
2436623004
package kr.co.anna.api.filter import org.springframework.stereotype.Component import org.springframework.web.filter.OncePerRequestFilter import org.springframework.web.util.ContentCachingRequestWrapper import org.springframework.web.util.ContentCachingResponseWrapper import javax.servlet.FilterChain import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse /** * http req, res ๋ฅผ ์—ฌ๋Ÿฌ๋ฒˆ ์ฝ์„ ์ˆ˜ ์žˆ๋„๋ก ContentCaching Wrapper ์‚ฌ์š” * * ์ฐธ๊ณ : https://hirlawldo.tistory.com/44 */ @Component class CustomServletWrapperFilter : OncePerRequestFilter() { override fun doFilterInternal( request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain ) { val wrappingRequest = ContentCachingRequestWrapper(request) val wrappingResponse = ContentCachingResponseWrapper(response) filterChain.doFilter(wrappingRequest, wrappingResponse) wrappingResponse.copyBodyToResponse(); } }
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/service/command/user/UserCommandService.kt
3096603837
package kr.co.anna.api.service.command.user import kr.co.anna.api.dto.user.* import kr.co.anna.domain.model.user.User import kr.co.anna.domain.repository.user.UserRepository import kr.co.anna.lib.security.jwt.JwtGenerator import org.springframework.dao.DataIntegrityViolationException import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.time.LocalDateTime import java.time.format.DateTimeFormatter @Service @Transactional class UserCommandService( private val userRepository: UserRepository, private val passwordEncoder: PasswordEncoder, ) { fun createUser(signUpIn: SignUpIn): UserOut { val user: User = try { userRepository.save(signUpIn.toEntity(passwordEncoder)) } catch (e: DataIntegrityViolationException) { // index ์ด๋ฆ„ ๋ฐ DataIntegrityViolationException ๊ตฌํ˜„์— ์˜์กดํ•˜๋ฏ€๋กœ ์ข‹์€ ๋ฐฉ์‹์€ ์•„๋‹ˆ์ง€๋งŒ, // userId, email ๊ฐ๊ฐ์— ๋Œ€ํ•ด ์ฟผ๋ฆฌ๋ฅผ 2๋ฒˆ ๋‚ ๋ฆด ํ•„์š”๊ฐ€ ์—†๋Š” ์žฅ์ ์ด ์žˆ๊ณ , ํ•ต์‹ฌ ๋น„์ฆˆ ๋กœ์ง๋„ ์•„๋‹ˆ๋ฏ€๋กœ ํŽธ๋ฆฌํ•˜๊ฒŒ ์ ์šฉ val defaultMsg = "๊ณ„์ •์„ ์ƒ์„ฑํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๊ด€๋ฆฌ์ž์—๊ฒŒ ๋ฌธ์˜ํ•ด์ฃผ์„ธ์š”." val msg = e.message ?: throw RuntimeException(defaultMsg) when { msg.contains("USER_ID") -> throw IllegalArgumentException("์ด๋ฏธ ์‚ฌ์šฉ ์ค‘์ธ ์‚ฌ์šฉ์ž ์•„์ด๋”” ์ž…๋‹ˆ๋‹ค.") msg.contains("EMAIL") -> throw IllegalArgumentException("์ด๋ฏธ ์‚ฌ์šฉ ์ค‘์ธ ์ด๋ฉ”์ผ ์ž…๋‹ˆ๋‹ค.") else -> throw RuntimeException(defaultMsg) } } return UserOut.fromEntity(user) } }
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/service/command/user/UserLoginService.kt
1563520182
package kr.co.anna.api.service.command.user import kr.co.anna.api.dto.user.SignInIn import kr.co.anna.api.dto.user.SignInOut import kr.co.anna.domain.model.user.User import kr.co.anna.domain.repository.user.UserRepository import kr.co.anna.lib.error.UnauthenticatedAccessException import kr.co.anna.lib.security.SignInUser import kr.co.anna.lib.security.jwt.JwtGenerator import kr.co.anna.lib.utils.MessageUtil import org.springframework.beans.factory.annotation.Value import org.springframework.security.authentication.* import org.springframework.security.core.Authentication import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Propagation import org.springframework.transaction.annotation.Transactional @Service @Transactional class UserLoginService( private val authManager: AuthenticationManager, private val jwtGenerator: JwtGenerator ) { @Transactional(noRollbackFor = [BadCredentialsException::class]) fun login(signIn: SignInIn): SignInOut { val authenticate: Authentication = try { authManager.authenticate(UsernamePasswordAuthenticationToken(signIn.userId, signIn.password)) } catch (e: InternalAuthenticationServiceException) { // ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์‚ฌ์šฉ์ž throw InternalAuthenticationServiceException(MessageUtil.getMessage("USER_NOT_FOUND")) } catch (e: DisabledException) { // ์œ ํšจํ•œ ํšŒ์›์ด ์•„๋‹˜ throw DisabledException(MessageUtil.getMessage("LOGIN_FAIL")) } catch (e: UnauthenticatedAccessException) { throw UnauthenticatedAccessException() } val signInUser = authenticate.principal as SignInUser return SignInOut.from(signInUser, jwtGenerator.generateUserToken(signInUser)) } }
kopring_graphql_querydsl/api/src/main/kotlin/kr/co/anna/api/interceptor/PersonalInfoLoggingInterceptor.kt
2077290698
package kr.co.anna.api.interceptor import org.springframework.web.servlet.HandlerInterceptor import org.springframework.web.servlet.ModelAndView import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse /** * Spring Intercepter */ class PersonalInfoLoggingInterceptor() : HandlerInterceptor { override fun postHandle( request: HttpServletRequest, response: HttpServletResponse, handler: Any, modelAndView: ModelAndView? ) { } }
AndroidClient/app/src/androidTest/java/com/studentschedulleapp/androidclient/ExampleInstrumentedTest.kt
3609032693
package com.studentschedulleapp.androidclient 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.studentschedulleapp.androidclient", appContext.packageName) } }
AndroidClient/app/src/test/java/com/studentschedulleapp/androidclient/ExampleUnitTest.kt
835523166
package com.studentschedulleapp.androidclient 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) } }
AndroidClient/app/src/main/java/com/studentschedulleapp/androidclient/presentation/ui/theme/Color.kt
4178949136
package com.studentschedulleapp.androidclient.presentation.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
AndroidClient/app/src/main/java/com/studentschedulleapp/androidclient/presentation/ui/theme/Theme.kt
1493520199
package com.studentschedulleapp.androidclient.presentation.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Color(0xFF2980B9), secondary = Color(0xFF1ABC9C), primaryContainer = Color(0xFF376D8F), surfaceVariant = Color(0xFF15425F), surface = Color(0xFFE9E9E9), ) @Composable fun AndroidClientTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
AndroidClient/app/src/main/java/com/studentschedulleapp/androidclient/presentation/ui/theme/Type.kt
2327160446
package com.studentschedulleapp.androidclient.presentation.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
AndroidClient/app/src/main/java/com/studentschedulleapp/androidclient/presentation/MainActivity.kt
3631648561
package com.studentschedulleapp.androidclient.presentation import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.studentschedulleapp.androidclient.presentation.ui.theme.AndroidClientTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AndroidClientTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Greeting("Android") } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { AndroidClientTheme { Greeting("Android") } }
AndroidClient/data/src/androidTest/java/com/studentschedulleapp/androidclient/ExampleInstrumentedTest.kt
3924849889
package com.studentschedulleapp.androidclient 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.studentschedulleapp.androidclient.test", appContext.packageName) } }
AndroidClient/data/src/test/java/com/studentschedulleapp/androidclient/ExampleUnitTest.kt
835523166
package com.studentschedulleapp.androidclient 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) } }
AndroidClient/domain/src/androidTest/java/com/studentschedulleapp/androidclient/ExampleInstrumentedTest.kt
3924849889
package com.studentschedulleapp.androidclient 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.studentschedulleapp.androidclient.test", appContext.packageName) } }
AndroidClient/domain/src/test/java/com/studentschedulleapp/androidclient/ExampleUnitTest.kt
835523166
package com.studentschedulleapp.androidclient 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) } }
CS330-DZ06-Zadatak3-AnteaPrimorac/app/src/androidTest/java/rs/ac/metropolitan/cs330_dz06_anteaprimorac5157/ExampleInstrumentedTest.kt
2964406475
package rs.ac.metropolitan.cs330_dz06_anteaprimorac5157 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("rs.ac.metropolitan.cs330_dz06_anteaprimorac5157", appContext.packageName) } }
CS330-DZ06-Zadatak3-AnteaPrimorac/app/src/test/java/rs/ac/metropolitan/cs330_dz06_anteaprimorac5157/ExampleUnitTest.kt
73693298
package rs.ac.metropolitan.cs330_dz06_anteaprimorac5157 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) } }
CS330-DZ06-Zadatak3-AnteaPrimorac/app/src/main/java/rs/ac/metropolitan/cs330_dz06_anteaprimorac5157/MyActivity.kt
3130976229
package rs.ac.metropolitan.cs330_dz06_anteaprimorac5157 import android.app.Activity import android.content.res.Configuration import android.os.Bundle import android.util.Log import android.widget.ArrayAdapter import android.widget.ImageView import android.widget.ListView import android.widget.Toast import android.content.Intent import kotlin.random.Random class MyActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val moleImageView: ImageView = findViewById(R.id.moleImageView) val moleListView: ListView = findViewById(R.id.moleListView) // Elementi poprimaju vrijednosti iz strings.xml. val moleNames = resources.getStringArray(R.array.mole_names) // Podeลกavanje ArrayAdapter objekta za ListView val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, moleNames) moleListView.adapter = adapter moleListView.setOnItemClickListener { _, _, position, _ -> val drawableId = when (position) { 0 -> R.drawable.sprout_mole 1 -> R.drawable.box_mole 2 -> R.drawable.warden_mole else -> { Log.e("MyActivity", "No image available for this position.") 0 } } if (drawableId != 0) { moleImageView.setImageResource(drawableId) if (Random.nextInt(10) == 1) { // 10% ลกanse za trigger intenta Toast.makeText(this, getString(R.string.lucky), Toast.LENGTH_SHORT).show() val emailIntent = Intent(Intent.ACTION_SEND).apply { type = "message/rfc822" putExtra( Intent.EXTRA_SUBJECT, getString(R.string.email_subject) ) putExtra(Intent.EXTRA_TEXT, getString(R.string.email_body)) } if (emailIntent.resolveActivity(packageManager) != null) { startActivity(Intent.createChooser(emailIntent, "Send email...")) } else { Toast.makeText(this, "No email client installed.", Toast.LENGTH_SHORT) .show() } } } } } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) val message = when (newConfig.orientation) { Configuration.ORIENTATION_LANDSCAPE -> getString(R.string.landscape_toast) Configuration.ORIENTATION_PORTRAIT -> getString(R.string.portrait_toast) else -> "" } if (message.isNotEmpty()) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } } }
JetBlogCleanArchitecture/core/src/androidTest/java/com/example/core/ExampleInstrumentedTest.kt
3393852045
package com.example.core 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.core.test", appContext.packageName) } }
JetBlogCleanArchitecture/core/src/test/java/com/example/core/ExampleUnitTest.kt
2303082555
package com.example.core 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) } }
JetBlogCleanArchitecture/core/src/main/java/com/example/core/di/DataModule.kt
3042090439
package com.example.core.di import com.example.core.Utils.Constant import com.example.core.data.network.api.ApiService import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.CertificatePinner import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit @InstallIn(SingletonComponent::class) @Module object DataModule { @Provides fun provideApiService(): ApiService { val hostname = "dummyapi.io" val certificatePinner = CertificatePinner.Builder() .add(hostname, "sha256/F6jTih9VkkYZS8yuYqeU/4DUGehJ+niBGkkQ1yg8H3U=") .add(hostname, "sha256/cXjPgKdVe6iojP8s0YQJ3rtmDFHTnYZxcYvmYGFiYME=") .add(hostname, "sha256/hxqRlPTu1bMS/0DITB1SSu0vd4u/8l8TjPgfaAp63Gc=") .add(hostname, "sha256/K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q=") .build() val loggingInterceptor = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY) val client = OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .connectTimeout(120, TimeUnit.SECONDS) .readTimeout(120, TimeUnit.SECONDS) .certificatePinner(certificatePinner) .build() val retrofit = Retrofit.Builder() .baseUrl(Constant.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build() return retrofit.create(ApiService::class.java) } // @Provides // fun provideRemoteDataSource(apiService: ApiService) : RemoteDataSource = // RemoteDataSource(apiService) // // @Provides // fun provideLocalDataSource() : LocalDataSource = // LocalDataSource() // @Provides // fun provideBlogRepositoryImpl(remoteDataSource: RemoteDataSource, localDataSource: LocalDataSource, ): BlogRepository = // BlogRepositoryImpl() }
JetBlogCleanArchitecture/core/src/main/java/com/example/core/di/RepositoryModule.kt
1717490526
package com.example.core.di import com.example.core.data.source.BlogRepositoryImpl import com.example.core.domain.repository.BlogRepository import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module(includes = [DatabaseModule::class, DataModule::class]) @InstallIn(SingletonComponent::class) abstract class RepositoryModule { @Binds abstract fun provideRepository(blogRepository: BlogRepositoryImpl) : BlogRepository }
JetBlogCleanArchitecture/core/src/main/java/com/example/core/di/DatabaseModule.kt
2178037401
package com.example.core.di import android.content.Context import androidx.room.Room import com.example.core.data.local.db.BlogDao import com.example.core.data.local.db.BlogDatabase import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import net.sqlcipher.database.SupportFactory import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class DatabaseModule { @Singleton @Provides fun provideDatabase(@ApplicationContext context: Context): BlogDatabase { val passphrase: ByteArray = net.sqlcipher.database.SQLiteDatabase.getBytes("satrio".toCharArray()) val factory = SupportFactory(passphrase) return Room.databaseBuilder( context, BlogDatabase::class.java, "Blog.db" ).fallbackToDestructiveMigration() .openHelperFactory(factory) .build() } @Provides fun provideMovieDao(database: BlogDatabase): BlogDao = database.blogDao() }
JetBlogCleanArchitecture/core/src/main/java/com/example/core/Utils/Constant.kt
2211525159
package com.example.core.Utils object Constant { const val BASE_URL = "https://dummyapi.io/data/v1/" const val APP_ID = "653c562ca291fa2ca39149ce" }
JetBlogCleanArchitecture/core/src/main/java/com/example/core/Utils/DataMapper.kt
3835502321
package com.example.core.Utils import com.example.core.data.local.entity.BlogEntity import com.example.core.data.local.entity.OwnerEntity import com.example.core.data.network.model.BlogDTO import com.example.core.data.network.model.OwnerDTO import com.example.core.domain.model.Blog import com.example.core.domain.model.Owner fun List<BlogDTO>.toDomain(): List<Blog> { return map { Blog( id = it.id ?: "", image = it.image ?: "", likes = it.likes ?: 0, owner = it.owner?.toDomain() ?: Owner("", "", "", "", ""), publishDate = it.publishDate ?: "", tags = it.tags ?: emptyList(), text = it.text ?: "", isFavorite = false ) } } fun List<BlogDTO>.toEntity(): List<BlogEntity> { return map { BlogEntity( id = it.id ?: "", image = it.image ?: "", likes = it.likes ?: 0, owner = it.owner?.toEntity() ?: OwnerEntity("", "", "", "", ""), publishDate = it.publishDate ?: "", tags = it.tags ?: emptyList(), text = it.text ?: "" ) } } fun OwnerDTO.toEntity(): OwnerEntity { return OwnerEntity( firstName ?: "", id ?: "", lastName ?: "", picture ?: "", title ?: "" ) } fun OwnerEntity.toDomain(): Owner { return Owner( firstName, id, lastName, picture, title ) } fun OwnerDTO.toDomain(): Owner { return Owner( firstName ?: "", id ?: "", lastName ?: "", picture ?: "", title ?: "" ) } fun Owner.toEntity(): OwnerEntity { return OwnerEntity( firstName, id, lastName, picture, title ) } object DataMapper { fun mapResponsesToEntities(input: List<BlogDTO?>?): List<BlogEntity> { val blogList = ArrayList<BlogEntity>() input?.map { val news = BlogEntity( id = it?.id ?: "", image = it?.image ?: "", likes = it?.likes ?: 0, owner = it?.owner?.toEntity() ?: OwnerEntity("", "", "", "", ""), publishDate = it?.publishDate ?: "", tags = it?.tags ?: emptyList(), text = it?.text ?: "" ) blogList.add(news) } return blogList } fun mapEntitiesToDomain(input: List<BlogEntity>): List<Blog> = input.map { Blog( id = it.id, image = it.image, likes = it.likes, owner = it.owner.toDomain(), publishDate = it.publishDate, tags = it.tags, text = it.text, isFavorite = it.isFavorite ) } fun mapDomainToEntity(input: Blog) = BlogEntity( id = input.id, image = input.image, likes = input.likes, owner = input.owner.toEntity(), publishDate = input.publishDate, tags = input.tags, text = input.text ) }
JetBlogCleanArchitecture/core/src/main/java/com/example/core/Utils/SafeApiRequest.kt
2168293322
package com.example.core.Utils import android.util.Log import org.json.JSONException import org.json.JSONObject import retrofit2.Response import java.io.IOException abstract class SafeApiRequest { suspend fun <T : Any> safeApiRequest(call: suspend () -> Response<T>): T { val response = call.invoke() if (response.isSuccessful) { return response.body()!! } else { val responseErr = response.errorBody()?.string() val message = StringBuilder() responseErr.let { try { message.append(JSONObject(it).getString("error")) } catch (e: JSONException) { } } Log.d("TAG", "safeApiRequest: $message") throw ApiException(message.toString()) } } } class ApiException(message: String) : IOException(message) class NoInternetException(message: String) : IOException(message)
JetBlogCleanArchitecture/core/src/main/java/com/example/core/Utils/StringListConverter.kt
2642156794
package com.example.core.Utils import androidx.room.TypeConverter import com.example.core.data.local.entity.OwnerEntity import com.google.gson.Gson import com.google.gson.reflect.TypeToken class StringListConverter { @TypeConverter fun fromString(value: String): List<String> { val listType = object : TypeToken<List<String>>() {}.type return Gson().fromJson(value, listType) } @TypeConverter fun fromList(list: List<String>): String { return Gson().toJson(list) } } class OwnerEntityConverter { @TypeConverter fun fromOwnerEntity(owner: OwnerEntity): String { return Gson().toJson(owner) } @TypeConverter fun toOwnerEntity(ownerString: String): OwnerEntity { return Gson().fromJson(ownerString, OwnerEntity::class.java) } }
JetBlogCleanArchitecture/core/src/main/java/com/example/core/Utils/AppExecutors.kt
397977330
package com.example.core.Utils import android.os.Handler import android.os.Looper import androidx.annotation.VisibleForTesting import java.util.concurrent.Executor import java.util.concurrent.Executors import javax.inject.Inject class AppExecutors @VisibleForTesting constructor( private val diskIO: Executor, private val networkIO: Executor, private val mainThread: Executor ) { companion object { private const val THREAD_COUNT = 3 } @Inject constructor() : this( Executors.newSingleThreadExecutor(), Executors.newFixedThreadPool(THREAD_COUNT), MainThreadExecutor() ) fun diskIO(): Executor = diskIO fun networkIO(): Executor = networkIO fun mainThread(): Executor = mainThread private class MainThreadExecutor : Executor { private val mainThreadHandler = Handler(Looper.getMainLooper()) override fun execute(command: Runnable) { mainThreadHandler.post(command) } } }
JetBlogCleanArchitecture/core/src/main/java/com/example/core/data/source/BlogRepositoryImpl.kt
2867771651
package com.example.core.data.source import com.example.core.Utils.AppExecutors import com.example.core.Utils.DataMapper import com.example.core.data.local.LocalDataSource import com.example.core.data.network.RemoteDataSource import com.example.core.data.network.api.ApiResponse import com.example.core.data.network.model.BlogDTO import com.example.core.domain.model.Blog import com.example.core.domain.repository.BlogRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.FlowCollector import kotlinx.coroutines.flow.map import kotlinx.coroutines.withContext import javax.inject.Inject class BlogRepositoryImpl @Inject constructor( private val remoteDataSource: RemoteDataSource, private val localDataSource: LocalDataSource, private val appExcecutor: AppExecutors ) : BlogRepository { // override suspend fun getAllBlogs(): Flow<Resource<List<Blog>>> { // return flow { // emit(Resource.Loading) // try { // val response = apiService.getBlogs() // if (response.isSuccessful) { // val bloglist = response.body()?.data?.toDomain() ?: emptyList() // emit(Resource.Success(bloglist)) // } else { // emit(Resource.Error(response.message())) // } // } catch (e: Exception) { // emit(Resource.Error(e.message.toString())) // } // }.flowOn(Dispatchers.IO) // } override suspend fun getAllBlogs(): Flow<Resource<List<Blog>>> { return object : NetworkBoundResource<List<Blog>, List<BlogDTO>>(), Flow <Resource<List<Blog>>>{ override fun loadFromDB(): Flow<List<Blog>> { return localDataSource.getAllBlogs().map { DataMapper.mapEntitiesToDomain(it) } } override suspend fun createCall(): Flow<ApiResponse<List<BlogDTO?>?>> { return remoteDataSource.getAllBlogs() } override suspend fun saveCallResult(data: List<BlogDTO?>?) { withContext(Dispatchers.IO){ localDataSource.insertBlog(DataMapper.mapResponsesToEntities(data)) } } override fun shouldFetch(data: List<Blog>?): Boolean { return data.isNullOrEmpty() } override suspend fun collect(collector: FlowCollector<Resource<List<Blog>>>) { } }.asFlow() } override fun getFavorite(): Flow<List<Blog>> { return localDataSource.getFavorite().map { DataMapper.mapEntitiesToDomain(it) } } override fun setFavorite(blog: Blog, state: Boolean) { val newsEntity = DataMapper.mapDomainToEntity(blog) appExcecutor.diskIO().execute { localDataSource.setFavoriteBlogs(newsEntity,state) } } }
JetBlogCleanArchitecture/core/src/main/java/com/example/core/data/source/Resource.kt
4023715196
package com.example.core.data.source sealed class Resource<out R> private constructor() { data class Success<out T>(val data: T) : Resource<T>() data class Error(val error: String) : Resource<Nothing>() object Loading : Resource<Nothing>() }
JetBlogCleanArchitecture/core/src/main/java/com/example/core/data/source/NetworkBoundResource.kt
4016667672
package com.example.core.data.source import com.example.core.data.network.api.ApiResponse import com.example.core.data.network.model.BlogDTO import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map abstract class NetworkBoundResource<ResultType, RequestType> { private val result: Flow<Resource<ResultType>> = flow { emit(Resource.Loading) val dbSource = loadFromDB().first() if (shouldFetch(dbSource)) { emit(Resource.Loading) when (val apiResponse = createCall().first()) { is ApiResponse.Success -> { saveCallResult(apiResponse.data) emitAll(loadFromDB().map { Resource.Success(it) }) } is ApiResponse.Error -> { onFetchFailed() emit(Resource.Error(apiResponse.errorMessage)) } else -> {} } } else { emitAll(loadFromDB().map { Resource.Success(it) }) } } protected open fun onFetchFailed() {} protected abstract fun loadFromDB(): Flow<ResultType> protected abstract fun shouldFetch(data: ResultType?): Boolean protected abstract suspend fun createCall(): Flow<ApiResponse<List<BlogDTO?>?>> protected abstract suspend fun saveCallResult(data: List<BlogDTO?>?) fun asFlow(): Flow<Resource<ResultType>> = result }
JetBlogCleanArchitecture/core/src/main/java/com/example/core/data/network/RemoteDataSource.kt
4230506092
package com.example.core.data.network import android.util.Log import com.example.core.data.network.api.ApiResponse import com.example.core.data.network.api.ApiService import com.example.core.data.network.model.BlogDTO import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import javax.inject.Inject import javax.inject.Singleton @Singleton class RemoteDataSource @Inject constructor(private val apiService: ApiService) { suspend fun getAllBlogs(): Flow<ApiResponse<List<BlogDTO?>?>> { // return flow { // try { // val response = apiService.getBlogs() // val bloglist = response.data // if (bloglist?.isNotEmpty() == true) { // emit(ApiResponse.Success(response.data)) // } else { // emit(ApiResponse.Empty) // } // } catch (e: Exception) { // emit(Resource.Error(e.message.toString())) // } // }.flowOn(Dispatchers.IO) return flow { try{ val response = apiService.getBlogs() val data = response.data if (data?.isNotEmpty() == true){ emit(ApiResponse.Success(response.data)) } else { emit(ApiResponse.Empty) } } catch (e : Exception){ emit(ApiResponse.Error(e.toString())) Log.e("RemoteDataSource", e.toString()) } }.flowOn(Dispatchers.IO) } }
JetBlogCleanArchitecture/core/src/main/java/com/example/core/data/network/model/BlogDTO.kt
4135387463
package com.example.core.data.network.model import androidx.annotation.Keep @Keep data class BlogDTO( val id: String?, val image: String?, val likes: Int?, val owner: OwnerDTO?, val publishDate: String?, val tags: List<String>?, val text: String? )
JetBlogCleanArchitecture/core/src/main/java/com/example/core/data/network/model/BlogsDTO.kt
3688516073
package com.example.core.data.network.model import androidx.annotation.Keep @Keep data class BlogsDTO( val `data`: List<BlogDTO>?, val limit: Int?, val page: Int?, val total: Int? )
JetBlogCleanArchitecture/core/src/main/java/com/example/core/data/network/model/OwnerDTO.kt
2802766273
package com.example.core.data.network.model import androidx.annotation.Keep @Keep data class OwnerDTO( val firstName: String?, val id: String?, val lastName: String?, val picture: String?, val title: String? )
JetBlogCleanArchitecture/core/src/main/java/com/example/core/data/network/api/ApiService.kt
2793111830
package com.example.core.data.network.api import com.example.core.Utils.Constant import com.example.core.data.network.model.BlogsDTO import retrofit2.http.GET import retrofit2.http.Header interface ApiService { @GET("post") suspend fun getBlogs ( @Header("app-id") appId:String= Constant.APP_ID ) : BlogsDTO }
JetBlogCleanArchitecture/core/src/main/java/com/example/core/data/network/api/ApiResponse.kt
3345823014
package com.example.core.data.network.api sealed class ApiResponse<out R> { data class Success<out T>(val data: T) : ApiResponse<T>() data class Error(val errorMessage: String) : ApiResponse<Nothing>() object Empty : ApiResponse<Nothing>() }
JetBlogCleanArchitecture/core/src/main/java/com/example/core/data/local/entity/BlogEntity.kt
1644172660
package com.example.core.data.local.entity import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.TypeConverters import com.example.core.Utils.OwnerEntityConverter import com.example.core.Utils.StringListConverter @TypeConverters(StringListConverter::class, OwnerEntityConverter::class) @Entity(tableName = "blog") data class BlogEntity ( @PrimaryKey(autoGenerate = false) var id: String, val image: String, val likes: Int, val owner: OwnerEntity, val publishDate: String, val tags: List<String>, val text: String, var isFavorite: Boolean = false )
JetBlogCleanArchitecture/core/src/main/java/com/example/core/data/local/entity/OwnerEntity.kt
1121947572
package com.example.core.data.local.entity import android.os.Parcelable import kotlinx.android.parcel.Parcelize data class OwnerEntity( val firstName: String, val id: String, val lastName: String, val picture: String, val title: String )
JetBlogCleanArchitecture/core/src/main/java/com/example/core/data/local/LocalDataSource.kt
392689265
package com.example.core.data.local import com.example.core.data.local.db.BlogDao import com.example.core.data.local.entity.BlogEntity import kotlinx.coroutines.flow.Flow import javax.inject.Inject import javax.inject.Singleton @Singleton class LocalDataSource @Inject constructor(private val blogDao: BlogDao) { fun getAllBlogs(): Flow<List<BlogEntity>> = blogDao.getAllBlog() fun getFavorite(): Flow<List<BlogEntity>> = blogDao.getFavoriteBlog() fun insertBlog(blogList: List<BlogEntity>) = blogDao.insertAllBlogs(blogList) fun setFavoriteBlogs(blogs: BlogEntity, newState: Boolean) { blogs.isFavorite = newState blogDao.updateFavoriteBlogs(blogs) } }
JetBlogCleanArchitecture/core/src/main/java/com/example/core/data/local/db/BlogDao.kt
2578551915
package com.example.core.data.local.db import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Update import com.example.core.data.local.entity.BlogEntity import kotlinx.coroutines.flow.Flow @Dao interface BlogDao { @Query("SELECT * FROM blog") fun getAllBlog() : Flow<List<BlogEntity>> @Query("SELECT * FROM blog WHERE isFavorite = 1") fun getFavoriteBlog() : Flow<List<BlogEntity>> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertAllBlogs(blogs: List<BlogEntity>) @Update fun updateFavoriteBlogs(blog: BlogEntity) }
JetBlogCleanArchitecture/core/src/main/java/com/example/core/data/local/db/BlogDatabase.kt
3152622531
package com.example.core.data.local.db import androidx.room.Database import androidx.room.RoomDatabase import com.example.core.data.local.entity.BlogEntity @Database(entities = [BlogEntity::class], version = 1, exportSchema = false) abstract class BlogDatabase : RoomDatabase() { abstract fun blogDao(): BlogDao }
JetBlogCleanArchitecture/core/src/main/java/com/example/core/domain/repository/BlogRepository.kt
4100867191
package com.example.core.domain.repository import com.example.core.data.source.Resource import com.example.core.domain.model.Blog import kotlinx.coroutines.flow.Flow interface BlogRepository { suspend fun getAllBlogs() : Flow<Resource<List<Blog>>> fun getFavorite() :Flow<List<Blog>> fun setFavorite(blog: Blog, state: Boolean) }
JetBlogCleanArchitecture/core/src/main/java/com/example/core/domain/model/Blogs.kt
3203038165
package com.example.core.domain.model import androidx.annotation.Keep @Keep data class Blogs( val `data`: List<Blog>, val limit: Int, val page: Int, val total: Int )
JetBlogCleanArchitecture/core/src/main/java/com/example/core/domain/model/Blog.kt
3348109437
package com.example.core.domain.model import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class Blog( val id: String, val image: String, val likes: Int, val owner: Owner, val publishDate: String, val tags: List<String>, val text: String, val isFavorite: Boolean ) : Parcelable
JetBlogCleanArchitecture/core/src/main/java/com/example/core/domain/model/Owner.kt
798993651
package com.example.core.domain.model import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class Owner( val firstName: String, val id: String, val lastName: String, val picture: String, val title: String ) : Parcelable
JetBlogCleanArchitecture/core/src/main/java/com/example/core/domain/usecases/BlogInteractor.kt
466500262
package com.example.core.domain.usecases import com.example.core.data.source.Resource import com.example.core.domain.model.Blog import com.example.core.domain.repository.BlogRepository import kotlinx.coroutines.flow.Flow import javax.inject.Inject class BlogInteractor @Inject constructor(private val blogRepository: BlogRepository) : BlogUseCase { override suspend fun getAllBlog(): Flow<Resource<List<Blog>>> { return blogRepository.getAllBlogs() } override fun getFavorite(): Flow<List<Blog>> { return blogRepository.getFavorite() } override fun setFavorite(blog: Blog, state: Boolean) { return blogRepository.setFavorite(blog, state) } }
JetBlogCleanArchitecture/core/src/main/java/com/example/core/domain/usecases/BlogUseCase.kt
1788538149
package com.example.core.domain.usecases import com.example.core.data.source.Resource import com.example.core.domain.model.Blog import kotlinx.coroutines.flow.Flow interface BlogUseCase { suspend fun getAllBlog() : Flow<Resource<List<Blog>>> fun getFavorite(): Flow<List<Blog>> fun setFavorite(blog: Blog, state: Boolean) }