path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
spring-sandbox/src/main/kotlin/jahni/sandbox/api/configuration/LoginMember.kt
2639850181
package jahni.sandbox.api.configuration @Target(AnnotationTarget.VALUE_PARAMETER) @Retention(AnnotationRetention.RUNTIME) annotation class LoginMember
spring-sandbox/src/main/kotlin/jahni/sandbox/api/configuration/LogInterceptor.kt
3705115778
package jahni.sandbox.api.configuration import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletResponse import org.slf4j.LoggerFactory import org.springframework.web.servlet.HandlerInterceptor class LogInterceptor : HandlerInterceptor { private val logger = LoggerFactory.getLogger(this.javaClass) override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean { logger.info("Request URL: ${request.requestURI}") return true } }
spring-sandbox/src/main/kotlin/jahni/sandbox/api/configuration/ControllerAdvice.kt
3113160887
package jahni.sandbox.api.configuration import jahni.sandbox.api.util.ApiResponse import jahni.sandbox.application.exception.ErrorMessage import jahni.sandbox.application.exception.JahniCustomException import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ExceptionHandler import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestControllerAdvice @RestControllerAdvice class ControllerAdvice { @ResponseStatus(HttpStatus.OK) @ExceptionHandler(Exception::class) fun handleException(e: Exception): ApiResponse<String> { val errorMessage = ErrorMessage("Internal Server Error") // TODO: μŠ¬λž™μ— μ—λŸ¬ 둜그 전솑 return ApiResponse.fail(errorMessage) } @ResponseStatus(HttpStatus.OK) @ExceptionHandler(JahniCustomException::class) fun handleException(e: JahniCustomException): ApiResponse<String> { return ApiResponse.fail(ErrorMessage(e.message ?: "μ•Œ 수 μ—†λŠ” μ—λŸ¬μž…λ‹ˆλ‹€.")) } }
spring-sandbox/src/main/kotlin/jahni/sandbox/api/configuration/WebConfiguration.kt
4283827001
package jahni.sandbox.api.configuration import org.springframework.context.annotation.Configuration import org.springframework.web.method.support.HandlerMethodArgumentResolver import org.springframework.web.servlet.config.annotation.InterceptorRegistry import org.springframework.web.servlet.config.annotation.WebMvcConfigurer @Configuration class WebConfiguration : WebMvcConfigurer { override fun addInterceptors(registry: InterceptorRegistry) { registry.addInterceptor(LogInterceptor()) .addPathPatterns("/**") } override fun addArgumentResolvers(resolvers: MutableList<HandlerMethodArgumentResolver>) { resolvers.add(LoginMemberArgumentResolver()) } }
spring-sandbox/src/main/kotlin/jahni/sandbox/api/configuration/LoginMemberArgumentResolver.kt
1065944982
package jahni.sandbox.api.configuration import jahni.sandbox.application.domain.Member.Member import jahni.sandbox.application.exception.JahniCustomException import jakarta.servlet.http.HttpServletRequest import org.springframework.core.MethodParameter import org.springframework.web.bind.support.WebDataBinderFactory import org.springframework.web.context.request.NativeWebRequest import org.springframework.web.method.support.HandlerMethodArgumentResolver import org.springframework.web.method.support.ModelAndViewContainer class LoginMemberArgumentResolver : HandlerMethodArgumentResolver { override fun supportsParameter(parameter: MethodParameter): Boolean { val hasLoginAnnotation = parameter.hasParameterAnnotation(LoginMember::class.java) val hasMemberType = Member::class.java.isAssignableFrom(parameter.parameterType) return hasLoginAnnotation && hasMemberType } override fun resolveArgument( parameter: MethodParameter, mavContainer: ModelAndViewContainer?, webRequest: NativeWebRequest, binderFactory: WebDataBinderFactory? ): Any { val request = webRequest.nativeRequest as HttpServletRequest return request.getSession(false)?.getAttribute("LOGIN_MEMBER") ?: throw JahniCustomException("둜그인이 ν•„μš”ν•©λ‹ˆλ‹€.") } }
spring-sandbox/src/main/kotlin/jahni/sandbox/api/util/ResultType.kt
1077060496
package jahni.sandbox.api.util enum class ResultType { SUCCESS, FAIL, ERROR }
spring-sandbox/src/main/kotlin/jahni/sandbox/api/util/ApiResponse.kt
1212242927
package jahni.sandbox.api.util import jahni.sandbox.application.exception.ErrorMessage class ApiResponse<T> { val resultType: ResultType val result: T? val errorMessage: ErrorMessage? companion object { fun <T> success(result: T): ApiResponse<T> { return ApiResponse(result) } fun <T> fail(errorMessage: ErrorMessage): ApiResponse<T> { return ApiResponse(errorMessage) } } private constructor(result: T) { this.resultType = ResultType.SUCCESS this.result = result this.errorMessage = null } private constructor(errorMessage: ErrorMessage) { this.resultType = ResultType.FAIL this.result = null this.errorMessage = errorMessage } }
spring-sandbox/src/main/kotlin/jahni/sandbox/api/controller/post/response/PostDetailResponse.kt
2548590384
package jahni.sandbox.api.controller.post.response import jahni.sandbox.application.domain.Member.Member import jahni.sandbox.application.domain.comment.Comment import jahni.sandbox.application.domain.post.PostDetailOutput import java.time.LocalDateTime data class PostDetailResponse( val id: Long, val author: AuthorInfo, val title: String, val content: String, val createdAt: LocalDateTime, val updatedAt: LocalDateTime, val comments: List<CommentInfo>, ) { data class AuthorInfo( val id: Long, val loginId: String, ) { companion object { fun from(author: Member): AuthorInfo { return AuthorInfo( id = author.id, loginId = author.loginId, ) } } } data class CommentInfo( val id: Long, val author: AuthorInfo, val content: String, val createdAt: LocalDateTime, val updatedAt: LocalDateTime, ) { companion object { fun of(comment: Comment, commentAuthors: Map<Long, Member>): CommentInfo { return CommentInfo( id = comment.id, author = AuthorInfo.from(commentAuthors[comment.authorId]!!), content = comment.content, createdAt = comment.createdAt, updatedAt = comment.updatedAt, ) } } } companion object { fun from(postDetailOutput: PostDetailOutput): PostDetailResponse { return PostDetailResponse( id = postDetailOutput.post.id, author = AuthorInfo.from(postDetailOutput.postAuthor), title = postDetailOutput.post.title, content = postDetailOutput.post.content, createdAt = postDetailOutput.post.createdAt, updatedAt = postDetailOutput.post.updatedAt, comments = postDetailOutput.comments.map { CommentInfo.of(it, postDetailOutput.commentAuthors) } ) } } }
spring-sandbox/src/main/kotlin/jahni/sandbox/api/controller/post/response/PostResponse.kt
701026946
package jahni.sandbox.api.controller.post.response import jahni.sandbox.application.domain.post.Post import java.time.LocalDateTime data class PostResponse( val id: Long, val authorId: Long, // μž‘μ„±μž 정보 μΆ”κ°€ν•˜κΈ° val title: String, val content: String, val createdAt: LocalDateTime, val updatedAt: LocalDateTime, ) { companion object { fun from(post: Post): PostResponse { return PostResponse( id = post.id, authorId = post.authorId, title = post.title, content = post.content, createdAt = post.createdAt, updatedAt = post.updatedAt, ) } } }
spring-sandbox/src/main/kotlin/jahni/sandbox/api/controller/post/PostController.kt
3474666719
package jahni.sandbox.api.controller.post import jahni.sandbox.api.configuration.LoginMember import jahni.sandbox.api.controller.post.request.CreatePostRequest import jahni.sandbox.api.controller.post.request.UpdatePostRequest import jahni.sandbox.api.controller.post.response.PostDetailResponse import jahni.sandbox.api.controller.post.response.PostResponse import jahni.sandbox.api.util.ApiResponse import jahni.sandbox.application.domain.Member.Member import jahni.sandbox.application.domain.post.PostService import org.springframework.web.bind.annotation.* @RestController class PostController( private val postService: PostService ) { // κΈ€ 등둝 @PostMapping("/post") fun createPost( @LoginMember member: Member, @RequestBody request: CreatePostRequest, ) : ApiResponse<String> { postService.createPost(request.toCommand(member)) return ApiResponse.success("글이 λ“±λ‘λ˜μ—ˆμŠ΅λ‹ˆλ‹€.") } // κΈ€ 쑰회 + λŒ“κΈ€κΉŒμ§€ @GetMapping("/post/{postId}") fun getPost( @PathVariable postId: Long, ): ApiResponse<PostDetailResponse> { val postDetailOutput = postService.getPost(postId) val response = PostDetailResponse.from(postDetailOutput) return ApiResponse.success(response) } // κΈ€ μˆ˜μ • @PutMapping("/post") fun updatePost( @LoginMember member: Member, @RequestBody request: UpdatePostRequest, ): ApiResponse<String> { val command = request.toCommand(member) postService.updatePost(command) return ApiResponse.success("글이 μˆ˜μ •λ˜μ—ˆμŠ΅λ‹ˆλ‹€.") } // κΈ€ μ‚­μ œ @DeleteMapping("/post/{postId}") fun deletePost( @LoginMember member: Member, @PathVariable postId: Long, ): ApiResponse<String> { postService.deletePost(member, postId) return ApiResponse.success("글이 μ‚­μ œλ˜μ—ˆμŠ΅λ‹ˆλ‹€.") } // κΈ€ μ „λΆ€ 쑰회 + λŒ“κΈ€ μ œμ™Έ // νŽ˜μ΄μ§• 처리 @GetMapping("/posts") fun getPosts(): ApiResponse<List<PostResponse>> { val posts = postService.getAllPost() val response = posts.map { PostResponse.from(it) } return ApiResponse.success(response) } }
spring-sandbox/src/main/kotlin/jahni/sandbox/api/controller/post/request/UpdatePostRequest.kt
926282061
package jahni.sandbox.api.controller.post.request import jahni.sandbox.application.domain.Member.Member import jahni.sandbox.application.domain.post.UpdatePostCommand data class UpdatePostRequest( val postId: Long, val newTitle: String, val newContent: String, ) { fun toCommand(member: Member): UpdatePostCommand { return UpdatePostCommand( memberId = member.id, postId = postId, newTitle = newTitle, newContent = newContent, ) } }
spring-sandbox/src/main/kotlin/jahni/sandbox/api/controller/post/request/CreatePostRequest.kt
2154649200
package jahni.sandbox.api.controller.post.request import jahni.sandbox.application.domain.Member.Member import jahni.sandbox.application.domain.post.CreatePostCommand data class CreatePostRequest( val title: String, val content: String, ) { fun toCommand(member: Member): CreatePostCommand { return CreatePostCommand( authorId = member.id, title = title, content = content, ) } }
spring-sandbox/src/main/kotlin/jahni/sandbox/api/controller/comment/request/CreateCommentRequest.kt
1432864635
package jahni.sandbox.api.controller.comment.request import jahni.sandbox.application.domain.Member.Member import jahni.sandbox.application.domain.comment.CreateCommentCommand data class CreateCommentRequest( val postId: Long, val content: String, ) { fun toCommand(member: Member): CreateCommentCommand { return CreateCommentCommand( authorId = member.id, postId = postId, content = content, ) } }
spring-sandbox/src/main/kotlin/jahni/sandbox/api/controller/comment/request/UpdateCommentRequest.kt
1828739421
package jahni.sandbox.api.controller.comment.request data class UpdateCommentRequest( val content: String, )
spring-sandbox/src/main/kotlin/jahni/sandbox/api/controller/comment/CommentController.kt
562667981
package jahni.sandbox.api.controller.comment import jahni.sandbox.api.configuration.LoginMember import jahni.sandbox.api.controller.comment.request.CreateCommentRequest import jahni.sandbox.api.controller.comment.request.UpdateCommentRequest import jahni.sandbox.api.util.ApiResponse import jahni.sandbox.application.domain.Member.Member import jahni.sandbox.application.domain.comment.CommentService import jahni.sandbox.application.domain.comment.UpdateCommentCommand import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RestController @RestController class CommentController( private val commentService: CommentService, ) { // λŒ“κΈ€ 등둝 @PostMapping("/comment") fun createComment( @LoginMember member: Member, @RequestBody request: CreateCommentRequest ) : ApiResponse<String> { commentService.createComment(request.toCommand(member)) return ApiResponse.success("λŒ“κΈ€μ΄ λ“±λ‘λ˜μ—ˆμŠ΅λ‹ˆλ‹€.") } // λŒ“κΈ€ μ‚­μ œ @DeleteMapping("/comment/{commentId}") fun deleteComment( @LoginMember member: Member, @PathVariable commentId: Long ) : ApiResponse<String> { commentService.deleteComment(member.id, commentId) return ApiResponse.success("λŒ“κΈ€μ΄ μ‚­μ œλ˜μ—ˆμŠ΅λ‹ˆλ‹€.") } // λŒ“κΈ€ μˆ˜μ • @PutMapping("/comment/{commentId}") fun updateComment( @LoginMember member: Member, @PathVariable commentId: Long, @RequestBody request: UpdateCommentRequest ) : ApiResponse<String> { val command = UpdateCommentCommand(member.id, commentId, request.content) commentService.updateComment(command) return ApiResponse.success("λŒ“κΈ€μ΄ μˆ˜μ •λ˜μ—ˆμŠ΅λ‹ˆλ‹€.") } }
spring-sandbox/src/main/kotlin/jahni/sandbox/api/controller/member/LoginController.kt
1420316361
package jahni.sandbox.api.controller.member import jahni.sandbox.api.controller.member.request.LoginMemberRequest import jahni.sandbox.api.util.ApiResponse import jahni.sandbox.application.domain.Member.LoginService import jakarta.servlet.http.HttpServletRequest import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RestController @RestController class LoginController( private val loginService: LoginService, ) { @PostMapping("/login") fun login( httpRequest: HttpServletRequest, @RequestBody request: LoginMemberRequest, ): ApiResponse<String> { loginService.login(request.toCommand(httpRequest)) return ApiResponse.success("둜그인이 μ™„λ£Œλ˜μ—ˆμŠ΅λ‹ˆλ‹€.") } }
spring-sandbox/src/main/kotlin/jahni/sandbox/api/controller/member/response/MemberResponse.kt
1079954212
package jahni.sandbox.api.controller.member.response data class MemberResponse( val id: Long, val loginId: String, val password: String, )
spring-sandbox/src/main/kotlin/jahni/sandbox/api/controller/member/MemberController.kt
571457023
package jahni.sandbox.api.controller.member import jahni.sandbox.api.configuration.LoginMember import jahni.sandbox.api.controller.member.request.RegisterMemberRequest import jahni.sandbox.api.controller.member.request.UpdatePasswordRequest import jahni.sandbox.api.controller.member.response.MemberResponse import jahni.sandbox.api.util.ApiResponse import jahni.sandbox.application.domain.Member.Member import jahni.sandbox.application.domain.Member.MemberService import org.springframework.web.bind.annotation.* @RestController class MemberController( private val memberService: MemberService, ) { @PostMapping("/member") fun register(@RequestBody request: RegisterMemberRequest): ApiResponse<String> { memberService.register(request.toDomain()) return ApiResponse.success("νšŒμ›κ°€μž…μ΄ μ™„λ£Œλ˜μ—ˆμŠ΅λ‹ˆλ‹€.") } @GetMapping("/member/{id}") fun getMember( @PathVariable id: Long, @LoginMember member: Member, ): ApiResponse<MemberResponse> { val findMember = memberService.getMember(member.id, id) val response = MemberResponse( id = findMember.id, loginId = findMember.loginId, password = findMember.password, ) return ApiResponse.success(response) } @PatchMapping("/member/password") fun updatePassword( @LoginMember member: Member, @RequestBody request: UpdatePasswordRequest, ): ApiResponse<String> { memberService.update(request.toDomain(member)) return ApiResponse.success("λΉ„λ°€λ²ˆν˜Έκ°€ λ³€κ²½λ˜μ—ˆμŠ΅λ‹ˆλ‹€.") } }
spring-sandbox/src/main/kotlin/jahni/sandbox/api/controller/member/request/LoginMemberRequest.kt
3137127013
package jahni.sandbox.api.controller.member.request import jahni.sandbox.application.domain.Member.LoginCommand import jakarta.servlet.http.HttpServletRequest data class LoginMemberRequest( val loginId: String, val password: String, ) { fun toCommand(httpRequest: HttpServletRequest): LoginCommand { return LoginCommand( loginId = loginId, password = password, httpRequest = httpRequest, ) } }
spring-sandbox/src/main/kotlin/jahni/sandbox/api/controller/member/request/RegisterMemberRequest.kt
1575887513
package jahni.sandbox.api.controller.member.request import jahni.sandbox.application.domain.Member.Member data class RegisterMemberRequest( val loginId: String, val password: String, ) { fun toDomain(): Member { return Member( loginId = loginId, password = password, ) } }
spring-sandbox/src/main/kotlin/jahni/sandbox/api/controller/member/request/UpdatePasswordRequest.kt
1344498331
package jahni.sandbox.api.controller.member.request import jahni.sandbox.application.domain.Member.Member data class UpdatePasswordRequest( val newPassword: String, ) { fun toDomain(oldMember: Member): Member { return Member( id = oldMember.id, loginId = oldMember.loginId, password = newPassword, ) } }
spring-sandbox/src/main/kotlin/jahni/sandbox/application/domain/post/PostService.kt
649289328
package jahni.sandbox.application.domain.post import jahni.sandbox.application.domain.Member.Member import jahni.sandbox.application.exception.JahniCustomException import jahni.sandbox.infra.database.CommentJpaRepository import jahni.sandbox.infra.database.MemberJpaRepository import jahni.sandbox.infra.database.PostJpaRepository import org.springframework.data.repository.findByIdOrNull import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service class PostService( private val memberRepository: MemberJpaRepository, private val postRepository: PostJpaRepository, private val commentRepository: CommentJpaRepository, ) { fun createPost(command: CreatePostCommand) { postRepository.save(command.toEntity()) } @Transactional(readOnly = true) fun getPost(postId: Long): PostDetailOutput { val post = postRepository.findByIdOrNull(postId) ?: throw JahniCustomException("μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” κΈ€μž…λ‹ˆλ‹€.") val comments = commentRepository.findByPostId(post.id) val postAuthor = memberRepository.findByIdOrNull(post.authorId) ?: throw JahniCustomException("μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” μž‘μ„±μžμž…λ‹ˆλ‹€.") val commentAuthorIds = comments.map { it.authorId } val commentAuthors = memberRepository.findByIdIn(commentAuthorIds) val commentAuthorMap = commentAuthors.associateBy { it.id } return PostDetailOutput(post, postAuthor, comments, commentAuthorMap) } @Transactional fun updatePost(command: UpdatePostCommand) { val post = postRepository.findByIdOrNull(command.postId) ?: throw JahniCustomException("μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” κΈ€μž…λ‹ˆλ‹€.") if (command.memberId != post.authorId) { throw JahniCustomException("κΈ€ μž‘μ„±μžλ§Œ μˆ˜μ •ν•  수 μžˆμŠ΅λ‹ˆλ‹€.") } post.update(command.newTitle, command.newContent) } fun getAllPost(): List<Post> { return postRepository.findAll() } @Transactional fun deletePost(member: Member, postId: Long) { val post = postRepository.findByIdOrNull(postId) ?: throw JahniCustomException("μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” κΈ€μž…λ‹ˆλ‹€.") if (member.id != post.authorId) { throw JahniCustomException("κΈ€ μž‘μ„±μžλ§Œ μ‚­μ œν•  수 μžˆμŠ΅λ‹ˆλ‹€.") } postRepository.delete(post) } }
spring-sandbox/src/main/kotlin/jahni/sandbox/application/domain/post/PostDetailOutput.kt
528139049
package jahni.sandbox.application.domain.post import jahni.sandbox.application.domain.Member.Member import jahni.sandbox.application.domain.comment.Comment data class PostDetailOutput( val post: Post, val postAuthor: Member, val comments: List<Comment>, val commentAuthors: Map<Long, Member>, )
spring-sandbox/src/main/kotlin/jahni/sandbox/application/domain/post/UpdatePostCommand.kt
2424840620
package jahni.sandbox.application.domain.post data class UpdatePostCommand( val memberId: Long, val postId: Long, val newTitle: String, val newContent: String, )
spring-sandbox/src/main/kotlin/jahni/sandbox/application/domain/post/CreatePostCommand.kt
23094136
package jahni.sandbox.application.domain.post data class CreatePostCommand( private val authorId: Long, private val title: String, private val content: String, ) { fun toEntity(): Post { return Post( authorId = authorId, title = title, content = content, ) } }
spring-sandbox/src/main/kotlin/jahni/sandbox/application/domain/post/Post.kt
2296246541
package jahni.sandbox.application.domain.post import jahni.sandbox.application.domain.BaseTimeEntity import jakarta.persistence.* @Entity @Table(name = "post") class Post( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long = 0L, val authorId: Long, var title: String, var content: String, var isDeleted: Boolean = false, ) : BaseTimeEntity() { fun update(newTitle: String, newContent: String) { this.title = newTitle this.content = newContent } }
spring-sandbox/src/main/kotlin/jahni/sandbox/application/domain/BaseTimeEntity.kt
4012607513
package jahni.sandbox.application.domain import jakarta.persistence.Column import jakarta.persistence.EntityListeners import jakarta.persistence.MappedSuperclass import org.springframework.data.annotation.CreatedDate import org.springframework.data.annotation.LastModifiedDate import org.springframework.data.jpa.domain.support.AuditingEntityListener import java.time.LocalDateTime @MappedSuperclass @EntityListeners(AuditingEntityListener::class) abstract class BaseTimeEntity { @CreatedDate @Column(updatable = false) var createdAt: LocalDateTime = LocalDateTime.now() @LastModifiedDate var updatedAt: LocalDateTime = LocalDateTime.now() }
spring-sandbox/src/main/kotlin/jahni/sandbox/application/domain/comment/UpdateCommentCommand.kt
3683205300
package jahni.sandbox.application.domain.comment data class UpdateCommentCommand( val updaterId: Long, val commentId: Long, val newContent: String )
spring-sandbox/src/main/kotlin/jahni/sandbox/application/domain/comment/CreateCommentCommand.kt
1811246715
package jahni.sandbox.application.domain.comment data class CreateCommentCommand( val authorId: Long, val postId: Long, val content: String, ) { fun toEntity(): Comment { return Comment( authorId = authorId, postId = postId, content = content, ) } }
spring-sandbox/src/main/kotlin/jahni/sandbox/application/domain/comment/CommentService.kt
1704195627
package jahni.sandbox.application.domain.comment import jahni.sandbox.application.exception.JahniCustomException import jahni.sandbox.infra.database.CommentJpaRepository import org.springframework.data.repository.findByIdOrNull import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service class CommentService( private val commentRepository: CommentJpaRepository, ) { fun createComment(command: CreateCommentCommand) { val comment = command.toEntity() commentRepository.save(comment) } @Transactional fun deleteComment(memberId: Long, commentId: Long) { val comment = commentRepository.findByIdOrNull(commentId) ?: throw JahniCustomException("μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” λŒ“κΈ€μž…λ‹ˆλ‹€.") if (memberId != comment.authorId) throw JahniCustomException("λŒ“κΈ€ μž‘μ„±μžλ§Œ μ‚­μ œν•  수 μžˆμŠ΅λ‹ˆλ‹€.") commentRepository.delete(comment) } @Transactional fun updateComment(command: UpdateCommentCommand) { val (updaterId, commentId, newContent) = command val comment = commentRepository.findByIdOrNull(commentId) ?: throw JahniCustomException("μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” λŒ“κΈ€μž…λ‹ˆλ‹€.") if (updaterId != comment.authorId) throw JahniCustomException("λŒ“κΈ€ μž‘μ„±μžλ§Œ μˆ˜μ •ν•  수 μžˆμŠ΅λ‹ˆλ‹€.") comment.updateContent(newContent) } }
spring-sandbox/src/main/kotlin/jahni/sandbox/application/domain/comment/Comment.kt
2024896967
package jahni.sandbox.application.domain.comment import jahni.sandbox.application.domain.BaseTimeEntity import jakarta.persistence.* @Entity @Table(name = "comment") class Comment( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long = 0L, val authorId: Long, val postId: Long, var content: String, ) : BaseTimeEntity() { fun updateContent(newContent: String) { this.content = newContent } }
spring-sandbox/src/main/kotlin/jahni/sandbox/application/domain/Member/MemberService.kt
2732307531
package jahni.sandbox.application.domain.Member import jahni.sandbox.application.exception.JahniCustomException import jahni.sandbox.infra.database.MemberJpaRepository import org.springframework.stereotype.Service @Service class MemberService( private val memberRepository: MemberJpaRepository ) { fun register(member: Member) { memberRepository.findByLoginId(member.loginId) ?.let { throw JahniCustomException("이미 μ‘΄μž¬ν•˜λŠ” νšŒμ›μž…λ‹ˆλ‹€.") } memberRepository.save(member) } fun getMember(memberId: Long, targetMemberId: Long): Member { if (memberId != targetMemberId) throw JahniCustomException("본인만 μ‘°νšŒν•  수 μžˆμŠ΅λ‹ˆλ‹€.") return memberRepository.findById(targetMemberId).orElseThrow { JahniCustomException("μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” νšŒμ›μž…λ‹ˆλ‹€.") } } fun update(newMember: Member) { memberRepository.save(newMember) } }
spring-sandbox/src/main/kotlin/jahni/sandbox/application/domain/Member/LoginCommand.kt
1259588244
package jahni.sandbox.application.domain.Member import jakarta.servlet.http.HttpServletRequest class LoginCommand( val loginId: String, val password: String, val httpRequest: HttpServletRequest, )
spring-sandbox/src/main/kotlin/jahni/sandbox/application/domain/Member/Member.kt
1641336738
package jahni.sandbox.application.domain.Member import jahni.sandbox.application.domain.BaseTimeEntity import jakarta.persistence.* @Entity @Table(name = "member") class Member( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long = 0L, val loginId: String, var password: String, ) : BaseTimeEntity()
spring-sandbox/src/main/kotlin/jahni/sandbox/application/domain/Member/LoginService.kt
1506630707
package jahni.sandbox.application.domain.Member import jahni.sandbox.application.exception.JahniCustomException import jahni.sandbox.infra.database.MemberJpaRepository import org.springframework.stereotype.Service @Service class LoginService( private val memberJpaRepository: MemberJpaRepository, ) { /** * JSESSIONIDλ₯Ό 톡해 νšŒμ› 정보λ₯Ό κ°€μ Έμ˜€λŠ” 방식은 μ•„λž˜μ™€ 같은 ꡬ쑰둜 μ΄ν•΄ν•˜λ©΄ λœλ‹€. * getSession -> SessionStore[JSESSIONID] -> Session * Session -> Session[LOGIN_MEMBER] -> Member 정보 * */ fun login(command: LoginCommand) { val member = memberJpaRepository.findByLoginId(command.loginId) ?: throw JahniCustomException("μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” νšŒμ›μž…λ‹ˆλ‹€.") checkPassword(member, command) val session = command.httpRequest.getSession(true) // μ„Έμ…˜μ΄ μžˆλ‹€λ©΄ 기쑴것을, μ—†λ‹€λ©΄ μ‹ κ·œ 생성 session.setAttribute("LOGIN_MEMBER", member) // μ„Έμ…˜μ— 둜그인 νšŒμ› 정보 μ €μž₯ (Map ν˜•νƒœλ‘œ μ €μž₯됨) } private fun checkPassword(member: Member, command: LoginCommand) { if (member.password != command.password) throw JahniCustomException("λΉ„λ°€λ²ˆν˜Έκ°€ μΌμΉ˜ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.") } }
spring-sandbox/src/main/kotlin/jahni/sandbox/application/exception/ErrorMessage.kt
577848827
package jahni.sandbox.application.exception class ErrorMessage(val reason: String)
spring-sandbox/src/main/kotlin/jahni/sandbox/application/exception/JahniCustomException.kt
1154078215
package jahni.sandbox.application.exception class JahniCustomException(override val message: String) : RuntimeException(message)
teste-tabs/app/src/androidTest/java/com/example/teste_tabs/ExampleInstrumentedTest.kt
3125547974
package com.example.teste_tabs 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.teste_tabs", appContext.packageName) } }
teste-tabs/app/src/test/java/com/example/teste_tabs/ExampleUnitTest.kt
1762451
package com.example.teste_tabs 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) } }
teste-tabs/app/src/main/java/com/example/teste_tabs/ui/SplashFragment.kt
3905315310
package com.example.teste_tabs.ui import android.os.Bundle import android.os.Handler import android.os.Looper 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.teste_tabs.R import com.example.teste_tabs.databinding.FragmentSplashBinding class SplashFragment : Fragment() { private var _binding: FragmentSplashBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentSplashBinding.inflate(layoutInflater,container,false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) Handler(Looper.getMainLooper()).postDelayed(this::initApp,3000) } private fun initApp() { findNavController().navigate(R.id.action_splashFragment_to_mainFragment2) } override fun onDestroyView() { super.onDestroyView() _binding = null } }
teste-tabs/app/src/main/java/com/example/teste_tabs/ui/LoginFragment.kt
2881695351
package com.example.teste_tabs.ui import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.teste_tabs.R // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [LoginFragment.newInstance] factory method to * create an instance of this fragment. */ class LoginFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_login, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment LoginFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = LoginFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
teste-tabs/app/src/main/java/com/example/teste_tabs/ui/MainFragment.kt
1548082981
package com.example.teste_tabs.ui import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.teste_tabs.R import com.example.teste_tabs.adapter.ViewPagerAdapter import com.example.teste_tabs.databinding.FragmentMainBinding import com.example.teste_tabs.databinding.FragmentSplashBinding import com.google.android.material.tabs.TabLayoutMediator class MainFragment : Fragment() { private var _binding: FragmentMainBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentMainBinding.inflate(layoutInflater,container,false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initTab() } private fun initTab() { val viewpagerAdapter = ViewPagerAdapter(requireActivity()) viewpagerAdapter.addFragment(LoginFragment(),R.string.tab_login) viewpagerAdapter.addFragment(CriarContaFragment(),R.string.tab_create) with(binding.viewpager){ adapter = viewpagerAdapter offscreenPageLimit = viewpagerAdapter.itemCount } TabLayoutMediator(binding.tablayout,binding.viewpager){ tab,position -> tab.text = getText(viewpagerAdapter.getTitle(position)) }.attach() } override fun onDestroyView() { super.onDestroyView() _binding = null } }
teste-tabs/app/src/main/java/com/example/teste_tabs/ui/CriarContaFragment.kt
1943745727
package com.example.teste_tabs.ui import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.teste_tabs.R // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [CriarContaFragment.newInstance] factory method to * create an instance of this fragment. */ class CriarContaFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_criar_conta, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment CriarContaFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = CriarContaFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
teste-tabs/app/src/main/java/com/example/teste_tabs/MainActivity.kt
1646093698
package com.example.teste_tabs import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
teste-tabs/app/src/main/java/com/example/teste_tabs/adapter/ViewPagerAdapter.kt
1938819273
package com.example.teste_tabs.adapter import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.viewpager2.adapter.FragmentStateAdapter class ViewPagerAdapter( fragmentActivity: FragmentActivity ) : FragmentStateAdapter(fragmentActivity) { private val fragmentList: MutableList<Fragment> = ArrayList() private val titleList: MutableList<Int> = ArrayList() fun getTitle(pos: Int): Int = titleList[pos] fun addFragment(fragment: Fragment, title: Int) { fragmentList.add(fragment) titleList.add(title) } override fun getItemCount(): Int = fragmentList.size override fun createFragment(position: Int): Fragment = fragmentList[position] }
nelsonhongle_comp304lab3_ex2/app/src/androidTest/java/com/nelson/le/ExampleInstrumentedTest.kt
2787861334
package com.nelson.le 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.nelson.le", appContext.packageName) } }
nelsonhongle_comp304lab3_ex2/app/src/test/java/com/nelson/le/ExampleUnitTest.kt
2997373683
package com.nelson.le 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) } }
nelsonhongle_comp304lab3_ex2/app/src/main/java/com/nelson/le/ui/theme/Color.kt
3146030867
package com.nelson.le.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)
nelsonhongle_comp304lab3_ex2/app/src/main/java/com/nelson/le/ui/theme/Theme.kt
334093050
package com.nelson.le.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.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 = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun Nelsonhongle_comp304lab3_ex2Theme( 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 ) }
nelsonhongle_comp304lab3_ex2/app/src/main/java/com/nelson/le/ui/theme/Type.kt
3675965621
package com.nelson.le.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 ) */ )
nelsonhongle_comp304lab3_ex2/app/src/main/java/com/nelson/le/MainActivity.kt
175347711
package com.nelson.le import android.os.Bundle import android.view.animation.AnimationSet import android.view.animation.AnimationUtils import android.widget.ImageView import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val sunImageView: ImageView = findViewById(R.id.sunImageView) val earthImageView: ImageView = findViewById(R.id.earthImageView) val sunAnimationSet = AnimationSet(true) val sunRotateAnimation = AnimationUtils.loadAnimation(this, R.anim.rotate_animation) val sunScaleAnimation = AnimationUtils.loadAnimation(this, R.anim.scale_animation) sunAnimationSet.addAnimation(sunRotateAnimation) sunAnimationSet.addAnimation(sunScaleAnimation) sunImageView.startAnimation(sunAnimationSet) earthImageView.startAnimation(AnimationUtils.loadAnimation(this, R.anim.translate_animation)) } }
practice_musicPlayer/app/src/androidTest/java/com/example/practice_musicplayer/ExampleInstrumentedTest.kt
781696026
package com.example.practice_musicplayer 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.practice_musicplayer", appContext.packageName) } }
practice_musicPlayer/app/src/test/java/com/example/practice_musicplayer/ExampleUnitTest.kt
1314916932
package com.example.practice_musicplayer 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) } }
practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/ViewPager.kt
853696116
package com.example.practice_musicplayer import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import com.bumptech.glide.request.transition.Transition.ViewAdapter import com.example.practice_musicplayer.adapters.AdapterViewPager import com.example.practice_musicplayer.adapters.MusicAdapter import com.example.practice_musicplayer.databinding.ActivityViewPagerBinding import com.example.practice_musicplayer.utils.DpData import com.example.practice_musicplayer.utils.RetrofitService import com.example.practice_musicplayer.utils.ViewPagerExtensions.addCarouselEffect import org.json.JSONException import org.json.JSONObject import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.ArrayList class ViewPager : AppCompatActivity() { private val binding by lazy { ActivityViewPagerBinding.inflate(layoutInflater) } lateinit var viewPagerAdapter: AdapterViewPager private val apiService = RetrofitService.getInstance() private var songList: ArrayList<MusicClass>? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) getNewSongs() } private fun initViewPager() { // binding.viewPager.addCarouselEffect() // binding.viewPager.adapter = adapter // adapter.submitList(dpData.dummyData) } private fun getNewSongs() { val apiService = apiService.getNewSongs( ) apiService?.enqueue(object : Callback<String?> { override fun onResponse(call: Call<String?>, response: Response<String?>) { if (response.isSuccessful) { if (response.body() != null) { val jsonresponse: String = response.body().toString() // on below line we are initializing our adapter. Log.d("response", jsonresponse) recycleNewSongs(jsonresponse) } else { Log.i( "onEmptyResponse", "Returned empty response" ) } } } override fun onFailure(call: Call<String?>, t: Throwable) { Log.e( "ERROR", t.message.toString() ) } }) } private fun recycleNewSongs(response: String) = try { val modelRecyclerArrayList: ArrayList<MusicClass> = ArrayList() val obj = JSONObject(response) val dataArray = obj.getJSONArray("data") // Log.d("RESPONSE", dataArray.toString()) for (i in 0 until dataArray.length()) { val dataObject = dataArray.getJSONObject(i) val musicItem = MusicClass( id = dataObject.getInt("id"), date = dataObject.getString("date"), name = dataObject.getString("name"), duration = dataObject.getString("duration"), artist = dataObject.getString("artist"), coverArtUrl = dataObject.getString("cover_art_url"), url = dataObject.getString("url") ) modelRecyclerArrayList.add(musicItem) } // Log.d("RESPONSE", modelRecyclerArrayList.toString()) songList = modelRecyclerArrayList // newSongRecycleData(songList!!) } catch (e: JSONException) { e.printStackTrace() } // private fun newSongRecycleData(array: ArrayList<MusicClass>) { // // binding.viewPager.addCarouselEffect() // viewPagerAdapter = AdapterViewPager(this,binding.viewPager, array, ) // binding.viewPager.adapter = viewPagerAdapter // // } }
practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/MainActivity.kt
1139118990
package com.example.practice_musicplayer import android.annotation.SuppressLint import android.bluetooth.BluetoothAdapter import android.content.Intent import android.content.IntentFilter import android.content.pm.PackageManager import android.media.AudioManager import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.provider.MediaStore import android.util.Log import android.view.MenuItem import android.view.View import android.widget.Toast import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.widget.SearchView import androidx.core.app.ActivityCompat import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.practice_musicplayer.activities.MusicInterface import com.example.practice_musicplayer.adapters.MusicAdapter import com.example.practice_musicplayer.databinding.ActivityMainBinding import com.example.practice_musicplayer.utils.RetrofitService import com.example.practice_musicplayer.utils.WaveAnimation import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.gson.GsonBuilder import com.google.gson.reflect.TypeToken import com.simform.refresh.SSPullToRefreshLayout import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import org.json.JSONException import org.json.JSONObject import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.io.File import java.util.ArrayList import kotlin.system.exitProcess class MainActivity : AppCompatActivity() { lateinit var musicAdapter: MusicAdapter private lateinit var toggle: ActionBarDrawerToggle private val myBroadcastReceiver = MyBroadcastReceiver() private val apiService = RetrofitService.getInstance() companion object { var songList: ArrayList<MusicClass>? = null lateinit var recyclerView: RecyclerView lateinit var musicListSearch: ArrayList<MusicClass> var isSearching: Boolean = false @SuppressLint("StaticFieldLeak") lateinit var binding: ActivityMainBinding } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setTheme(R.style.Base_Theme_Practice_musicPlayer) setContentView(binding.root) setSupportActionBar(binding.toolbar) val filter = IntentFilter() filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED) filter.addAction(AudioManager.ACTION_HEADSET_PLUG) registerReceiver(myBroadcastReceiver, filter) toggle = ActionBarDrawerToggle(this, binding.root, R.string.open, R.string.close) binding.root.addDrawerListener(toggle) toggle.syncState() supportActionBar?.setDisplayHomeAsUpEnabled(true) getNewSongs() //for refreshing layout on swipe from top binding.refreshLayout.setRefreshView(WaveAnimation(this@MainActivity)) binding.refreshLayout.setOnRefreshListener(object : SSPullToRefreshLayout.OnRefreshListener { override fun onRefresh() { CoroutineScope(Dispatchers.Main).launch { delay(1000) getNewSongs() musicAdapter.updateMusicList(songList!!) Log.d("Begli" , songList.toString()) binding.refreshLayout.setRefreshing(false) // This stops refreshing } } }) binding.navView.setNavigationItemSelectedListener { when (it.itemId) { R.id.navFeedback -> { Toast.makeText(this, "Feedback", Toast.LENGTH_SHORT).show() } R.id.navAbout -> { Toast.makeText(this, "About", Toast.LENGTH_SHORT).show() } R.id.navExit -> { val builder = MaterialAlertDialogBuilder(this) builder.setTitle("Exit") .setMessage("Do you want to close app?") .setPositiveButton("Yes") { _, _ -> exitApplication() } .setNegativeButton("No") { dialog, _ -> dialog.dismiss() } val customDialog = builder.create() customDialog.show() } } true } } fun getNewSongs() { val apiService = apiService.getNewSongs( ) apiService?.enqueue(object : Callback<String?> { override fun onResponse(call: Call<String?>, response: Response<String?>) { if (response.isSuccessful) { if (response.body() != null) { val jsonresponse: String = response.body().toString() // on below line we are initializing our adapter. // Log.d("response", jsonresponse.toString()) recycleNewSongs(jsonresponse) } else { Log.i( "onEmptyResponse", "Returned empty response" ) } } } override fun onFailure(call: Call<String?>, t: Throwable) { Log.e( "ERROR", t.message.toString() ) } }) } private fun recycleNewSongs(response: String) = try { val modelRecyclerArrayList: ArrayList<MusicClass> = ArrayList() val obj = JSONObject(response) val dataArray = obj.getJSONArray("data") // Log.d("RESPONSE", dataArray.toString()) for (i in 0 until dataArray.length()) { val dataObject = dataArray.getJSONObject(i) val musicItem = MusicClass( id = dataObject.getInt("id"), date = dataObject.getString("date"), name = dataObject.getString("name"), duration = dataObject.getString("duration"), artist = dataObject.getString("artist"), coverArtUrl = dataObject.getString("cover_art_url"), url = dataObject.getString("url") ) modelRecyclerArrayList.add(musicItem) } // Log.d("RESPONSE", modelRecyclerArrayList.toString()) songList = modelRecyclerArrayList newSongRecycleData(songList!!) } catch (e: JSONException) { e.printStackTrace() } private fun newSongRecycleData(array: ArrayList<MusicClass>) { recyclerView = binding.listView musicAdapter = MusicAdapter(this, array) recyclerView.adapter = musicAdapter recyclerView.setItemViewCacheSize(50) recyclerView.hasFixedSize() recyclerView.layoutManager = LinearLayoutManager(this@MainActivity) } override fun onDestroy() { super.onDestroy() unregisterReceiver(myBroadcastReceiver) exitApplication() } override fun onResume() { super.onResume() if (MusicInterface.musicService != null) binding.nowPlaying.visibility = View.VISIBLE } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (toggle.onOptionsItemSelected(item)) return true return super.onOptionsItemSelected(item) } }
practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/MusicService.kt
4273669195
package com.example.practice_musicplayer import android.annotation.SuppressLint import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Intent import android.media.AudioAttributes import android.media.AudioManager import android.media.MediaPlayer import android.os.Binder import android.os.Build import android.os.Handler import android.os.IBinder import android.os.Looper import android.support.v4.media.MediaMetadataCompat import android.support.v4.media.session.MediaControllerCompat import android.support.v4.media.session.MediaSessionCompat import android.support.v4.media.session.PlaybackStateCompat import android.view.KeyEvent import androidx.core.app.NotificationCompat import com.example.practice_musicplayer.activities.MusicInterface import com.example.practice_musicplayer.fragments.NowPlaying import com.example.practice_musicplayer.utils.ApplicationClass import com.google.android.exoplayer2.DefaultLoadControl import com.google.android.exoplayer2.DefaultRenderersFactory import com.google.android.exoplayer2.SimpleExoPlayer import com.google.android.exoplayer2.trackselection.DefaultTrackSelector import com.google.android.exoplayer2.ui.PlayerNotificationManager import com.google.android.exoplayer2.upstream.DefaultDataSource @Suppress("DEPRECATION") class MusicService : Service(), AudioManager.OnAudioFocusChangeListener { private var myBinder = MyBinder() var mediaPlayer: MediaPlayer? = null private lateinit var mediaSession: MediaSessionCompat private lateinit var runnable: Runnable lateinit var audioManager: AudioManager val broadcastReceiver: MyBroadcastReceiver = MyBroadcastReceiver() companion object { lateinit var playPendingIntent: PendingIntent } override fun onBind(intent: Intent?): IBinder { mediaSession = MediaSessionCompat(baseContext, "Music") return myBinder } inner class MyBinder : Binder() { fun currentService(): MusicService { return this@MusicService } } @SuppressLint("UnspecifiedImmutableFlag") fun showNotification(playPauseButton: Int) { val intent = Intent(baseContext, MusicInterface::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP intent.putExtra("index", MusicInterface.songPosition) intent.putExtra("class", "Now Playing Notification") val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { PendingIntent.FLAG_IMMUTABLE } else { PendingIntent.FLAG_UPDATE_CURRENT } val contentIntent = PendingIntent.getActivity(this, 0, intent, flag) val prevIntent = Intent( baseContext, MyBroadcastReceiver::class.java ).setAction(ApplicationClass.PREVIOUS) val prevPendingIntent = PendingIntent.getBroadcast( baseContext, 3, prevIntent, flag ) val playIntent = Intent(baseContext, MyBroadcastReceiver::class.java).setAction(ApplicationClass.PLAY) playPendingIntent = PendingIntent.getBroadcast( baseContext, 3, playIntent, flag ) val nextIntent = Intent(baseContext, MyBroadcastReceiver::class.java).setAction(ApplicationClass.NEXT) val nextPendingIntent = PendingIntent.getBroadcast( baseContext, 3, nextIntent, flag ) val exitIntent = Intent(baseContext, MyBroadcastReceiver::class.java).setAction(ApplicationClass.EXIT) val exitPendingIntent = PendingIntent.getBroadcast( baseContext, 3, exitIntent, flag ) createNotificationChannel() val notificationIntent = Intent(this, MusicInterface::class.java) val pendingIntent = PendingIntent.getActivity( this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE ) val notification = NotificationCompat.Builder(this, "12") .setContentTitle(MusicInterface.musicList[MusicInterface.songPosition].name) .setContentText(MusicInterface.musicList[MusicInterface.songPosition].artist) .setSubText(MusicInterface.musicList[MusicInterface.songPosition].name) .setSmallIcon(R.drawable.music_note) .setPriority(NotificationCompat.PRIORITY_HIGH) .setContentIntent(pendingIntent) .setStyle( androidx.media.app.NotificationCompat.MediaStyle() .setMediaSession(mediaSession.sessionToken) .setShowActionsInCompactView(0, 1, 2) ) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC).setOnlyAlertOnce(true) .addAction(R.drawable.navigate_before_notification, "Previous", prevPendingIntent) .addAction(playPauseButton, "PlayPause", playPendingIntent) .addAction(R.drawable.navigate_next_notification, "Next", nextPendingIntent) .addAction(R.drawable.close_notification, "Exit", exitPendingIntent) .build() // val notification = NotificationCompat.Builder(baseContext, ApplicationClass.CHANNEL_ID) // .setContentTitle(MusicInterface.musicList[MusicInterface.songPosition].name) // .setContentText(MusicInterface.musicList[MusicInterface.songPosition].artist) // .setSubText(MusicInterface.musicList[MusicInterface.songPosition].date) // .setSmallIcon(R.drawable.music_note) // .setStyle( // androidx.media.app.NotificationCompat.MediaStyle() // .setMediaSession(mediaSession.sessionToken) // .setShowActionsInCompactView(0, 1, 2) // ).setPriority(NotificationCompat.PRIORITY_HIGH) // .setSilent(true) // .setContentIntent(contentIntent) // .setVisibility(NotificationCompat.VISIBILITY_PUBLIC).setOnlyAlertOnce(true) // .addAction(R.drawable.navigate_before_notification, "Previous", prevPendingIntent) // .addAction(playPauseButton, "PlayPause", playPendingIntent) // .build() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val playbackSpeed = if (MusicInterface.isPlaying) 1F else 0F mediaSession.setMetadata( MediaMetadataCompat.Builder() .putLong( MediaMetadataCompat.METADATA_KEY_DURATION, mediaPlayer!!.duration.toLong() ) .build() ) val playBackState = PlaybackStateCompat.Builder() .setState( PlaybackStateCompat.STATE_PLAYING, mediaPlayer!!.currentPosition.toLong(), playbackSpeed ) .setActions( PlaybackStateCompat.ACTION_SEEK_TO or PlaybackStateCompat.ACTION_SKIP_TO_NEXT or PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS or PlaybackStateCompat.ACTION_PLAY_PAUSE ) .build() mediaSession.setPlaybackState(playBackState) mediaSession.isActive = true mediaSession.setCallback(object : MediaSessionCompat.Callback() { override fun onMediaButtonEvent(mediaButtonEvent: Intent): Boolean { val event = mediaButtonEvent.getParcelableExtra<KeyEvent>(Intent.EXTRA_KEY_EVENT) if (event != null) { if (event.action == KeyEvent.ACTION_DOWN) { when (event.keyCode) { KeyEvent.KEYCODE_MEDIA_PAUSE -> { if (mediaPlayer != null) { if (MusicInterface.isPlaying) { //pause music MusicInterface.binding.interfacePlay.setImageResource(R.drawable.play) MusicInterface.isPlaying = false mediaPlayer!!.pause() showNotification(R.drawable.play_notification) NowPlaying.binding.fragmentButton.setImageResource(R.drawable.play_now) } else { //play music MusicInterface.binding.interfacePlay.setImageResource( R.drawable.pause ) MusicInterface.isPlaying = true mediaPlayer!!.start() showNotification(R.drawable.pause_notification) NowPlaying.binding.fragmentButton.setImageResource( R.drawable.pause_now ) } } } KeyEvent.KEYCODE_MEDIA_NEXT -> { broadcastReceiver.prevNextMusic(increment = true, baseContext) MusicInterface.counter-- } KeyEvent.KEYCODE_MEDIA_PREVIOUS -> { broadcastReceiver.prevNextMusic(increment = false, baseContext) } } return true } } return false } override fun onSeekTo(pos: Long) { super.onSeekTo(pos) mediaPlayer!!.seekTo(pos.toInt()) val playBackStateNew = PlaybackStateCompat.Builder() .setState( PlaybackStateCompat.STATE_PLAYING, mediaPlayer!!.currentPosition.toLong(), playbackSpeed ) .setActions(PlaybackStateCompat.ACTION_SEEK_TO) .build() mediaSession.setPlaybackState(playBackStateNew) } }) } startForeground(1, notification) } fun initSong() { try { if (mediaPlayer == null) mediaPlayer = MediaPlayer() MusicInterface.musicService!!.mediaPlayer!!.reset() MusicInterface.musicService!!.mediaPlayer!!.setDataSource(MusicInterface.musicList[MusicInterface.songPosition].coverArtUrl) MusicInterface.musicService!!.mediaPlayer!!.prepare() MusicInterface.musicService!!.showNotification(R.drawable.pause_notification) MusicInterface.binding.interfacePlay.setImageResource((R.drawable.pause)) } catch (e: Exception) { return } } fun seekBarHandler() { runnable = Runnable { MusicInterface.binding.interfaceSeekStart.text = formatDuration(mediaPlayer!!.currentPosition.toLong()) MusicInterface.binding.seekbar.progress = mediaPlayer!!.currentPosition Handler(Looper.getMainLooper()).postDelayed(runnable, 200) } Handler(Looper.getMainLooper()).postDelayed(runnable, 0) } override fun onAudioFocusChange(focusChange: Int) { if (focusChange <= 0) { //pause music MusicInterface.binding.interfacePlay.setImageResource(R.drawable.play) MusicInterface.isPlaying = false NowPlaying.binding.fragmentButton.setImageResource(R.drawable.play_now) mediaPlayer!!.pause() showNotification(R.drawable.play_notification) } else { //play music MusicInterface.binding.interfacePlay.setImageResource(R.drawable.pause) MusicInterface.isPlaying = true mediaPlayer!!.start() NowPlaying.binding.fragmentButton.setImageResource(R.drawable.pause_now) showNotification(R.drawable.pause_notification) } } private fun createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val serviceChannel = NotificationChannel("12", "Foreground Service Channel", NotificationManager.IMPORTANCE_LOW) val manager = getSystemService(NotificationManager::class.java) manager!!.createNotificationChannel(serviceChannel) } } }
practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/fragments/ExamplePlaying.kt
2718263673
package com.example.practice_musicplayer.fragments import android.annotation.SuppressLint import android.content.ContentValues import android.content.Intent import android.media.AudioManager import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.content.ContextCompat import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.example.practice_musicplayer.MusicClass import com.example.practice_musicplayer.R import com.example.practice_musicplayer.activities.MusicInterface import com.example.practice_musicplayer.adapters.AdapterViewPager import com.example.practice_musicplayer.databinding.FragmentExamplePlayingBinding import com.example.practice_musicplayer.databinding.FragmentNowPlayingBinding import com.example.practice_musicplayer.getImageArt import com.example.practice_musicplayer.setSongPosition import com.example.practice_musicplayer.utils.OnSwipeTouchListener import com.example.practice_musicplayer.utils.RetrofitService import com.example.practice_musicplayer.utils.ViewPagerExtensions.addCarouselEffect import org.json.JSONException import org.json.JSONObject import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.ArrayList @Suppress("DEPRECATION") class ExamplePlaying : Fragment() { lateinit var viewPagerAdapter: AdapterViewPager private val apiService = RetrofitService.getInstance() private var songList: ArrayList<MusicClass>? = null companion object { @SuppressLint("StaticFieldLeak") lateinit var binding: FragmentExamplePlayingBinding } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View { binding = FragmentExamplePlayingBinding.inflate(inflater, container, false) val view: View = binding.root binding.root.visibility = View.VISIBLE getNewSongs() return view } private fun getNewSongs() { val apiService = apiService.getNewSongs( ) apiService?.enqueue(object : Callback<String?> { override fun onResponse(call: Call<String?>, response: Response<String?>) { if (response.isSuccessful) { if (response.body() != null) { val jsonresponse: String = response.body().toString() // on below line we are initializing our adapter. Log.d("response", jsonresponse) recycleNewSongs(jsonresponse) } else { Log.i( "onEmptyResponse", "Returned empty response" ) } } } override fun onFailure(call: Call<String?>, t: Throwable) { Log.e( "ERROR", t.message.toString() ) } }) } private fun recycleNewSongs(response: String) = try { val modelRecyclerArrayList: ArrayList<MusicClass> = ArrayList() val obj = JSONObject(response) val dataArray = obj.getJSONArray("data") // Log.d("RESPONSE", dataArray.toString()) for (i in 0 until dataArray.length()) { val dataObject = dataArray.getJSONObject(i) val musicItem = MusicClass( id = dataObject.getInt("id"), date = dataObject.getString("date"), name = dataObject.getString("name"), duration = dataObject.getString("duration"), artist = dataObject.getString("artist"), coverArtUrl = dataObject.getString("cover_art_url"), url = dataObject.getString("url") ) modelRecyclerArrayList.add(musicItem) } // Log.d("RESPONSE", modelRecyclerArrayList.toString()) songList = modelRecyclerArrayList // newSongRecycleData(songList!!) } catch (e: JSONException) { e.printStackTrace() } // private fun newSongRecycleData(array: ArrayList<MusicClass>) { // // binding.viewPager.addCarouselEffect() // viewPagerAdapter = AdapterViewPager(requireContext(), array) // binding.viewPager.adapter = viewPagerAdapter // // } @SuppressLint("ClickableViewAccessibility") override fun onResume() { super.onResume() } }
practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/fragments/NowPlaying.kt
882773309
package com.example.practice_musicplayer.fragments import android.annotation.SuppressLint import android.content.ContentValues import android.content.Intent import android.media.AudioManager import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.example.practice_musicplayer.MainActivity import com.example.practice_musicplayer.R import com.example.practice_musicplayer.activities.MusicInterface import com.example.practice_musicplayer.databinding.FragmentNowPlayingBinding import com.example.practice_musicplayer.getImageArt import com.example.practice_musicplayer.getNewSongs import com.example.practice_musicplayer.setSongPosition import com.example.practice_musicplayer.utils.OnSwipeTouchListener @Suppress("DEPRECATION") class NowPlaying : Fragment() { companion object { @SuppressLint("StaticFieldLeak") lateinit var binding: FragmentNowPlayingBinding } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View { binding = FragmentNowPlayingBinding.inflate(inflater, container, false) val view: View = binding.root binding.root.visibility = View.GONE binding.fragmentButton.setOnClickListener { if (MusicInterface.isPlaying) pauseMusic() else playMusic() } // Inflate the layout for this fragment return view } @SuppressLint("ClickableViewAccessibility") override fun onResume() { super.onResume() if (MusicInterface.musicService != null) { binding.root.visibility = View.VISIBLE binding.fragmentTitle.isSelected = true binding.root.setOnTouchListener(object : OnSwipeTouchListener(requireContext()) { override fun onSingleClick() { openActivity() } override fun onSwipeTop() { Log.d(ContentValues.TAG, "onSwipeTop: Performed") openActivity() } override fun onSwipeLeft() { nextPrevMusic(increment = true) } override fun onSwipeRight() { nextPrevMusic(increment = false) } }) Log.e("musiclist", MusicInterface.musicList.toString()) Glide.with(this) .load(MusicInterface.musicList[MusicInterface.songPosition].coverArtUrl) .apply( RequestOptions().placeholder(R.drawable.image_as_cover).centerCrop() ).into(binding.fragmentImage) binding.fragmentTitle.text = MusicInterface.musicList[MusicInterface.songPosition].name binding.fragmentAlbumName.text = MusicInterface.musicList[MusicInterface.songPosition].artist if (MusicInterface.isPlaying) binding.fragmentButton.setImageResource(R.drawable.pause_now) else binding.fragmentButton.setImageResource(R.drawable.play_now) } } private fun playMusic() { MusicInterface.musicService!!.audioManager.requestAudioFocus( MusicInterface.musicService, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN ) MusicInterface.isPlaying = true binding.fragmentButton.setImageResource(R.drawable.pause_now) MusicInterface.musicService!!.showNotification(R.drawable.pause_notification) MusicInterface.binding.interfacePlay.setImageResource(R.drawable.pause) MusicInterface.musicService!!.mediaPlayer!!.start() } private fun pauseMusic() { MusicInterface.musicService!!.audioManager.abandonAudioFocus(MusicInterface.musicService) MusicInterface.isPlaying = false MusicInterface.musicService!!.mediaPlayer!!.pause() MusicInterface.musicService!!.showNotification(R.drawable.play_notification) MusicInterface.binding.interfacePlay.setImageResource(R.drawable.play) binding.fragmentButton.setImageResource(R.drawable.play_now) } private fun nextPrevMusic(increment: Boolean) { setSongPosition(increment = increment) MusicInterface.musicService!!.initSong() Glide.with(requireContext()) .load(getImageArt(MusicInterface.musicList[MusicInterface.songPosition].coverArtUrl)) .apply( RequestOptions().placeholder(R.drawable.image_as_cover).centerCrop() ).into(binding.fragmentImage) binding.fragmentTitle.text = MusicInterface.musicList[MusicInterface.songPosition].name binding.fragmentAlbumName.text = MusicInterface.musicList[MusicInterface.songPosition].artist playMusic() } fun openActivity() { val intent = Intent(requireContext(), MusicInterface::class.java) intent.putExtra("index", MusicInterface.songPosition) intent.putExtra("class", "Now playing") ContextCompat.startActivity(requireContext(), intent, null) } }
practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/SlidingActivity.kt
138562788
package com.example.practice_musicplayer import android.annotation.SuppressLint import android.os.Bundle import android.util.Log import android.util.TypedValue import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.viewpager2.widget.ViewPager2 import com.example.practice_musicplayer.adapters.AdapterViewPager import com.example.practice_musicplayer.adapters.MusicAdapter import com.example.practice_musicplayer.databinding.ActivitySlidingBinding import com.example.practice_musicplayer.databinding.ItemLargeCarouselBinding import com.example.practice_musicplayer.utils.RetrofitService import com.sothree.slidinguppanel.SlidingUpPanelLayout import org.json.JSONException import org.json.JSONObject import retrofit2.Call import retrofit2.Callback import retrofit2.Response open class SlidingActivity : AppCompatActivity() { private lateinit var binding: ActivitySlidingBinding lateinit var viewPagerAdapter: AdapterViewPager private val apiService = RetrofitService.getInstance() private var songList: ArrayList<MusicClass>? = null lateinit var recyclerView: RecyclerView lateinit var musicAdapter: MusicAdapter private var initialSlide = true companion object { var statePanel: Boolean = true } @SuppressLint("ClickableViewAccessibility") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySlidingBinding.inflate(layoutInflater) setContentView(binding.root) val slidingLayout: SlidingUpPanelLayout = findViewById(R.id.sliding_layout) // Initially hide the sliding panel slidingLayout.panelState = SlidingUpPanelLayout.PanelState.HIDDEN // Convert DP to pixels val pixels = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 65f, resources.displayMetrics ).toInt() binding.btnSlide.setOnClickListener { // Slide up the panel when the button is clicked // slidingLayout.panelState = SlidingUpPanelLayout.PanelState.EXPANDED if (initialSlide) { // If it's the first slide, set the panel height slidingLayout.panelState = SlidingUpPanelLayout.PanelState.EXPANDED initialSlide = false } else { // Toggle the sliding panel when the button is clicked slidingLayout.panelState = if (slidingLayout.panelState == SlidingUpPanelLayout.PanelState.COLLAPSED) SlidingUpPanelLayout.PanelState.EXPANDED else SlidingUpPanelLayout.PanelState.COLLAPSED } } // Set up the Sliding UpPanelLayout slidingLayout.addPanelSlideListener(object : SlidingUpPanelLayout.PanelSlideListener { @SuppressLint("NotifyDataSetChanged") override fun onPanelSlide(panel: View?, slideOffset: Float) { // Do something when the panel is sliding Log.e("panel", "offset $slideOffset") // Iterate through all items in the ViewPager and update the visibility of smalCard if (slideOffset <= 0.5){ statePanel = false } else { statePanel = true } viewPagerAdapter.notifyDataSetChanged() // Log.e("state", statePanel.toString()) } @SuppressLint("NotifyDataSetChanged") override fun onPanelStateChanged( panel: View?, previousState: SlidingUpPanelLayout.PanelState?, newState: SlidingUpPanelLayout.PanelState?, ) { // Do something when the panel state changes Log.e("panel", "Hide") if (newState == SlidingUpPanelLayout.PanelState.COLLAPSED) { // If the panel is collapsed, set it to expanded with the desired height slidingLayout.panelHeight = pixels } } }) getNewSongs() } private fun getNewSongs() { val apiService = apiService.getNewSongs( ) apiService?.enqueue(object : Callback<String?> { override fun onResponse(call: Call<String?>, response: Response<String?>) { if (response.isSuccessful) { if (response.body() != null) { val jsonresponse: String = response.body().toString() // on below line we are initializing our adapter. Log.d("response", jsonresponse) recycleNewSongs(jsonresponse) } else { Log.i( "onEmptyResponse", "Returned empty response" ) } } } override fun onFailure(call: Call<String?>, t: Throwable) { Log.e( "ERROR", t.message.toString() ) } }) } private fun recycleNewSongs(response: String) = try { val modelRecyclerArrayList: ArrayList<MusicClass> = ArrayList() val obj = JSONObject(response) val dataArray = obj.getJSONArray("data") // Log.d("RESPONSE", dataArray.toString()) for (i in 0 until dataArray.length()) { val dataObject = dataArray.getJSONObject(i) val musicItem = MusicClass( id = dataObject.getInt("id"), date = dataObject.getString("date"), name = dataObject.getString("name"), duration = dataObject.getString("duration"), artist = dataObject.getString("artist"), coverArtUrl = dataObject.getString("cover_art_url"), url = dataObject.getString("url") ) modelRecyclerArrayList.add(musicItem) } // Log.d("RESPONSE", modelRecyclerArrayList.toString()) songList = modelRecyclerArrayList newSongViewPagerData(songList!!) newSongRecycleData(songList!!) } catch (e: JSONException) { e.printStackTrace() } private fun newSongViewPagerData(array: ArrayList<MusicClass>) { viewPagerAdapter = AdapterViewPager(this, array) binding.viewPager.adapter = viewPagerAdapter } private fun newSongRecycleData(array: ArrayList<MusicClass>) { recyclerView = binding.recycleSliding musicAdapter = MusicAdapter(this, array) recyclerView.adapter = musicAdapter recyclerView.setItemViewCacheSize(50) recyclerView.hasFixedSize() recyclerView.layoutManager = LinearLayoutManager(this@SlidingActivity) } }
practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/MyBroadcastReceiver.kt
126275512
package com.example.practice_musicplayer import android.bluetooth.BluetoothAdapter import android.content.BroadcastReceiver import android.content.ContentValues import android.content.Context import android.content.Intent import android.media.AudioManager import android.util.Log import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.example.practice_musicplayer.activities.MusicInterface import com.example.practice_musicplayer.fragments.NowPlaying import com.example.practice_musicplayer.utils.ApplicationClass @Suppress("DEPRECATION") class MyBroadcastReceiver : BroadcastReceiver(){ override fun onReceive(context: Context?, intent: Intent?) { when (intent?.action) { ApplicationClass.PREVIOUS -> { prevNextMusic(increment = false, context = context!!) } ApplicationClass.PLAY -> { if (MusicInterface.isPlaying) pauseMusic() else playMusic() } ApplicationClass.NEXT -> { prevNextMusic(increment = true, context = context!!) MusicInterface.counter-- } ApplicationClass.EXIT -> { exitApplicationNotification() } /* AudioManager.ACTION_HEADSET_PLUG -> { val state = intent.getIntExtra("state", -1) if (state == 0) { pauseMusic() } else{ Log.d(TAG, "onReceive: HeadSet Plugged") } } */ BluetoothAdapter.ACTION_STATE_CHANGED -> { val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); Log.d(ContentValues.TAG, "onReceive: ${state.toString()}") when (state) { BluetoothAdapter.STATE_OFF -> { pauseMusic() } BluetoothAdapter.STATE_TURNING_OFF -> { pauseMusic() } } } } } private fun playMusic() { MusicInterface.musicService!!.audioManager.requestAudioFocus( MusicInterface.musicService, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN ) MusicInterface.isPlaying = true MusicInterface.binding.interfacePlay.setImageResource(R.drawable.pause) MusicInterface.musicService!!.mediaPlayer!!.start() MusicInterface.musicService!!.showNotification(R.drawable.pause_notification) NowPlaying.binding.fragmentButton.setImageResource(R.drawable.pause_now) } fun prevNextMusic(increment: Boolean, context: Context) { try { setSongPosition(increment = increment) MusicInterface.musicService!!.initSong() Glide.with(context) .load(MusicInterface.musicList[MusicInterface.songPosition].coverArtUrl) .apply( RequestOptions().placeholder(R.drawable.image_as_cover).centerCrop() ).into(MusicInterface.binding.interfaceCover) MusicInterface.binding.interfaceSongName.text = MusicInterface.musicList[MusicInterface.songPosition].name MusicInterface.binding.interfaceArtistName.text = MusicInterface.musicList[MusicInterface.songPosition].artist Glide.with(context) .load(MusicInterface.musicList[MusicInterface.songPosition].coverArtUrl) .apply( RequestOptions().placeholder(R.drawable.image_as_cover).centerCrop() ).into(NowPlaying.binding.fragmentImage) NowPlaying.binding.fragmentTitle.text = MusicInterface.musicList[MusicInterface.songPosition].name NowPlaying.binding.fragmentAlbumName.text = MusicInterface.musicList[MusicInterface.songPosition].artist playMusic() } catch (e: Exception) { Log.e("AdapterView", e.toString()) } } private fun pauseMusic() { MusicInterface.musicService!!.audioManager.abandonAudioFocus(MusicInterface.musicService) MusicInterface.isPlaying = false MusicInterface.binding.interfacePlay.setImageResource(R.drawable.play) MusicInterface.musicService!!.mediaPlayer!!.pause() MusicInterface.musicService!!.showNotification(R.drawable.play_notification) NowPlaying.binding.fragmentButton.setImageResource(R.drawable.play_now) } }
practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/MusicClass.kt
3430967671
@file:Suppress("DEPRECATION") package com.example.practice_musicplayer import android.content.ContentValues import android.content.Intent import android.content.pm.ServiceInfo import android.graphics.Bitmap import android.graphics.Color import android.media.MediaMetadataRetriever import android.util.Log import androidx.core.app.ServiceCompat import com.example.practice_musicplayer.activities.MusicInterface import com.example.practice_musicplayer.utils.RetrofitService import org.json.JSONException import org.json.JSONObject import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.io.File import java.util.concurrent.TimeUnit import kotlin.math.roundToInt import kotlin.random.Random import kotlin.system.exitProcess data class MusicClass( val id: Int, val date: String, var name: String, val duration: String, var artist: String, var coverArtUrl: String, var url: String ) val usedNumber = mutableSetOf<Int>() class Playlist { lateinit var name: String lateinit var playlist: ArrayList<MusicClass> lateinit var createdBy: String lateinit var createdOn: String } class MusicPlaylist { var ref: ArrayList<Playlist> = ArrayList() } fun exitApplication() { exitProcess(1) } fun getImageArt(path: String): ByteArray? { val retriever = MediaMetadataRetriever() retriever.setDataSource(path) return retriever.embeddedPicture } fun getMainColor(img: Bitmap): Int { val newImg = Bitmap.createScaledBitmap(img, 1, 1, true) val color = newImg.getPixel(0, 0) newImg.recycle() return manipulateColor(color, 0.4.toFloat()) } fun manipulateColor(color: Int, factor: Float): Int { val a: Int = Color.alpha(color) val r = (Color.red(color) * factor).roundToInt() val g = (Color.green(color) * factor).roundToInt() val b = (Color.blue(color) * factor).roundToInt() return Color.argb( a, r.coerceAtMost(255), g.coerceAtMost(255), b.coerceAtMost(255) ) } fun exitApplicationNotification() { // if (MusicInterface.isPlaying) { // val musicInterface = MusicInterface() // musicInterface.pauseMusic() // } Log.e("serStop", MusicInterface.musicService.toString()) MusicInterface.musicService!!.stopForeground(true) // MusicInterface.myService!!.stopForeground(true) } fun formatDuration(duration: Long): String { val minutes = TimeUnit.MINUTES.convert(duration, TimeUnit.MILLISECONDS) val seconds = (TimeUnit.SECONDS.convert( duration, TimeUnit.MILLISECONDS ) - minutes * TimeUnit.SECONDS.convert(1, TimeUnit.MINUTES)) return String.format("%02d:%02d", minutes, seconds) } fun shuffleSongs() { var newSong: Int = MusicInterface.songPosition checkIfListIsFull(usedNumber) Log.d(ContentValues.TAG, "shuffleSongs: " + usedNumber.size) while (newSong == MusicInterface.songPosition) { newSong = getRandomNumber(MusicInterface.musicList.size) } MusicInterface.songPosition = newSong } fun getRandomNumber(max: Int): Int { val random = Random var number = random.nextInt(max + 1) while (usedNumber.contains(number)) { number = random.nextInt(max + 1) } usedNumber.add(number) return number } fun checkIfListIsFull(list: MutableSet<Int>) { if (list.size.toInt() == MusicInterface.musicList.size) { list.clear() } } fun setSongPosition(increment: Boolean) { if (!MusicInterface.isRepeating) { if (increment) { if (MusicInterface.isShuffling && MusicInterface.counter == 0) { shuffleSongs() } else { if (MusicInterface.musicList.size - 1 == MusicInterface.songPosition) { MusicInterface.songPosition = 0 } else ++MusicInterface.songPosition } } else { if (0 == MusicInterface.songPosition) MusicInterface.songPosition = MusicInterface.musicList.size - 1 else --MusicInterface.songPosition } } } fun getNewSongs() { val api_Service = RetrofitService.getInstance() val apiService = api_Service.getNewSongs( ) apiService?.enqueue(object : Callback<String?> { override fun onResponse(call: Call<String?>, response: Response<String?>) { if (response.isSuccessful) { if (response.body() != null) { val jsonresponse: String = response.body().toString() // on below line we are initializing our adapter. // Log.d("response", jsonresponse.toString()) recycleNewSongs(jsonresponse) } else { Log.i( "onEmptyResponse", "Returned empty response" ) } } } override fun onFailure(call: Call<String?>, t: Throwable) { Log.e( "ERROR", t.message.toString() ) } }) } fun recycleNewSongs(response: String) = try { val modelRecyclerArrayList: java.util.ArrayList<MusicClass> = java.util.ArrayList() val obj = JSONObject(response) val dataArray = obj.getJSONArray("data") // Log.d("RESPONSE", dataArray.toString()) for (i in 0 until dataArray.length()) { val dataObject = dataArray.getJSONObject(i) val musicItem = MusicClass( id = dataObject.getInt("id"), date = dataObject.getString("date"), name = dataObject.getString("name"), duration = dataObject.getString("duration"), artist = dataObject.getString("artist"), coverArtUrl = dataObject.getString("cover_art_url"), url = dataObject.getString("url") ) modelRecyclerArrayList.add(musicItem) } // Log.d("RESPONSE", modelRecyclerArrayList.toString()) MainActivity.songList = modelRecyclerArrayList } catch (e: JSONException) { e.printStackTrace() }
practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/utils/WaveAnimation.kt
149983999
package com.example.practice_musicplayer.utils import android.animation.ValueAnimator import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Path import com.simform.refresh.SSAnimationView import kotlin.math.sin // This is a demo view in which user can set any animation or // just make it blank and set Gif animation using setGifAnimation() method on SSPullToRefreshLayout class WaveAnimation(context: Context): SSAnimationView(context) { private var amplitude = 22f.toDp() // scale private var speed = 0f private val path = Path() private var paint = Paint(Paint.ANTI_ALIAS_FLAG) private var animator: ValueAnimator? = null override fun onDraw(c: Canvas) = c.drawPath(path, paint) private fun createAnimator(): ValueAnimator { return ValueAnimator.ofFloat(0f, Float.MAX_VALUE).apply { repeatCount = ValueAnimator.INFINITE addUpdateListener { speed -= WAVE_SPEED createPath() invalidate() } } } private fun createPath() { path.reset() paint.color = Color.parseColor("#00F15E") path.moveTo(0f, height.toFloat()) path.lineTo(0f, amplitude) path.lineTo(0f, amplitude - 10) var i = 0 while (i < width + 10) { val wx = i.toFloat() val sinComponent = sin((i + 10) * Math.PI / WAVE_AMOUNT_ON_SCREEN + speed).toFloat() val wy = amplitude * (2 + sinComponent) path.lineTo(wx, wy) i += 10 } path.lineTo(width.toFloat(), height.toFloat()) path.close() } override fun onDetachedFromWindow() { animator?.cancel() super.onDetachedFromWindow() } companion object { const val WAVE_SPEED = 0.25f const val WAVE_AMOUNT_ON_SCREEN = 350 } private fun Float.toDp() = this * context.resources.displayMetrics.density override fun reset() { } override fun refreshing() { } override fun refreshComplete() { animator?.cancel() } override fun pullToRefresh() { animator = createAnimator().apply { start() } } override fun releaseToRefresh() { } override fun pullProgress(pullDistance: Float, pullProgress: Float) { } }
practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/utils/RetrofitService.kt
4159014262
package com.example.practice_musicplayer.utils import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.scalars.ScalarsConverterFactory import retrofit2.http.GET interface RetrofitService { // @GET("api/v1/song?sort=date&order=desc&max=10") // fun getMainPage(): Call<SongResponse?>? @GET("api/v1/song?sort=date&order=desc&max=10") fun getNewSongs(): Call<String?>? @GET("api/v1/song?sort=date&order=desc&max=10&artistId=47%2C48%2C106%2C102%2C17%2C44%2C37%2C70%2C8%2C49%2C57%2C4%2C35%2C38%2C46%2C53%2C16%2C51%2C55%2C52%2C61%2C24%2C15%2C127%2C460%2C790%2C104") fun getTrendSongs(): Call<String?>? @GET("api/v1/video?sort=date&order=desc&videoTypeId=1") fun getClips(): Call<String?>? companion object { var retrofitService: RetrofitService? = null fun getInstance(): RetrofitService { if (retrofitService == null) { val retrofit = Retrofit.Builder() .baseUrl("https://aydym.com/") .addConverterFactory(ScalarsConverterFactory.create()) // .addConverterFactory(GsonConverterFactory.create()) .build() retrofitService = retrofit.create(RetrofitService::class.java) } return retrofitService!! } } }
practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/utils/DpData.kt
2629802236
package com.example.practice_musicplayer.utils class DpData { val dummyData = listOf( "Hello Developers", "Hope, you are all fine!", "Sohaib here!", "Enjoy this new feature.", "I made it pretty easier for you by adding an extension function." ) }
practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/utils/ApplicationClass.kt
380289635
package com.example.practice_musicplayer.utils import android.annotation.SuppressLint import android.app.Application import android.app.NotificationChannel import android.app.NotificationManager import android.os.Build class ApplicationClass : Application() { companion object { const val CHANNEL_ID = "12" const val NEXT = "next" const val PREVIOUS = "previous" const val PLAY = "play" const val EXIT = "exit" } @SuppressLint("ObsoleteSdkInt") override fun onCreate() { super.onCreate() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val notificationChannel = NotificationChannel(CHANNEL_ID, "Now playing", NotificationManager.IMPORTANCE_HIGH) notificationChannel.description = "Channel for showing playing song" val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(notificationChannel) } } }
practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/utils/OnSwipeTouchListener.kt
2997182530
package com.example.practice_musicplayer.utils import android.annotation.SuppressLint import android.content.Context import android.view.GestureDetector import android.view.MotionEvent import android.view.View import kotlin.math.abs open class OnSwipeTouchListener(ctx: Context) : View.OnTouchListener { private val gestureDetector: GestureDetector companion object { private const val SWIPE_THRESHOLD = 300 private const val SWIPE_VELOCITY_THRESHOLD = 300 } init { gestureDetector = GestureDetector(ctx, GestureListener()) } @SuppressLint("ClickableViewAccessibility") override fun onTouch(v: View, event: MotionEvent): Boolean { return gestureDetector.onTouchEvent(event) } private inner class GestureListener : GestureDetector.SimpleOnGestureListener() { override fun onDown(e: MotionEvent): Boolean { return true } override fun onSingleTapConfirmed(e: MotionEvent): Boolean { onSingleClick() return super.onSingleTapConfirmed(e) } override fun onFling( e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float ): Boolean { var result = false try { val diffY = e2.y - e1.y val diffX = e2.x - e1.x if (abs(diffX) > abs(diffY)) { if (abs(diffX) > SWIPE_THRESHOLD && abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) { if (diffX > 0) { onSwipeRight() } else { onSwipeLeft() } result = true } } else if (abs(diffY) > abs(diffX)) { if (abs(diffY) > SWIPE_THRESHOLD && abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) { if (diffY < 0) { onSwipeTop() } else if (diffY > 0) { onSwipeDown() } result = true } } } catch (exception: Exception) { exception.printStackTrace() } return result } } open fun onSwipeRight() {} open fun onSingleClick() {} open fun onSwipeLeft() {} open fun onSwipeTop() {} open fun onSwipeDown() {} }
practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/utils/ViewPagerExtensions.kt
2890470067
package com.example.practice_musicplayer.utils import android.content.res.Resources import androidx.recyclerview.widget.RecyclerView import androidx.viewpager2.widget.CompositePageTransformer import androidx.viewpager2.widget.MarginPageTransformer import androidx.viewpager2.widget.ViewPager2 import kotlin.math.abs object ViewPagerExtensions { fun ViewPager2.addCarouselEffect(enableZoom: Boolean = true) { clipChildren = false // No clipping the left and right items clipToPadding = false // Show the viewpager in full width without clipping the padding offscreenPageLimit = 3 // Render the left and right items (getChildAt(0) as RecyclerView).overScrollMode = RecyclerView.OVER_SCROLL_NEVER // Remove the scroll effect val compositePageTransformer = CompositePageTransformer() compositePageTransformer.addTransformer(MarginPageTransformer((20 * Resources.getSystem().displayMetrics.density).toInt())) if (enableZoom) { compositePageTransformer.addTransformer { page, position -> val r = 1 - abs(position) page.scaleY = (0.80f + r * 0.20f) } } setPageTransformer(compositePageTransformer) } }
practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/MyService.kt
1665712383
package com.example.practice_musicplayer import android.annotation.SuppressLint import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Intent import android.content.pm.ServiceInfo import android.media.AudioManager import android.media.MediaPlayer import android.os.Binder import android.os.Build import android.os.IBinder import android.provider.Settings import android.support.v4.media.session.MediaSessionCompat import androidx.annotation.RequiresApi import androidx.core.app.ServiceCompat import com.example.practice_musicplayer.activities.MusicInterface import com.example.practice_musicplayer.fragments.NowPlaying import com.example.practice_musicplayer.utils.ApplicationClass @Suppress("DEPRECATION") class MyService : Service(), AudioManager.OnAudioFocusChangeListener { var mediaPlayer: MediaPlayer? = null private var audioUrl: String? = null private var myBinder = MyBinder() private val channelid = "3" lateinit var audioManager: AudioManager private lateinit var mediaSession: MediaSessionCompat @RequiresApi(Build.VERSION_CODES.O) override fun onCreate() { super.onCreate() mediaPlayer = MediaPlayer() createNotificationChanel() } override fun onBind(intent: Intent?): IBinder { mediaSession = MediaSessionCompat(baseContext, "Music") return myBinder } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { playAudio() showNotification() return START_STICKY } private fun playAudio() { mediaPlayer?.apply { reset() setDataSource(MusicInterface.musicUrl) prepareAsync() setOnPreparedListener { start() } } initSong() } @RequiresApi(Build.VERSION_CODES.O) @SuppressLint("UnspecifiedImmutableFlag", "InlinedApi") fun showNotification() { val notificationIntent = Intent(this, MainActivity::class.java) val pendingIntent = PendingIntent.getActivity(this, 3, notificationIntent, PendingIntent.FLAG_IMMUTABLE) val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { PendingIntent.FLAG_IMMUTABLE } else { PendingIntent.FLAG_UPDATE_CURRENT } val exitIntent = Intent(baseContext, MyBroadcastReceiver::class.java).setAction(ApplicationClass.EXIT) val exitPendingIntent = PendingIntent.getBroadcast( baseContext, 3, exitIntent, flag ) val notification = Notification .Builder(this, channelid) .setContentText("Music Player") .setSmallIcon(R.drawable.play) .setContentIntent(pendingIntent) .build() startForeground( 3, notification, ) } inner class MyBinder : Binder() { fun currentService(): MyService { return this@MyService } } private fun createNotificationChanel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val serviceChannel = NotificationChannel( channelid, "Foreground Service Channel", NotificationManager.IMPORTANCE_DEFAULT ) val manager = getSystemService(NotificationManager::class.java) manager!!.createNotificationChannel(serviceChannel) } } fun initSong() { try { if (mediaPlayer == null) mediaPlayer = MediaPlayer() MusicInterface.myService?.let { it.mediaPlayer!!.reset() it.mediaPlayer!!.setDataSource(MusicInterface.musicList[MusicInterface.songPosition].url) it.mediaPlayer!!.prepare() it.showNotification() MusicInterface.binding.interfacePlay.setImageResource((R.drawable.pause)) } } catch (e: Exception) { e.printStackTrace() // Log the exception for debugging } } override fun onDestroy() { super.onDestroy() mediaPlayer!!.stop() } override fun onAudioFocusChange(focusChange: Int) { if (focusChange <= 0) { //pause music MusicInterface.binding.interfacePlay.setImageResource(R.drawable.play) MusicInterface.isPlaying = false NowPlaying.binding.fragmentButton.setImageResource(R.drawable.play_now) mediaPlayer!!.pause() showNotification() } else { //play music MusicInterface.binding.interfacePlay.setImageResource(R.drawable.pause) MusicInterface.isPlaying = true mediaPlayer!!.start() NowPlaying.binding.fragmentButton.setImageResource(R.drawable.pause_now) showNotification() } } }
practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/adapters/MusicAdapter.kt
2542009630
package com.example.practice_musicplayer.adapters import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.view.LayoutInflater import android.view.ViewGroup import android.widget.Toast import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.request.RequestOptions import com.example.practice_musicplayer.MainActivity import com.example.practice_musicplayer.MusicClass import com.example.practice_musicplayer.R import com.example.practice_musicplayer.activities.MusicInterface import com.example.practice_musicplayer.databinding.SingleLayoutBinding import com.example.practice_musicplayer.formatDuration import com.google.android.material.snackbar.Snackbar class MusicAdapter( private val context: Context, private var musicList: ArrayList<MusicClass>, private val playlistDetails: Boolean = false, private val selectionActivity: Boolean = false, ) : RecyclerView.Adapter<MusicAdapter.MyHolder>() { class MyHolder(binding: SingleLayoutBinding) : RecyclerView.ViewHolder(binding.root) { val titleView = binding.titleView val albumName = binding.albumName val imageView = binding.imageView val duration = binding.duration val root = binding.root } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder { return MyHolder( SingleLayoutBinding.inflate( LayoutInflater.from( context ), parent, false ) ) } override fun onBindViewHolder(holder: MyHolder, position: Int) { holder.titleView.text = musicList[position].name holder.albumName.text = musicList[position].artist holder.duration.text = musicList[position].duration val myOptions = RequestOptions() .centerCrop() .override(100, 100) Glide .with(context) .applyDefaultRequestOptions(myOptions) .load(musicList[position].coverArtUrl) .diskCacheStrategy(DiskCacheStrategy.ALL) .error(R.drawable.image_as_cover) .into(holder.imageView) when { playlistDetails -> { holder.root.setOnClickListener { Toast.makeText(context, "play list details", Toast.LENGTH_SHORT).show() sendIntent(position = position, parameter = "PlaylistDetailsAdapter") } } else -> { holder.itemView.setOnClickListener { if (MainActivity.isSearching) { sendIntent(position = position, parameter = "MusicAdapterSearch") } else { sendIntent(position = position, parameter = "MusicAdapter") } } } } } override fun getItemCount(): Int { return musicList.size } fun updateMusicList(searchList: ArrayList<MusicClass>) { musicList = ArrayList() musicList.addAll(searchList) notifyDataSetChanged() } private fun sendIntent(position: Int, parameter: String) { val intent = Intent(context, MusicInterface::class.java) intent.putExtra("index", position) intent.putExtra("class", parameter) ContextCompat.startActivity(context, intent, null) } }
practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/adapters/AdapterViewPager.kt
3158684326
package com.example.practice_musicplayer.adapters import android.annotation.SuppressLint import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import androidx.viewpager2.widget.ViewPager2 import com.bumptech.glide.Glide import com.bumptech.glide.load.DecodeFormat import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.request.RequestOptions import com.example.practice_musicplayer.MusicClass import com.example.practice_musicplayer.R import com.example.practice_musicplayer.SlidingActivity import com.example.practice_musicplayer.databinding.ItemLargeCarouselBinding import com.google.android.material.card.MaterialCardView class AdapterViewPager( private val context: Context, private var musicList: ArrayList<MusicClass>, ) : RecyclerView.Adapter<AdapterViewPager.MyHolder>() { class MyHolder(binding: ItemLargeCarouselBinding) : RecyclerView.ViewHolder(binding.root) { val songNameUp = binding.mtvItem val songName = binding.songName val singerName = binding.singerName val imgSmall = binding.imgSmall val imgLarge = binding.imgLarge val root = binding.root } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder { return MyHolder( ItemLargeCarouselBinding.inflate( LayoutInflater.from( context ), parent, false ) ) } @SuppressLint("CutPasteId", "NotifyDataSetChanged") override fun onBindViewHolder(holder: MyHolder, position: Int) { holder.itemView.findViewById<MaterialCardView>(R.id.smalCard).visibility = if (SlidingActivity.statePanel) View.GONE else View.VISIBLE holder.songNameUp.text = musicList[position].name holder.songName.text = musicList[position].name holder.singerName.text = musicList[position].artist val optionSmall = RequestOptions() .centerCrop() .override(100, 100) Glide .with(context) .applyDefaultRequestOptions(optionSmall) .load(musicList[position].coverArtUrl) .diskCacheStrategy(DiskCacheStrategy.ALL) .error(R.drawable.image_as_cover) .into(holder.imgSmall) val otionsLarge = RequestOptions() .format(DecodeFormat.PREFER_ARGB_8888) // Use higher quality ARGB_8888 format .diskCacheStrategy(DiskCacheStrategy.ALL) // Cache both original and transformed images .override(500, 500) // Load the original image size Glide .with(context) .load(musicList[position].coverArtUrl) .apply(otionsLarge) .error(R.drawable.image_as_cover) .into(holder.imgLarge) } override fun getItemCount(): Int { return musicList.size } }
practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/activities/MusicInterface.kt
3534139419
package com.example.practice_musicplayer.activities import android.annotation.SuppressLint import android.content.ComponentName import android.content.ContentValues import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.graphics.BitmapFactory import android.graphics.drawable.GradientDrawable import android.media.AudioManager import android.media.MediaPlayer import android.media.audiofx.AudioEffect import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.IBinder import android.util.Log import android.widget.SeekBar import android.widget.Toast import androidx.core.content.ContextCompat import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.example.practice_musicplayer.MainActivity import com.example.practice_musicplayer.MusicClass import com.example.practice_musicplayer.MusicService import com.example.practice_musicplayer.MyService import com.example.practice_musicplayer.R import com.example.practice_musicplayer.databinding.ActivityMusicInterfaceBinding import com.example.practice_musicplayer.exitApplication import com.example.practice_musicplayer.formatDuration import com.example.practice_musicplayer.fragments.NowPlaying import com.example.practice_musicplayer.getImageArt import com.example.practice_musicplayer.getMainColor import com.example.practice_musicplayer.setSongPosition import com.example.practice_musicplayer.utils.OnSwipeTouchListener import com.google.android.material.snackbar.Snackbar @Suppress("DEPRECATION") class MusicInterface : AppCompatActivity(), ServiceConnection, MediaPlayer.OnCompletionListener { companion object { @SuppressLint("StaticFieldLeak") lateinit var binding: ActivityMusicInterfaceBinding lateinit var musicList: ArrayList<MusicClass> var musicService: MusicService? = null var myService: MyService? = null var songPosition: Int = 0 var isPlaying: Boolean = false var isRepeating: Boolean = false var isShuffling: Boolean = false var counter: Int = 0 set(value) { field = kotlin.math.max(value, 0) } var fIndex: Int = -1 var isLiked: Boolean = false var min15: Boolean = false var min30: Boolean = false var min60: Boolean = false var musicUrl = "https://aydym.com/audioFiles/original/2023/10/24/17/42/944dc23f-c4cf-4267-8122-34b3eb2bada8.mp3" } @SuppressLint("ClickableViewAccessibility") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMusicInterfaceBinding.inflate(layoutInflater) setContentView(binding.root) binding.interfaceSongName.isSelected = true binding.backButton.setOnClickListener { finish() } // musicList = ArrayList() // val songList = MainActivity.songList // musicList.add(songList[songPosition]) // val response = musicList[songPosition] if (intent.data?.scheme.contentEquals("content")) { val intentService = Intent(this, MusicService::class.java) bindService(intentService, this, BIND_AUTO_CREATE) startService(intentService) Glide.with(this).load(MainActivity.songList!![songPosition].coverArtUrl).apply( RequestOptions().placeholder(R.drawable.image_as_cover).centerCrop() ).into(binding.interfaceCover) Log.e("IF ", MainActivity.songList!![songPosition].url) binding.interfaceSongName.text = MainActivity.songList!![songPosition].name binding.interfaceArtistName.text = MainActivity.songList!![songPosition].artist } else { Log.e("ELSE ", intent.getIntExtra("index", 0).toString()) Log.e("aglama", MainActivity.songList.toString()) initActivity() } binding.interfacePlay.setOnClickListener { if (isPlaying) pauseMusic() else playMusic() } binding.interfaceNext.setOnClickListener { prevNextSong(increment = true) } binding.interfacePrevious.setOnClickListener { prevNextSong(increment = false) } binding.seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar?, progress: Int, isUser: Boolean) { try { if (isUser) { musicService!!.mediaPlayer!!.seekTo(progress) musicService!!.showNotification(if (isPlaying) R.drawable.pause_notification else R.drawable.play_notification) } } catch (e: Exception) { return } } override fun onStartTrackingTouch(p0: SeekBar?) = Unit override fun onStopTrackingTouch(p0: SeekBar?) = Unit }) binding.interfaceEqualizer.setOnClickListener { try { val eqIntent = Intent(AudioEffect.ACTION_DISPLAY_AUDIO_EFFECT_CONTROL_PANEL) eqIntent.putExtra( AudioEffect.EXTRA_AUDIO_SESSION, musicService!!.mediaPlayer!!.audioSessionId ) eqIntent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, baseContext.packageName) eqIntent.putExtra(AudioEffect.EXTRA_CONTENT_TYPE, AudioEffect.CONTENT_TYPE_MUSIC) startActivityForResult(eqIntent, 3) } catch (e: Exception) { Snackbar.make( this, it, "Equalizer feature not supported in your device.", 3000 ).show() } } binding.interfaceCover.setOnTouchListener(object : OnSwipeTouchListener(baseContext) { override fun onSingleClick() { if (isPlaying) { pauseMusic() } else { playMusic() } } override fun onSwipeDown() { Log.d(ContentValues.TAG, "onSwipeDown: Performed") finish() } override fun onSwipeLeft() { prevNextSong(increment = true) } override fun onSwipeRight() { prevNextSong(increment = false) } }) binding.root.setOnTouchListener(object : OnSwipeTouchListener(baseContext) { override fun onSwipeDown() { Log.d(ContentValues.TAG, "onSwipeDown: Performed") finish() } override fun onSwipeLeft() { prevNextSong(increment = true) } override fun onSwipeRight() { prevNextSong(increment = false) } }) } private fun initActivity() { songPosition = intent.getIntExtra("index", 0) when (intent.getStringExtra("class")) { "MusicAdapter" -> { initServiceAndPlaylist(MainActivity.songList!!, shuffle = false) } "Now playing" -> { showMusicInterfacePlaying() } "Now Playing Notification" -> { showMusicInterfacePlaying() } } } private fun setLayout() { try { Glide.with(this).load(MainActivity.songList!![songPosition].coverArtUrl).apply( RequestOptions().placeholder(R.drawable.image_as_cover).centerCrop() ).into(binding.interfaceCover) binding.interfaceSongName.text = MainActivity.songList!![songPosition].name binding.interfaceArtistName.text = MainActivity.songList!![songPosition].artist if (isRepeating) { binding.interfaceRepeat.setImageResource(R.drawable.repeat_on) binding.interfaceRepeat.setColorFilter(ContextCompat.getColor(this, R.color.green)) } if (isShuffling) { binding.interfaceShuffle.setColorFilter(ContextCompat.getColor(this, R.color.green)) binding.interfaceShuffle.setImageResource(R.drawable.shuffle_fill) } if (isLiked) { NowPlaying.binding.fragmentHeartButton.setImageResource(R.drawable.heart_fill) binding.interfaceLikeButton.setImageResource(R.drawable.heart_fill) } else { NowPlaying.binding.fragmentHeartButton.setImageResource(R.drawable.heart) binding.interfaceLikeButton.setImageResource(R.drawable.heart) } val img = getImageArt(MainActivity.songList!![songPosition].coverArtUrl) val image = if (img != null) { BitmapFactory.decodeByteArray(img, 0, img.size) } else { BitmapFactory.decodeResource( resources, R.drawable.image_as_cover ) } val bgColor = getMainColor(image) val gradient = GradientDrawable( GradientDrawable.Orientation.BOTTOM_TOP, intArrayOf(0xFFFFFF, bgColor) ) binding.root.background = gradient window?.statusBarColor = bgColor } catch (e: Exception) { return } } private fun initSong() { try { if (musicService!!.mediaPlayer == null) musicService!!.mediaPlayer = MediaPlayer() musicService!!.mediaPlayer!!.reset() musicService!!.mediaPlayer!!.setDataSource(MainActivity.songList!![songPosition].url) musicService!!.mediaPlayer!!.prepare() binding.interfacePlay.setImageResource((R.drawable.pause)) binding.interfaceSeekStart.text = formatDuration(musicService!!.mediaPlayer!!.currentPosition.toLong()) binding.interfaceSeekEnd.text = formatDuration(musicService!!.mediaPlayer!!.duration.toLong()) binding.seekbar.progress = 0 binding.seekbar.max = musicService!!.mediaPlayer!!.duration musicService!!.mediaPlayer!!.setOnCompletionListener(this) playMusic() } catch (e: Exception) { return } } fun playMusic() { try { musicService!!.audioManager.requestAudioFocus( musicService, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN ) isPlaying = true musicService!!.mediaPlayer!!.start() binding.interfacePlay.setImageResource((R.drawable.pause)) musicService!!.showNotification(R.drawable.pause_notification) NowPlaying.binding.fragmentButton.setImageResource(R.drawable.pause_now) } catch (e: Exception) { return } } fun pauseMusic() { try { musicService!!.audioManager.abandonAudioFocus(musicService) isPlaying = false musicService!!.mediaPlayer!!.pause() binding.interfacePlay.setImageResource((R.drawable.play)) musicService!!.showNotification(R.drawable.play_notification) NowPlaying.binding.fragmentButton.setImageResource(R.drawable.play_now) } catch (e: Exception) { return } } private fun prevNextSong(increment: Boolean) { if (increment) { setSongPosition(increment = true) setLayout() initSong() counter-- } else { setSongPosition(increment = false) setLayout() initSong() } } override fun onServiceConnected(name: ComponentName?, service: IBinder?) { Toast.makeText(this, "connected", Toast.LENGTH_SHORT).show() if (musicService == null) { val binder = service as MusicService.MyBinder musicService = binder.currentService() musicService!!.audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager musicService!!.audioManager.requestAudioFocus( musicService, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN ) } initSong() musicService!!.seekBarHandler() } override fun onServiceDisconnected(p0: ComponentName?) { musicService = null Toast.makeText(this, "disconnected", Toast.LENGTH_SHORT).show() } override fun onCompletion(p0: MediaPlayer?) { setSongPosition(increment = true) setLayout() initSong() counter-- //for refreshing now playing image & text on song completion NowPlaying.binding.fragmentTitle.isSelected = true Glide.with(applicationContext).load(MainActivity.songList!![songPosition].url) .apply(RequestOptions().placeholder(R.drawable.image_as_cover).centerCrop()) .into(NowPlaying.binding.fragmentImage) NowPlaying.binding.fragmentTitle.text = MainActivity.songList!![songPosition].name NowPlaying.binding.fragmentAlbumName.text = MainActivity.songList!![songPosition].artist } @Deprecated("Deprecated in Java") override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == 3 || resultCode == RESULT_OK) return } override fun onDestroy() { super.onDestroy() if (MainActivity.songList!![songPosition].id == 0 && !isPlaying) exitApplication() } private fun showMusicInterfacePlaying() { setLayout() binding.interfaceSeekStart.text = formatDuration(musicService!!.mediaPlayer!!.currentPosition.toLong()) binding.interfaceSeekEnd.text = formatDuration(musicService!!.mediaPlayer!!.duration.toLong()) binding.seekbar.progress = musicService!!.mediaPlayer!!.currentPosition binding.seekbar.max = musicService!!.mediaPlayer!!.duration if (isPlaying) { binding.interfacePlay.setImageResource((R.drawable.pause)) } else { binding.interfacePlay.setImageResource((R.drawable.play)) } } override fun onPause() { super.onPause() overridePendingTransition(0, com.google.android.material.R.anim.mtrl_bottom_sheet_slide_out) } override fun onResume() { super.onResume() overridePendingTransition(com.google.android.material.R.anim.mtrl_bottom_sheet_slide_in, 0) } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) if (intent != null) { showMusicInterfacePlaying() } } fun initServiceAndPlaylist( playlist: ArrayList<MusicClass>, shuffle: Boolean, ) { val intent = Intent(this, MusicService::class.java) bindService(intent, this, BIND_AUTO_CREATE) startService(intent) musicList = ArrayList() musicList.addAll(playlist) // if (shuffle) musicList!!.shuffle() setLayout() } }
CESS/src/main/kotlin/me/aquabtw/cess/listener/ConnectionListener.kt
4044288832
package me.aquabtw.cess.listener import me.aquabtw.cess.CESS import me.aquabtw.cess.utils.mini import org.bukkit.Bukkit import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.player.PlayerJoinEvent import org.bukkit.event.player.PlayerQuitEvent class ConnectionListener( private val main: CESS ) : Listener { @EventHandler fun onJoin(event: PlayerJoinEvent) { updateJoinMessage(event) } @EventHandler fun onQuit(event: PlayerQuitEvent) { updateQuitMessage(event) } private fun updateJoinMessage(event: PlayerJoinEvent) { val player = event.player if (!player.hasPlayedBefore()) { val uniqueJoins = Bukkit.getOfflinePlayers().size event.joinMessage(mini("<light_purple>+ <gray>${player.name} <dark_gray>(${uniqueJoins})")) } else { event.joinMessage(mini("<green>+ <gray>${player.name}")) } } private fun updateQuitMessage(event: PlayerQuitEvent) { event.quitMessage(mini("<red>- <gray>${event.player.name}")) } }
CESS/src/main/kotlin/me/aquabtw/cess/utils/Adventure.kt
1933639748
package me.aquabtw.cess.utils import net.kyori.adventure.text.Component import net.kyori.adventure.text.format.TextDecoration import net.kyori.adventure.text.minimessage.MiniMessage import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver private fun getResolvers(): TagResolver { return TagResolver.resolver( TagResolver.standard(), Placeholder.parsed("cess", "<bold><gradient:#ffafcc:#bde0fe>CESS<reset>"), Placeholder.parsed("dot", "<bold><dark_gray>β€’<reset>") ) } val miniMessage: MiniMessage = MiniMessage.builder() .tags(getResolvers()) .build() internal fun mini(s: String): Component { val component = miniMessage.deserialize(s) if (!component.hasDecoration(TextDecoration.ITALIC)) { return component.decoration(TextDecoration.ITALIC, false) } return component }
CESS/src/main/kotlin/me/aquabtw/cess/command/CESSCommand.kt
3267842646
package me.aquabtw.cess.command import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.command.TabCompleter abstract class CESSCommand( val name: String ) : CommandExecutor, TabCompleter { override fun onCommand(sender: CommandSender, command: Command, alias: String, args: Array<out String>): Boolean { onCommand(sender, alias, args) return true } override fun onTabComplete( sender: CommandSender, command: Command, alias: String, args: Array<out String> ): List<String> { return onTabComplete(sender, alias, args) } abstract fun onCommand(sender: CommandSender, alias: String, args: Array<out String>) abstract fun onTabComplete(sender: CommandSender, alias: String, args: Array<out String>): List<String> }
CESS/src/main/kotlin/me/aquabtw/cess/command/GamemodeCommand.kt
2847432204
package me.aquabtw.cess.command import me.aquabtw.cess.CESS import me.aquabtw.cess.utils.mini import org.bukkit.GameMode import org.bukkit.command.CommandSender import org.bukkit.entity.Player class GamemodeCommand( private val main: CESS ) : CESSCommand("gmc") { override fun onCommand(sender: CommandSender, alias: String, args: Array<out String>) { if (sender !is Player) return val gameMode = when (alias) { "gmc" -> GameMode.CREATIVE "gms" -> GameMode.SURVIVAL "gmsp" -> GameMode.SPECTATOR "gma" -> GameMode.ADVENTURE else -> GameMode.SURVIVAL } sender.gameMode = gameMode sender.sendMessage(mini("<cess> <dot> <green>Set your gamemode to ${gameMode.name}")) } override fun onTabComplete(sender: CommandSender, alias: String, args: Array<out String>): List<String> { return emptyList() } }
CESS/src/main/kotlin/me/aquabtw/cess/CESS.kt
3840750249
package me.aquabtw.cess import me.aquabtw.cess.command.GamemodeCommand import me.aquabtw.cess.listener.ConnectionListener import org.bukkit.Bukkit import org.bukkit.plugin.java.JavaPlugin class CESS : JavaPlugin() { override fun onEnable() { registerListeners() registerCommands() logger.info("CESS has started!") } private fun registerCommands() { setOf( GamemodeCommand(this) ).forEach { val command = getCommand(it.name) ?: return@forEach command.setExecutor(it) command.tabCompleter = it } } private fun registerListeners() { setOf( ConnectionListener(this) ).forEach { Bukkit.getPluginManager().registerEvents(it, this) } } }
Desafio-Dio/src/main/kotlin/me/dio/credit/application/system/entity/Credit.kt
2071105256
package me.dio.credit.application.system.entity import jakarta.persistence.* import me.dio.credit.application.system.enummeration.Status import java.math.BigDecimal import java.time.LocalDate import java.util.UUID @Entity //@Table(name = "Credito") data class Credit ( @Column(nullable = false, unique = true) val creditCode: UUID = UUID.randomUUID(), @Column(nullable = false) val creditValue: BigDecimal = BigDecimal.ZERO, @Column(nullable = false) val dayFirstInstallment: LocalDate, @Column(nullable = false) val numberOfInstallments: Int = 0, @Enumerated val status: Status = Status.IN_PROGRESS, @ManyToOne var customer: Customer? = null, @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long? = null)
Desafio-Dio/src/main/kotlin/me/dio/credit/application/system/entity/Customer.kt
1089055478
package me.dio.credit.application.system.entity import jakarta.persistence.* import java.math.BigDecimal @Entity //@Table(name = "Cliente") data class Customer( @Column(nullable = false) var firstName: String = "", @Column(nullable = false) var lastName: String = "", @Column(nullable = false, unique = true) var cpf: String = "", @Column(nullable = false, unique = true) var email: String = "", @Column(nullable = false) var income: BigDecimal = BigDecimal.ZERO, @Column(nullable = false) var password: String = "", @Column(nullable = false) @Embedded var address: Address = Address(), @Column(nullable = false) @OneToMany(fetch = FetchType.LAZY, cascade = arrayOf(CascadeType.REMOVE, CascadeType.PERSIST), mappedBy = "customer") var credits: List<Credit> = mutableListOf(), @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long? = null )
Desafio-Dio/src/main/kotlin/me/dio/credit/application/system/entity/Address.kt
1728191815
package me.dio.credit.application.system.entity import jakarta.persistence.Column import jakarta.persistence.Embeddable @Embeddable data class Address( @Column(nullable = false) var zipCode: String = "", @Column(nullable = false) var street: String = "" )
csm3123-lab6/Lab6_AmphibianApp-master/app/src/androidTest/java/com/example/amphibians/InstrumentationTests.kt
1817480679
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.amphibians import androidx.fragment.app.testing.launchFragmentInContainer import androidx.test.core.app.launchActivity import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import com.example.amphibians.ui.AmphibianListFragment import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class InstrumentationTests : BaseTest() { @Test fun `recycler_view_content`() { launchFragmentInContainer<AmphibianListFragment>(themeResId = R.style.Theme_Amphibians) waitForView(withText("Great Basin Spadefoot")).check(matches(isDisplayed())) waitForView(withText("Tiger Salamander")).check(matches(isDisplayed())) } @Test fun `detail_content`() { launchActivity<MainActivity>() waitForView(withText("Blue Jeans Frog")).perform(click()) waitForView(withText("Blue Jeans Frog")).check(matches(isDisplayed())) waitForView(withText("Sometimes called the Strawberry Poison-Dart Frog, this little " + "amphibian is identifiable by its bright red body and blueish-purple arms and " + "legs. The Blue Jeans Frog is not toxic to humans like some of its close " + "relatives, but it can be harmful to some predators.")) .check(matches(isDisplayed())) } }
csm3123-lab6/Lab6_AmphibianApp-master/app/src/androidTest/java/com/example/amphibians/BaseTest.kt
2273097844
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.amphibians import android.view.View import androidx.test.espresso.Espresso.onView import androidx.test.espresso.NoMatchingViewException import androidx.test.espresso.UiController import androidx.test.espresso.ViewAction import androidx.test.espresso.ViewInteraction import androidx.test.espresso.matcher.ViewMatchers.isRoot import androidx.test.espresso.util.TreeIterables import org.hamcrest.Matcher import java.lang.Exception import java.lang.Thread.sleep open class BaseTest { companion object { fun lookFor(matcher: Matcher<View>): ViewAction { return object : ViewAction { override fun getConstraints(): Matcher<View> { return isRoot() } override fun getDescription(): String { return "Looking for $matcher" } override fun perform(uiController: UiController?, view: View?) { var attempts = 0 val childViews: Iterable<View> = TreeIterables.breadthFirstViewTraversal(view) childViews.forEach { attempts++ if (matcher.matches(it)) { return } } throw NoMatchingViewException.Builder() .withRootView(view) .withViewMatcher(matcher) .build() } } } } fun waitForView(matcher: Matcher<View>, timeoutMillis: Int = 5000, attemptTimeoutMillis: Long = 100 ): ViewInteraction { val maxAttempts = timeoutMillis / attemptTimeoutMillis.toInt() var attempts = 0 for (i in 0..maxAttempts) { try { attempts++ onView(isRoot()).perform(lookFor(matcher)) return onView(matcher) } catch (e: Exception) { if (attempts == maxAttempts) { throw e } sleep(attemptTimeoutMillis) } } throw Exception("Could not find a view matching $matcher") } }
csm3123-lab6/Lab6_AmphibianApp-master/app/src/main/java/com/example/amphibians/ui/AmphibianDetailFragment.kt
444233151
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.amphibians.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import com.example.amphibians.databinding.FragmentAmphibianDetailBinding /** * This Fragment shows the detailed information on a particular Amphibian */ class AmphibianDetailFragment : Fragment() { private val viewModel: AmphibianViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val binding = FragmentAmphibianDetailBinding.inflate(inflater) binding.lifecycleOwner = this binding.viewModel = viewModel // Inflate the layout for this fragment return binding.root } }
csm3123-lab6/Lab6_AmphibianApp-master/app/src/main/java/com/example/amphibians/ui/AmphibianViewModel.kt
1548828569
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.amphibians.ui import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.amphibians.network.Amphibian import com.example.amphibians.network.AmphibianApi import com.example.amphibians.network.AmphibianApiService import kotlinx.coroutines.launch enum class AmphibianApiStatus {LOADING, ERROR, DONE} class AmphibianViewModel : ViewModel() { private val _status = MutableLiveData<AmphibianApiStatus>() val status: LiveData<AmphibianApiStatus> = _status // Create properties to represent MutableLiveData and LiveData for a single amphibian object. // This will be used to display the details of an amphibian when a list item is clicked private val _amphibians = MutableLiveData<List<Amphibian>>() val amphibians: LiveData<List<Amphibian>> = _amphibians private val _amphibian = MutableLiveData<Amphibian>() val amphibian: LiveData<Amphibian> = _amphibian init { getAmphibianList() } private fun getAmphibianList() { viewModelScope.launch { _status.value = AmphibianApiStatus.LOADING try { _amphibians.value = AmphibianApi.retrofitService.getAmphibians() _status.value = AmphibianApiStatus.DONE } catch (e: Exception) { _status.value = AmphibianApiStatus.ERROR _amphibians.value = emptyList() } } } fun onAmphibianClicked(amphibian: Amphibian) { // Set the amphibian object _amphibian.value= amphibian } }
csm3123-lab6/Lab6_AmphibianApp-master/app/src/main/java/com/example/amphibians/ui/AmphibianListFragment.kt
1661950255
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.amphibians.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController import com.example.amphibians.R import com.example.amphibians.databinding.FragmentAmphibianListBinding class AmphibianListFragment : Fragment() { private val viewModel: AmphibianViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val binding = FragmentAmphibianListBinding.inflate(inflater) // TODO: call the view model method that calls the amphibians app binding.lifecycleOwner = this binding.viewModel = viewModel binding.recyclerView.adapter = AmphibianListAdapter(AmphibianListener { amphibian -> viewModel.onAmphibianClicked(amphibian) findNavController() .navigate(R.id.action_amphibianListFragment_to_amphibianDetailFragment) }) // Inflate the layout for this fragment return binding.root } }
csm3123-lab6/Lab6_AmphibianApp-master/app/src/main/java/com/example/amphibians/ui/AmphibianListAdapter.kt
1932573560
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.amphibians.ui import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.example.amphibians.databinding.ListViewItemBinding import com.example.amphibians.network.Amphibian /** * This class implements a [RecyclerView] [ListAdapter] which uses Data Binding to present [List] * data, including computing diffs between lists. */ class AmphibianListAdapter(val clickListener: AmphibianListener) : ListAdapter<Amphibian, AmphibianListAdapter.AmphibianViewHolder>(DiffCallback) { class AmphibianViewHolder( var binding: ListViewItemBinding ) : RecyclerView.ViewHolder(binding.root){ fun bind(clickListener: AmphibianListener, amphibian: Amphibian) { binding.amphibian = amphibian binding.clickListener = clickListener binding.executePendingBindings() } } companion object DiffCallback : DiffUtil.ItemCallback<Amphibian>() { override fun areItemsTheSame(oldItem: Amphibian, newItem: Amphibian): Boolean { return oldItem.name == newItem.name } override fun areContentsTheSame(oldItem: Amphibian, newItem: Amphibian): Boolean { return oldItem.type == newItem.type && oldItem.description == newItem.description } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AmphibianViewHolder { val layoutInflater = LayoutInflater.from(parent.context) return AmphibianViewHolder( ListViewItemBinding.inflate(layoutInflater, parent, false) ) } override fun onBindViewHolder(holder: AmphibianViewHolder, position: Int) { val amphibian = getItem(position) holder.bind(clickListener, amphibian) } } class AmphibianListener(val clickListener: (amphibian: Amphibian) -> Unit) { fun onClick(amphibian: Amphibian) = clickListener(amphibian) }
csm3123-lab6/Lab6_AmphibianApp-master/app/src/main/java/com/example/amphibians/MainActivity.kt
3623787225
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.amphibians import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.NavigationUI.setupActionBarWithNavController class MainActivity : AppCompatActivity() { private lateinit var navController: NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val navHostFragment = supportFragmentManager .findFragmentById(R.id.nav_host_fragment) as NavHostFragment navController = navHostFragment.navController setupActionBarWithNavController(this, navController) } override fun onSupportNavigateUp(): Boolean { return navController.navigateUp() || super.onSupportNavigateUp() } }
csm3123-lab6/Lab6_AmphibianApp-master/app/src/main/java/com/example/amphibians/BindingAdapters.kt
2455731843
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.amphibians import android.view.View import android.widget.ImageView import androidx.databinding.BindingAdapter import androidx.recyclerview.widget.RecyclerView import com.example.amphibians.network.Amphibian import com.example.amphibians.ui.AmphibianApiStatus import com.example.amphibians.ui.AmphibianListAdapter /** * Updates the data shown in the [RecyclerView] */ @BindingAdapter("listData") fun bindRecyclerView(recyclerView: RecyclerView, data: List<Amphibian>?) { val adapter = recyclerView.adapter as AmphibianListAdapter adapter.submitList(data) } /** * This binding adapter displays the [AmphibianApiStatus] of the network request in an image view. * When the request is loading, it displays a loading_animation. If the request has an error, it * displays a broken image to reflect the connection error. When the request is finished, it * hides the image view. */ @BindingAdapter("apiStatus") fun bindStatus(statusImageView: ImageView, status: AmphibianApiStatus?) { when(status) { AmphibianApiStatus.LOADING -> { statusImageView.visibility = View.VISIBLE statusImageView.setImageResource(R.drawable.loading_animation) } AmphibianApiStatus.DONE -> { statusImageView.visibility = View.GONE } AmphibianApiStatus.ERROR -> { statusImageView.visibility = View.VISIBLE statusImageView.setImageResource(R.drawable.ic_connection_error) } } }
csm3123-lab6/Lab6_AmphibianApp-master/app/src/main/java/com/example/amphibians/network/Amphibian.kt
3993332077
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.amphibians.network import com.squareup.moshi.Json /** * This data class defines an Amphibian which includes the amphibian's name, the type of * amphibian, and a brief description of the amphibian. * The property names of this data class are used by Moshi to match the names of values in JSON. */ data class Amphibian( val name: String, val type: String, val description: String )
csm3123-lab6/Lab6_AmphibianApp-master/app/src/main/java/com/example/amphibians/network/AmphibianApiService.kt
1098614865
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.amphibians.network import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import retrofit2.http.GET // Create a property for the base URL provided in the codelab- done private const val BASE_URL = "https://developer.android.com/courses/pathways/android-basics-kotlin-unit-4-pathway-2/" // Build the Moshi object with Kotlin adapter factory that Retrofit will be using to parse JSON-done private val moshi = Moshi.Builder() .add(KotlinJsonAdapterFactory()) .build() // Build a Retrofit object with the Moshi converter-done private val retrofit = Retrofit.Builder() .addConverterFactory(MoshiConverterFactory.create(moshi)) .baseUrl(BASE_URL) .build() interface AmphibianApiService { // Declare a suspended function to get the list of amphibians @GET("android-basics-kotlin-unit-4-pathway-2-project-api.json") suspend fun getAmphibians(): List<Amphibian> } // Create an object that provides a lazy-initialized retrofit service-done object AmphibianApi { val retrofitService: AmphibianApiService by lazy { retrofit.create(AmphibianApiService::class.java) } }
csm3123-lab6/lab6_coroutines-main/threadcount.kt
1028030537
fun main() { var count = 0 for (i in 1..50) { Thread { count += 1 println("Thread: $i count: $count") }.start() } }
csm3123-lab6/lab6_coroutines-main/coroutine2.kt
2095651887
import kotlinx.coroutines.* import java.time.LocalDateTime import java.time.format.DateTimeFormatter val formatter = DateTimeFormatter.ISO_LOCAL_TIME val time = { formatter.format(LocalDateTime.now()) } suspend fun getValue(): Double { println("entering getValue() at ${time()}") delay(3000) println("leaving getValue() at ${time()}") return Math.random() } fun main() { runBlocking { val num1 = getValue() val num2 = getValue() println("result of num1 + num2 is ${num1 + num2}") } }
csm3123-lab6/lab6_coroutines-main/coroutine2a.kt
621519227
import kotlinx.coroutines.* import java.time.LocalDateTime import java.time.format.DateTimeFormatter val formatter = DateTimeFormatter.ISO_LOCAL_TIME val time = { formatter.format(LocalDateTime.now()) } suspend fun getValue(): Double { println("entering getValue() at ${time()}") delay(3000) println("leaving getValue() at ${time()}") return Math.random() } fun main() { runBlocking { val num1 = async { getValue() } val num2 = async { getValue() } println("result of num1 + num2 is ${num1.await() + num2.await()}") } }
csm3123-lab6/lab6_coroutines-main/practiceExercise.kt
3462655626
import kotlinx.coroutines.* fun main() { val states = arrayOf("Starting", "Doing Task 1", "Doing Task 2", "Ending") repeat(3) { GlobalScope.launch { //use coroutines instead of thread println("${Thread.currentThread()} has started") for (i in states) { println("${Thread.currentThread()} - $i") } } } }
csm3123-lab6/lab6_coroutines-main/multiplethread.kt
1902275933
fun main() { val states = arrayOf("Starting", "Doing Task 1", "Doing Task 2", "Ending") repeat(3) { Thread { println("${Thread.currentThread()} has started") for (i in states) { println("${Thread.currentThread()} - $i") Thread.sleep(50) //sleep for 50ms } }.start() } }
csm3123-lab6/lab6_coroutines-main/thread.kt
3726304761
fun main() { val thread = Thread { println("${Thread.currentThread()} has run.") } thread.start() }
csm3123-lab6/lab6_coroutines-main/coroutine1.kt
173352602
import kotlinx.coroutines.* fun main() { repeat(3) { GlobalScope.launch { println("Hi from ${Thread.currentThread()}") } } }
csm3123-lab6/Lab6_Debugging-master/app/src/androidTest/java/com/example/debugging/ExampleInstrumentedTest.kt
866264895
package com.example.debugging 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.debugging", appContext.packageName) } }
csm3123-lab6/Lab6_Debugging-master/app/src/test/java/com/example/debugging/ExampleUnitTest.kt
4266698688
package com.example.debugging 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) } }
csm3123-lab6/Lab6_Debugging-master/app/src/main/java/com/example/debugging/MainActivity.kt
599676396
package com.example.debugging import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log public val TAG = "MainActivity" class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) division() } fun division() { val numerator = 60 var denominator = 4 repeat(4) { Log.v(TAG, "${numerator / denominator}") denominator-- } } }
csm3123-lab6/Lab6_MarsPhotoDisplayImage-master/app/src/main/java/com/example/android/marsphotos/MainActivity.kt
892584274
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.marsphotos import android.os.Bundle import androidx.appcompat.app.AppCompatActivity /** * MainActivity sets the content view activity_main, a fragment container that contains * overviewFragment. */ class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }