content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.jalloft.noteskt.database
import com.jalloft.noteskt.models.Notes
import kotlinx.coroutines.Dispatchers
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction
import org.jetbrains.exposed.sql.transactions.transaction
object DatabaseFactory {
fun init(){
val database = Database.connect(
url = System.getenv("DATABASE_URL"),
driver = "org.postgresql.Driver",
user = System.getenv("DATABASE_USERNAME"),
password = System.getenv("DATABASE_PASSWORD")
)
transaction(database){
SchemaUtils.create(Notes)
}
}
suspend fun <T> dbQuery(block: suspend () -> T): T =
newSuspendedTransaction(Dispatchers.IO) { block() }
} | notes-api/src/main/kotlin/com/jalloft/noteskt/database/DatabaseFactory.kt | 910673858 |
package com.jalloft.noteskt.repository
import com.jalloft.noteskt.dao.note.NoteDao
import com.jalloft.noteskt.dao.note.NoteDaoImpl
import com.jalloft.noteskt.models.Note
class NoteRepository(
private val dao: NoteDao = NoteDaoImpl()
) {
suspend fun notes(userId: String) = dao.allNotes(userId)
suspend fun note(noteId: String, userId: String) = dao.note(noteId, userId)
suspend fun save(note: Note) = dao.save(note)
suspend fun edit(noteId: String, note: Note) = dao.edit(noteId, note)
suspend fun saveAll(notes: List<Note>) = dao.saveAll(notes)
suspend fun delete(noteId: String) = dao.delete(noteId)
}
| notes-api/src/main/kotlin/com/jalloft/noteskt/repository/NoteRepository.kt | 2643890809 |
package com.jalloft.noteskt.repository
import com.jalloft.noteskt.dao.user.UserDao
import com.jalloft.noteskt.dao.user.UserDaoImpl
import com.jalloft.noteskt.models.User
class UserRepository(
private val dao: UserDao = UserDaoImpl()
) {
suspend fun findUserByEmail(email: String) = dao.findUserByEmail(email)
suspend fun saveUser(user: User) = dao.saveUser(user)
} | notes-api/src/main/kotlin/com/jalloft/noteskt/repository/UserRepository.kt | 523977395 |
package com.jalloft.noteskt
import com.jalloft.noteskt.database.DatabaseFactory
import com.jalloft.noteskt.plugins.configureRouting
import com.jalloft.noteskt.plugins.configureSecurity
import com.jalloft.noteskt.plugins.configureSerialization
import com.jalloft.noteskt.plugins.configureStatusPage
import com.jalloft.noteskt.repository.NoteRepository
import com.jalloft.noteskt.repository.UserRepository
import com.jalloft.noteskt.security.hashing.SHA256HashingService
import com.jalloft.noteskt.security.token.JwtTokenService
import com.jalloft.noteskt.security.token.TokenConfig
import io.ktor.server.application.*
fun main(args: Array<String>) {
io.ktor.server.netty.EngineMain.main(args)
}
fun Application.module() {
val tokenService = JwtTokenService()
val tokenConfig = TokenConfig(
issuer = environment.config.property("jwt.issuer").getString(),
audience = environment.config.property("jwt.audience").getString(),
expiresIn = 365L * 1000L * 60L * 60L * 24L,
secret = System.getenv("JWT_SECRET")
)
val hashingService = SHA256HashingService()
val noteRepo = NoteRepository()
val userRepo = UserRepository()
DatabaseFactory.init()
configureSerialization()
configureStatusPage()
configureSecurity(tokenConfig)
configureRouting(noteRepo, userRepo, hashingService, tokenService, tokenConfig)
}
| notes-api/src/main/kotlin/com/jalloft/noteskt/Application.kt | 4187176 |
package com.jalloft.noteskt.security.token
data class TokenClaim(
val name: String,
val value: String
)
| notes-api/src/main/kotlin/com/jalloft/noteskt/security/token/TokenClaim.kt | 2609684956 |
package com.jalloft.noteskt.security.token
interface TokenService {
fun generate(
config: TokenConfig,
vararg claims: TokenClaim
): String
} | notes-api/src/main/kotlin/com/jalloft/noteskt/security/token/TokenService.kt | 3132866280 |
package com.jalloft.noteskt.security.token
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import java.util.*
class JwtTokenService: TokenService {
override fun generate(config: TokenConfig, vararg claims: TokenClaim): String {
var token = JWT.create()
.withAudience(config.audience)
.withIssuer(config.issuer)
.withExpiresAt(Date(System.currentTimeMillis() + config.expiresIn))
claims.forEach { claim ->
token = token.withClaim(claim.name, claim.value)
}
return token.sign(Algorithm.HMAC256(config.secret))
}
} | notes-api/src/main/kotlin/com/jalloft/noteskt/security/token/JwtTokenService.kt | 744943561 |
package com.jalloft.noteskt.security.token
data class TokenConfig(
val issuer: String,
val audience: String,
val expiresIn: Long,
val secret: String
)
| notes-api/src/main/kotlin/com/jalloft/noteskt/security/token/TokenConfig.kt | 1793161922 |
package com.jalloft.noteskt.security.hashing
interface HashingService {
fun generateSaltedHash(value: String, saltLength: Int = 32): SaltedHash
fun verify(value: String, saltedHash: SaltedHash): Boolean
} | notes-api/src/main/kotlin/com/jalloft/noteskt/security/hashing/HashingService.kt | 1627462456 |
package com.jalloft.noteskt.security.hashing
data class SaltedHash(
val hash: String,
val salt: String
) | notes-api/src/main/kotlin/com/jalloft/noteskt/security/hashing/SaltedHash.kt | 123645532 |
package com.jalloft.noteskt.security.hashing
import org.apache.commons.codec.binary.Hex
import org.apache.commons.codec.digest.DigestUtils
import java.security.SecureRandom
class SHA256HashingService: HashingService {
override fun generateSaltedHash(value: String, saltLength: Int): SaltedHash {
val salt = SecureRandom.getInstance("SHA1PRNG").generateSeed(saltLength)
val saltAsHex = Hex.encodeHexString(salt)
val hash = DigestUtils.sha256Hex("$saltAsHex$value")
return SaltedHash(
hash = hash,
salt = saltAsHex
)
}
override fun verify(value: String, saltedHash: SaltedHash): Boolean {
return DigestUtils.sha256Hex(saltedHash.salt + value) == saltedHash.hash
}
} | notes-api/src/main/kotlin/com/jalloft/noteskt/security/hashing/SHA256HashingService.kt | 2619393247 |
package com.jalloft.noteskt.plugins
import com.jalloft.noteskt.repository.NoteRepository
import com.jalloft.noteskt.repository.UserRepository
import com.jalloft.noteskt.routes.*
import com.jalloft.noteskt.security.hashing.HashingService
import com.jalloft.noteskt.security.token.TokenConfig
import com.jalloft.noteskt.security.token.TokenService
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.routing.*
fun Application.configureRouting(
noteRepo: NoteRepository,
userRepo: UserRepository,
hashingService: HashingService,
tokenService: TokenService,
tokenConfig: TokenConfig
) {
routing {
authenticate {
getNotes(noteRepo)
getNote(noteRepo)
postNote(noteRepo)
postNotes(noteRepo)
deleteNote(noteRepo)
putNote(noteRepo)
}
signIn(userRepo, hashingService, tokenService, tokenConfig)
signUp(hashingService, userRepo)
authenticate()
getSecretInfo()
}
}
| notes-api/src/main/kotlin/com/jalloft/noteskt/plugins/Routing.kt | 267905119 |
package com.jalloft.noteskt.plugins
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.plugins.contentnegotiation.*
import kotlinx.serialization.json.Json
fun Application.configureSerialization() {
install(ContentNegotiation) {
json(Json {
ignoreUnknownKeys = true
})
}
}
| notes-api/src/main/kotlin/com/jalloft/noteskt/plugins/Serialization.kt | 1473978943 |
package com.jalloft.noteskt.plugins
import com.jalloft.noteskt.exceptions.AuthenticationException
import com.jalloft.noteskt.exceptions.UserNotFoundException
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.plugins.statuspages.*
import io.ktor.server.response.*
fun Application.configureStatusPage(){
install(StatusPages) {
exception<AuthenticationException> { call, cause ->
call.respond(status = HttpStatusCode.Unauthorized, message = cause.message ?: "Authentication failed!")
}
exception<UserNotFoundException> { call, cause ->
call.respond(status = HttpStatusCode.Unauthorized, message = cause.message ?: "Authentication failed!")
}
status(HttpStatusCode.NotFound) { call, status ->
call.respond(message = "404: Page Not Found", status = status)
}
}
} | notes-api/src/main/kotlin/com/jalloft/noteskt/plugins/Status.kt | 2808075603 |
package com.jalloft.noteskt.plugins
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.jalloft.noteskt.exceptions.AuthenticationException
import com.jalloft.noteskt.security.token.TokenConfig
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.plugins.*
fun Application.configureSecurity(config: TokenConfig) {
install(Authentication) {
jwt {
realm = [email protected]("jwt.realm").getString()
verifier(
JWT
.require(Algorithm.HMAC256(config.secret))
.withAudience(config.audience)
.withIssuer(config.issuer)
.build()
)
validate { credential ->
if (credential.payload.audience.contains(config.audience)) {
JWTPrincipal(credential.payload)
} else null
}
challenge { _, _ ->
call.request.headers["Authorization"]?.let {
if (it.isNotEmpty()) {
throw AuthenticationException("Token Expired")
} else {
throw BadRequestException("Authorization header can not be blank!")
}
} ?: throw AuthenticationException("You are not authorized to access")
}
}
}
} | notes-api/src/main/kotlin/com/jalloft/noteskt/plugins/Security.kt | 3448442348 |
package com.jalloft.noteskt.serialization
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializer
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import java.util.*
@OptIn(ExperimentalSerializationApi::class)
@Serializer(forClass = UUID::class)
object UUIDSerializer : KSerializer<UUID> {
override fun serialize(encoder: Encoder, value: UUID) {
encoder.encodeString(value.toString())
}
override fun deserialize(decoder: Decoder): UUID {
return UUID.fromString(decoder.decodeString())
}
} | notes-api/src/main/kotlin/com/jalloft/noteskt/serialization/UUIDSerializer.kt | 2891912568 |
package com.jalloft.noteskt.serialization
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializer
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
@OptIn(ExperimentalSerializationApi::class)
@Serializer(forClass = LocalDateTime::class)
object LocalDateSerializer : KSerializer<LocalDateTime> {
private val formatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME
override fun serialize(encoder: Encoder, value: LocalDateTime) {
encoder.encodeString(value.format(formatter))
}
override fun deserialize(decoder: Decoder): LocalDateTime {
return LocalDateTime.parse(decoder.decodeString(), formatter)
}
} | notes-api/src/main/kotlin/com/jalloft/noteskt/serialization/LocalDateSerializer.kt | 225923155 |
package com.jalloft.noteskt.dao.note
import com.jalloft.noteskt.database.DatabaseFactory
import com.jalloft.noteskt.models.Note
import com.jalloft.noteskt.models.Notes
import com.jalloft.noteskt.utils.toUUID
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.statements.InsertStatement
class NoteDaoImpl : NoteDao {
override suspend fun allNotes(userId: String): List<Note> = DatabaseFactory.dbQuery {
val uuid = userId.toUUID() ?: return@dbQuery emptyList()
Notes.selectAll().where { Notes.userId eq uuid }.map(::resultRowToNote)
}
override suspend fun note(noteId: String, userId: String): Note? = DatabaseFactory.dbQuery {
val uuidNote = noteId.toUUID() ?: return@dbQuery null
val uuidUser = userId.toUUID() ?: return@dbQuery null
Notes.selectAll().where { Notes.userId eq uuidUser }.andWhere { Notes.id eq uuidNote }
.map(::resultRowToNote)
.singleOrNull()
}
override suspend fun save(note: Note) = DatabaseFactory.dbQuery {
val insertStatement = Notes.insert { insertNoteRows(it, note) }
insertStatement.resultedValues?.singleOrNull()?.let(::resultRowToNote)
}
override suspend fun edit(noteId: String, note: Note): Boolean {
val uuid = noteId.toUUID() ?: return false
return Notes.update({ Notes.id eq uuid }) {
it[Notes.title] = note.title
it[Notes.content] = note.content
} > 0
}
override suspend fun delete(noteId: String): Boolean {
val uuid = noteId.toUUID() ?: return false
return Notes.deleteWhere { Notes.id eq uuid } > 0
}
override suspend fun saveAll(notes: List<Note>) = DatabaseFactory.dbQuery {
val insertStatements = notes.map { note -> Notes.insert { insertNoteRows(it, note) } }
insertStatements.map { it.resultedValues?.singleOrNull()?.let(::resultRowToNote) }
}
private fun resultRowToNote(row: ResultRow) =
Note(
id = row[Notes.id],
userId = row[Notes.userId],
title = row[Notes.title],
content = row[Notes.content],
createdAt = row[Notes.createdAt]
)
private fun insertNoteRows(insertStatement: InsertStatement<Number>, note: Note) {
insertStatement[Notes.id] = note.id
note.userId?.let { insertStatement[Notes.userId] = it }
insertStatement[Notes.title] = note.title
insertStatement[Notes.content] = note.content
insertStatement[Notes.createdAt] = note.createdAt
}
}
| notes-api/src/main/kotlin/com/jalloft/noteskt/dao/note/NoteDaoImpl.kt | 3475208618 |
package com.jalloft.noteskt.dao.note
import com.jalloft.noteskt.models.Note
interface NoteDao {
suspend fun allNotes(userId: String): List<Note>
suspend fun note(noteId: String, userId: String): Note?
suspend fun save(note: Note): Note?
suspend fun edit(noteId: String, note: Note): Boolean
suspend fun delete(noteId: String): Boolean
suspend fun saveAll(notes: List<Note>): List<Note?>
} | notes-api/src/main/kotlin/com/jalloft/noteskt/dao/note/NoteDao.kt | 256896980 |
package com.jalloft.noteskt.dao.user
import com.jalloft.noteskt.database.DatabaseFactory
import com.jalloft.noteskt.models.User
import com.jalloft.noteskt.models.Users
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.selectAll
class UserDaoImpl : UserDao {
override suspend fun findUserByEmail(email: String): User? = DatabaseFactory.dbQuery {
Users.selectAll()
.where { Users.email eq email }
.map { User(it[Users.id], it[Users.email], it[Users.password], it[Users.salt]) }
.singleOrNull()
}
override suspend fun saveUser(user: User) = DatabaseFactory.dbQuery {
val insertStatement = Users.insert {
it[id] = user.id
it[email] = user.email
it[password] = user.password
it[salt] = user.salt
}
insertStatement.resultedValues.orEmpty().isNotEmpty()
}
} | notes-api/src/main/kotlin/com/jalloft/noteskt/dao/user/UserDaoImpl.kt | 3548208924 |
package com.jalloft.noteskt.dao.user
import com.jalloft.noteskt.models.User
interface UserDao {
suspend fun findUserByEmail(email: String): User?
suspend fun saveUser(user: User): Boolean
} | notes-api/src/main/kotlin/com/jalloft/noteskt/dao/user/UserDao.kt | 2059403877 |
package com.jalloft.noteskt.utils
import java.util.*
fun String.toUUID(): UUID? =
try {
UUID.fromString(this)
} catch (_: Throwable) {
null
} | notes-api/src/main/kotlin/com/jalloft/noteskt/utils/Extensions.kt | 1403201659 |
package com.jalloft.noteskt.models
import org.jetbrains.exposed.sql.Table
import org.jetbrains.exposed.sql.javatime.CurrentDateTime
import org.jetbrains.exposed.sql.javatime.datetime
import java.time.LocalDateTime
import java.util.*
data class Note(
val id: UUID = UUID.randomUUID(),
val userId: UUID? = null,
val title: String,
val content: String,
val createdAt: LocalDateTime = LocalDateTime.now()
)
object Notes : Table() {
val id = uuid("id").autoGenerate()
val userId = uuid("userId").references(Users.id)
val title = varchar("title", 128)
val content = varchar("content", 1024)
val createdAt = datetime("createdIn").defaultExpression(CurrentDateTime)
override val primaryKey = PrimaryKey(id)
} | notes-api/src/main/kotlin/com/jalloft/noteskt/models/Note.kt | 1773077157 |
package com.jalloft.noteskt.models
import org.jetbrains.exposed.sql.Table
import java.util.*
data class User(
val id: UUID = UUID.randomUUID(),
val email: String,
val password: String,
val salt: String,
)
object Users: Table(){
val id = uuid("id").autoGenerate()
val email = varchar("email", 255)
val password = varchar("password", 255)
val salt = varchar("salt", 128)
override val primaryKey = PrimaryKey(id)
}
| notes-api/src/main/kotlin/com/jalloft/noteskt/models/User.kt | 1666993124 |
package com.jalloft.noteskt.exceptions
data class AuthenticationException(
override val message: String? = null,
override val cause: Throwable? = null
): Throwable(message, cause) | notes-api/src/main/kotlin/com/jalloft/noteskt/exceptions/AuthenticationException.kt | 1518596341 |
package com.jalloft.noteskt.exceptions
data class UserNotFoundException(
override val message: String? = null,
override val cause: Throwable? = null
): Throwable(message, cause) | notes-api/src/main/kotlin/com/jalloft/noteskt/exceptions/UserNotFoundException.kt | 2817984432 |
package com.jalloft.noteskt.routes
import com.jalloft.noteskt.dto.NoteRequest
import com.jalloft.noteskt.dto.OtherResponse
import com.jalloft.noteskt.dto.toNoteResponse
import com.jalloft.noteskt.repository.NoteRepository
import com.jalloft.noteskt.utils.toUUID
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction
fun Route.getNotes(noteRepo: NoteRepository){
get("/notes") {
val principal = call.principal<JWTPrincipal>()
val userId = principal?.payload?.getClaim("userId")?.asString()
if (userId != null){
val notes = noteRepo.notes(userId).map { it.toNoteResponse() }
call.respond(HttpStatusCode.OK, notes)
}else{
call.respond(HttpStatusCode.Unauthorized)
}
}
}
fun Route.getNote(noteRepo: NoteRepository){
get("/note/{id?}") {
val noteId = call.parameters["id"] ?: return@get call.respond(
HttpStatusCode.BadRequest,
OtherResponse(HttpStatusCode.BadRequest.value, "ID ausente")
)
val principal = call.principal<JWTPrincipal>()
val userId = principal?.payload?.getClaim("userId")?.asString()
if (userId != null) {
val note = noteRepo.note(noteId, userId) ?: return@get call.respond(
HttpStatusCode.NotFound,
OtherResponse(HttpStatusCode.NotFound.value, "Nenhuma anotação encontrada com este ID")
)
call.respond(HttpStatusCode.OK, note.toNoteResponse())
} else {
call.respond(HttpStatusCode.Unauthorized)
}
}
}
fun Route.deleteNote(noteRepo: NoteRepository){
delete("/note/{id?}") {
val noteId = call.parameters["id"] ?: return@delete call.respond(HttpStatusCode.BadRequest)
newSuspendedTransaction {
val isDeleted = noteRepo.delete(noteId)
if (isDeleted) {
call.respond(
HttpStatusCode.Accepted,
OtherResponse(HttpStatusCode.Accepted.value, "Anotação excluída com sucesso")
)
} else {
call.respond(
HttpStatusCode.NotFound,
OtherResponse(HttpStatusCode.NotFound.value, "Nenhuma anotação encontrada com este ID")
)
}
}
}
}
fun Route.postNote(noteRepo: NoteRepository){
post("/note") {
val principal = call.principal<JWTPrincipal>()
val userId = principal?.payload?.getClaim("userId")?.asString()?.toUUID()
if (userId != null) {
val noteRequest = call.receive<NoteRequest>()
val note = noteRepo.save(noteRequest.copy(userId = userId).toNote()) ?: return@post call.respond(HttpStatusCode.BadRequest)
call.respond(HttpStatusCode.Created, note.toNoteResponse())
}else{
call.respond(HttpStatusCode.Unauthorized)
}
}
}
fun Route.postNotes(noteRepo: NoteRepository){
post("/notes") {
val notesRequest = call.receive<List<NoteRequest>>()
val savedNotes = noteRepo.saveAll(notesRequest.map { it.toNote() })
call.respond(HttpStatusCode.Created, savedNotes.map { it?.toNoteResponse() })
}
}
fun Route.putNote(noteRepo: NoteRepository){
put("/note/{id?}") {
val noteId = call.parameters["id"] ?: return@put call.respond(HttpStatusCode.BadRequest)
val noteRequest = call.receive<NoteRequest>()
val isUpdated = noteRepo.edit(noteId, noteRequest.toNote())
if (isUpdated) {
call.respond(
HttpStatusCode.Accepted,
OtherResponse(HttpStatusCode.Accepted.value, "Anotação atualizada com sucesso")
)
} else {
call.respond(
HttpStatusCode.NotFound,
OtherResponse(HttpStatusCode.NotFound.value, "Nenhuma anotação encontrada com este ID")
)
}
}
}
| notes-api/src/main/kotlin/com/jalloft/noteskt/routes/NoteRoutes.kt | 994202199 |
package com.jalloft.noteskt.routes
import com.jalloft.noteskt.dto.AuthRequest
import com.jalloft.noteskt.dto.AuthResponse
import com.jalloft.noteskt.models.User
import com.jalloft.noteskt.repository.UserRepository
import com.jalloft.noteskt.security.hashing.HashingService
import com.jalloft.noteskt.security.hashing.SaltedHash
import com.jalloft.noteskt.security.token.TokenClaim
import com.jalloft.noteskt.security.token.TokenConfig
import com.jalloft.noteskt.security.token.TokenService
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import org.apache.commons.codec.digest.DigestUtils
fun Route.signUp(
hashingService: HashingService,
repo: UserRepository
){
post("signup"){
val request = call.receive<AuthRequest>()
val areFieldsBlank = request.email.isBlank() || request.password.isBlank()
val isPwTooShort = request.password.length < 8
if(areFieldsBlank || isPwTooShort) {
call.respond(HttpStatusCode.Conflict)
return@post
}
val saltedHash = hashingService.generateSaltedHash(request.password)
val user = User(
email = request.email,
password = saltedHash.hash,
salt = saltedHash.salt
)
val wasAcknowledged = repo.saveUser(user)
if(!wasAcknowledged) {
call.respond(HttpStatusCode.Conflict)
return@post
}
call.respond(HttpStatusCode.OK)
}
}
fun Route.signIn(
repo: UserRepository,
hashingService: HashingService,
tokenService: TokenService,
tokenConfig: TokenConfig
) {
post("signin") {
val request = call.receive<AuthRequest>()
val user = repo.findUserByEmail(request.email)
if(user == null) {
call.respond(HttpStatusCode.Conflict, "Incorrect username or password")
return@post
}
val isValidPassword = hashingService.verify(
value = request.password,
saltedHash = SaltedHash(
hash = user.password,
salt = user.salt
)
)
if(!isValidPassword) {
println("Entered hash: ${DigestUtils.sha256Hex("${user.salt}${request.password}")}, Hashed PW: ${user.password}")
call.respond(HttpStatusCode.Conflict, "Incorrect username or password")
return@post
}
val token = tokenService.generate(
config = tokenConfig,
TokenClaim(
name = "userId",
value = user.id.toString()
)
)
call.respond(
status = HttpStatusCode.OK,
message = AuthResponse(
token = token
)
)
}
}
fun Route.authenticate() {
authenticate {
get("authenticate") {
call.respond(HttpStatusCode.OK)
}
}
}
fun Route.getSecretInfo() {
authenticate {
get("secret") {
val principal = call.principal<JWTPrincipal>()
val userId = principal?.getClaim("userId", String::class)
call.respond(HttpStatusCode.OK, "Your userId is $userId")
}
}
} | notes-api/src/main/kotlin/com/jalloft/noteskt/routes/UserRoutes.kt | 1947460051 |
package com.muindi.stephen.radio_group_buttons
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.muindi.stephen.radio_group_buttons.test", appContext.packageName)
}
} | Custom-Radio-Group-Buttons/radio-group-buttons/src/androidTest/java/com/muindi/stephen/radio_group_buttons/ExampleInstrumentedTest.kt | 2012737974 |
package com.muindi.stephen.radio_group_buttons
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)
}
} | Custom-Radio-Group-Buttons/radio-group-buttons/src/test/java/com/muindi/stephen/radio_group_buttons/ExampleUnitTest.kt | 870396780 |
package com.muindi.stephen.radio_group_buttons
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.muindi.stephen.radio_group_buttons.R.*
class RadioGroupButtons : AppCompatActivity() {
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_radio_group_buttons)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(id.radio_group_buttons)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
// This will get the radiogroup
val rGroup = findViewById<View>(R.id.radioGroup1) as RadioGroup
val tv = findViewById<TextView>(R.id.textView2)
// This will get the radiobutton in the radiogroup that is checked
val checkedRadioButton =
rGroup.findViewById<View>(rGroup.checkedRadioButtonId) as RadioButton
// This overrides the radiogroup onCheckListener
rGroup.setOnCheckedChangeListener { group, checkedId ->
// This will get the radiobutton that has changed in its check state
val checkedRadioButton = group.findViewById<View>(checkedId) as RadioButton
// This puts the value (true/false) into the variable
val isChecked = checkedRadioButton.isChecked
// If the radiobutton that has changed in check state is now checked...
if (isChecked) {
// Changes the textview's text to "Checked: example radiobutton text"
tv.text = checkedRadioButton.getText()
checkedRadioButton.setBackgroundResource(drawable.frame_51)
checkedRadioButton.setTextColor(ContextCompat.getColor(this,color.white))
for (i in 0 until group.childCount) {
val radioButton = group.getChildAt(i) as RadioButton
if (radioButton.id != checkedId) {
radioButton.setBackgroundResource(drawable.frame_52)
radioButton.setTextColor(ContextCompat.getColor(this,color.black))
}
}
}
}
}
} | Custom-Radio-Group-Buttons/radio-group-buttons/src/main/java/com/muindi/stephen/radio_group_buttons/RadioGroupButtons.kt | 2173639334 |
package com.muindi.stephen.radiogrouplibrary
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.muindi.stephen.radiogrouplibrary", appContext.packageName)
}
} | Custom-Radio-Group-Buttons/app/src/androidTest/java/com/muindi/stephen/radiogrouplibrary/ExampleInstrumentedTest.kt | 1969169547 |
package com.muindi.stephen.radiogrouplibrary
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)
}
} | Custom-Radio-Group-Buttons/app/src/test/java/com/muindi/stephen/radiogrouplibrary/ExampleUnitTest.kt | 632537617 |
package com.muindi.stephen.radiogrouplibrary
/**
* Stephen Muindi (c) 2024
* Radio Group Library
*/
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.muindi.stephen.radiogrouplibrary.R.*
class MainActivity : AppCompatActivity() {
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
}
} | Custom-Radio-Group-Buttons/app/src/main/java/com/muindi/stephen/radiogrouplibrary/MainActivity.kt | 838673152 |
package io.github.mpichler94.beeradvisor
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class BeerAdvisorApplicationTests {
@Test
fun contextLoads() {
}
}
| beer-advisor/src/test/kotlin/io/github/mpichler94/beeradvisor/BeerAdvisorApplicationTests.kt | 1135471001 |
package io.github.mpichler94.beeradvisor.beer
import org.springframework.data.repository.CrudRepository
interface BeerRepository : CrudRepository<Beer, Long>
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/beer/BeerRepository.kt | 4145510135 |
package io.github.mpichler94.beeradvisor.beer
import org.springframework.data.repository.CrudRepository
interface BreweryRepository : CrudRepository<Brewery, Long>
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/beer/BreweryRepository.kt | 2473079072 |
package io.github.mpichler94.beeradvisor.beer
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.server.ResponseStatusException
import kotlin.jvm.optionals.getOrNull
@RestController
@RequestMapping(value = ["/api/brewery"], produces = [MediaType.APPLICATION_JSON_VALUE])
class BreweryController(private val repository: BreweryRepository) {
@PostMapping
private fun createBrewery(
@RequestBody brewery: BreweryDto,
): BreweryDto {
val created = repository.save(Brewery(null, brewery.name))
return BreweryDto(created.name)
}
@GetMapping
private fun breweries(): Iterable<BreweryDto> {
return repository.findAll().map { BreweryDto(it.name) }
}
@GetMapping("/{breweryId}")
private fun brewery(
@PathVariable breweryId: Long,
): BreweryDto {
val brewery = repository.findById(breweryId).getOrNull() ?: throw ResponseStatusException(HttpStatus.NOT_FOUND)
return BreweryDto(brewery.name)
}
}
internal class BreweryDto(val name: String)
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/beer/BreweryController.kt | 3336414844 |
package io.github.mpichler94.beeradvisor.beer
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.JoinColumn
import jakarta.persistence.ManyToOne
import jakarta.persistence.SequenceGenerator
@Entity(name = "Beers")
class Beer(
@Id
@Column(nullable = false, updatable = false)
@SequenceGenerator(name = "beer_sequence", sequenceName = "beer_sequence", allocationSize = 1, initialValue = 10000)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "beer_sequence")
val id: Long?,
val name: String,
@ManyToOne
@JoinColumn(name = "brewery_id")
val brewery: Brewery,
val type: String,
val alcohol: Float,
@Column(columnDefinition = "TEXT")
val description: String,
val reviews: Int = 0,
val stars: Float = 0f,
)
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/beer/Beer.kt | 462941442 |
package io.github.mpichler94.beeradvisor.beer
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.util.Assert
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.server.ResponseStatusException
import kotlin.jvm.optionals.getOrNull
@RestController
@RequestMapping(value = ["/api/beer"], produces = [MediaType.APPLICATION_JSON_VALUE])
class BeerController(private val repository: BeerRepository, private val breweryRepository: BreweryRepository) {
@PostMapping
private fun createBeer(
@RequestBody beer: BeerDto,
): BeerDto {
val brewery = breweryRepository.findById(beer.breweryId)
Assert.state(brewery.isPresent, "Brewery ${beer.breweryId} not found")
val created = repository.save(Beer(null, beer.name, brewery.get(), beer.type, beer.alcohol, beer.description))
return BeerDto(
created.name,
created.type,
created.brewery.id!!,
created.alcohol,
created.description,
created.reviews,
created.stars,
)
}
@GetMapping
private fun beers(): Iterable<BeerDto> {
return repository.findAll().map { BeerDto(it.name, it.type, it.brewery.id!!, it.alcohol, it.description, it.reviews, it.stars) }
}
@GetMapping("/{beerId}")
private fun beer(
@PathVariable beerId: Long,
): BeerDto {
val beer = repository.findById(beerId).getOrNull() ?: throw ResponseStatusException(HttpStatus.NOT_FOUND)
return BeerDto(beer.name, beer.type, beer.brewery.id!!, beer.alcohol, beer.description, beer.reviews, beer.stars)
}
}
internal class BeerDto(
val name: String,
val type: String,
val breweryId: Long,
val alcohol: Float,
val description: String,
val reviews: Int = 0,
val stars: Float = 0f,
)
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/beer/BeerController.kt | 1678546817 |
package io.github.mpichler94.beeradvisor.beer
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.FetchType
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.OneToMany
import jakarta.persistence.SequenceGenerator
@Entity(name = "Breweries")
class Brewery(
@Id
@Column(nullable = false, updatable = false)
@SequenceGenerator(name = "brewery_sequence", sequenceName = "brewery_sequence", allocationSize = 1, initialValue = 10000)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "brewery_sequence")
val id: Long?,
val name: String,
@OneToMany(mappedBy = "brewery", fetch = FetchType.EAGER)
val beers: Set<Beer> = setOf(),
)
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/beer/Brewery.kt | 2332135694 |
package io.github.mpichler94.beeradvisor.util
class NotFoundException : RuntimeException {
constructor() : super()
constructor(message: String) : super(message)
}
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/util/NotFoundException.kt | 140719055 |
package io.github.mpichler94.beeradvisor.util
import jakarta.servlet.FilterChain
import jakarta.servlet.ServletException
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.slf4j.MDC
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Component
import org.springframework.web.filter.OncePerRequestFilter
import java.io.IOException
import java.util.UUID
@Component
class MdcFilter(@Value("\${beer.web.requestHeader:X-Header-Token}") private val requestHeader: String?,
@Value("\${beer.web.responseHeader:Response_Token}") private val responseHeader: String?,
@Value("\${beer.web.mdcTokenKey:requestId}") private val mdcTokenKey: String?) : OncePerRequestFilter() {
@Throws(ServletException::class, IOException::class)
override fun doFilterInternal(
request: HttpServletRequest,
response: HttpServletResponse,
filterChain: FilterChain,
) {
try {
val token =
if (!requestHeader.isNullOrEmpty() && !request.getHeader(requestHeader).isNullOrEmpty()) {
request.getHeader(requestHeader)
} else {
UUID.randomUUID().toString().replace("-", "")
}
MDC.put(mdcTokenKey, token)
if (!responseHeader.isNullOrEmpty()) {
response.addHeader(responseHeader, token)
}
filterChain.doFilter(request, response)
} finally {
MDC.remove(mdcTokenKey)
}
}
}
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/util/MdcFilter.kt | 3164015132 |
package io.github.mpichler94.beeradvisor.config
data class ErrorResponse(
var httpStatus: Int? = null,
var exception: String? = null,
var message: String? = null,
var fieldErrors: List<FieldError>? = null,
)
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/config/ErrorResponse.kt | 2377727256 |
package io.github.mpichler94.beeradvisor.config
import com.fasterxml.jackson.databind.ObjectMapper
import jakarta.servlet.http.HttpServletResponse
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpStatus
import org.springframework.http.ProblemDetail
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.invoke
import org.springframework.security.crypto.factory.PasswordEncoderFactories
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.security.web.SecurityFilterChain
import org.springframework.security.web.authentication.AuthenticationFailureHandler
import org.springframework.security.web.authentication.AuthenticationSuccessHandler
import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler
import org.springframework.security.web.context.DelegatingSecurityContextRepository
import org.springframework.security.web.context.HttpSessionSecurityContextRepository
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.CorsConfigurationSource
import org.springframework.web.cors.UrlBasedCorsConfigurationSource
import java.net.URI
@Configuration
@EnableWebSecurity
class SecurityConfig(private val mapper: ObjectMapper) {
@Bean
fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
cors {}
csrf { disable() } // FIXME: Enable in production
authorizeRequests {
authorize("/api/user/**", permitAll)
authorize("/api/**", authenticated)
authorize("/**", permitAll)
}
securityContext {
securityContextRepository =
DelegatingSecurityContextRepository(
RequestAttributeSecurityContextRepository(),
HttpSessionSecurityContextRepository(),
)
}
formLogin {
loginProcessingUrl = "/api/user/login"
authenticationSuccessHandler =
AuthenticationSuccessHandler {
_,
response,
_,
->
response.status = HttpServletResponse.SC_OK
}
authenticationFailureHandler =
AuthenticationFailureHandler { _, response, exception ->
val detail = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Invalid credentials provided")
detail.type = URI.create("about:blank")
detail.title = "Bad Credentials"
detail.properties = mapOf("message" to exception.message)
response.status = HttpServletResponse.SC_BAD_REQUEST
mapper.writeValue(response.writer, detail)
}
permitAll = true
}
exceptionHandling {
authenticationEntryPoint = Http403ForbiddenEntryPoint()
}
logout {
logoutUrl = "/api/user/logout"
logoutSuccessHandler = LogoutSuccessHandler { _, response, _ -> response.status = HttpServletResponse.SC_OK }
}
}
return http.build()
}
@Bean
fun corsConfigurationSource(): CorsConfigurationSource {
val config =
CorsConfiguration().apply {
allowedOrigins = listOf("http://localhost:8081")
allowedMethods = listOf("*")
allowedHeaders = listOf("*")
allowCredentials = true
}
return UrlBasedCorsConfigurationSource().apply {
registerCorsConfiguration("/**", config)
}
}
@Bean
fun passwordEncoder(): PasswordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder()
}
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/config/SecurityConfig.kt | 2472000589 |
package io.github.mpichler94.beeradvisor.config
import io.github.mpichler94.beeradvisor.util.NotFoundException
import io.swagger.v3.oas.annotations.responses.ApiResponse
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.validation.BindingResult
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.server.ResponseStatusException
@RestControllerAdvice(annotations = [RestController::class])
class RestExceptionHandler {
@ExceptionHandler(NotFoundException::class)
fun handleNotFound(exception: NotFoundException): ResponseEntity<ErrorResponse> {
val errorResponse = ErrorResponse()
errorResponse.httpStatus = HttpStatus.NOT_FOUND.value()
errorResponse.exception = exception::class.simpleName
errorResponse.message = exception.message
return ResponseEntity(errorResponse, HttpStatus.NOT_FOUND)
}
@ExceptionHandler(MethodArgumentNotValidException::class)
fun handleMethodArgumentNotValid(exception: MethodArgumentNotValidException): ResponseEntity<ErrorResponse> {
val bindingResult: BindingResult = exception.bindingResult
val fieldErrors: List<FieldError> =
bindingResult.fieldErrors
.stream()
.map { error ->
var fieldError = FieldError()
fieldError.errorCode = error.code
fieldError.field = error.field
fieldError
}
.toList()
val errorResponse = ErrorResponse()
errorResponse.httpStatus = HttpStatus.BAD_REQUEST.value()
errorResponse.exception = exception::class.simpleName
errorResponse.fieldErrors = fieldErrors
return ResponseEntity(errorResponse, HttpStatus.BAD_REQUEST)
}
@ExceptionHandler(ResponseStatusException::class)
fun handleResponseStatus(exception: ResponseStatusException): ResponseEntity<ErrorResponse> {
val errorResponse = ErrorResponse()
errorResponse.httpStatus = exception.statusCode.value()
errorResponse.exception = exception::class.simpleName
errorResponse.message = exception.message
return ResponseEntity(errorResponse, exception.statusCode)
}
@ExceptionHandler(Throwable::class)
@ApiResponse(
responseCode = "4xx/5xx",
description = "Error",
)
fun handleThrowable(exception: Throwable): ResponseEntity<ErrorResponse> {
exception.printStackTrace()
val errorResponse = ErrorResponse()
errorResponse.httpStatus = HttpStatus.INTERNAL_SERVER_ERROR.value()
errorResponse.exception = exception::class.simpleName
return ResponseEntity(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR)
}
}
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/config/RestExceptionHandler.kt | 3082929302 |
package io.github.mpichler94.beeradvisor.config
data class FieldError(
var `field`: String? = null,
var errorCode: String? = null,
)
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/config/FieldError.kt | 1303870783 |
package io.github.mpichler94.beeradvisor.user
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.JoinColumn
import jakarta.persistence.ManyToOne
import jakarta.persistence.SequenceGenerator
import org.springframework.security.core.GrantedAuthority
@Entity(name = "Authorities")
class BeerAuthority(
@Id
@Column(nullable = false, updatable = false)
@SequenceGenerator(name = "authority_sequence", sequenceName = "authority_sequence", allocationSize = 1, initialValue = 10000)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "authority_sequence")
private val id: Long,
private val authority: String,
@ManyToOne
@JoinColumn(name = "user_id")
private val user: BeerUser,
) : GrantedAuthority {
override fun getAuthority(): String {
TODO("Not yet implemented")
}
}
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/user/BeerAuthority.kt | 4284293695 |
package io.github.mpichler94.beeradvisor.user
import org.springframework.data.repository.CrudRepository
import java.util.Optional
interface AuthorityRepository : CrudRepository<BeerAuthority, Long> {
fun findByAuthority(authority: String): Optional<BeerAuthority>
}
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/user/AuthorityRepository.kt | 2548948384 |
package io.github.mpichler94.beeradvisor.user
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.stereotype.Service
import kotlin.jvm.optionals.getOrElse
@Service
class BeerUserDetailsService(private val repository: UserRepository) : UserDetailsService {
override fun loadUserByUsername(username: String?): UserDetails {
return repository.findByUsername(username!!).getOrElse { throw UsernameNotFoundException(username) }
}
}
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/user/BeerUserDetailsService.kt | 1849527729 |
package io.github.mpichler94.beeradvisor.user
import org.springframework.data.repository.CrudRepository
import java.util.Optional
interface UserRepository : CrudRepository<BeerUser, Long> {
fun findByUsername(username: String): Optional<BeerUser>
}
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/user/UserRepository.kt | 1159183251 |
package io.github.mpichler94.beeradvisor.user
import jakarta.servlet.http.HttpServletRequest
import org.springframework.http.HttpStatus
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.server.ResponseStatusException
@RestController
@RequestMapping("/api/user")
class UserController(
private val userRepository: UserRepository,
private val authorityRepository: AuthorityRepository,
private val passwordEncoder: PasswordEncoder,
) {
@PostMapping("/register")
private fun createUser(
@RequestBody user: UserDto,
): UserDto {
if (userRepository.findByUsername(user.username).isPresent) {
throw IllegalStateException("Username already exists")
}
val authority = authorityRepository.findByAuthority("user")
if (authority.isEmpty) {
throw java.lang.IllegalStateException("Authority does not exist")
}
val createdUser =
userRepository.save(
BeerUser(
null,
user.username,
passwordEncoder.encode(user.password),
setOf(authority.get()),
),
)
return UserDto(createdUser.username)
}
@GetMapping
private fun user(request: HttpServletRequest): UserDto {
return UserDto(request.userPrincipal?.name ?: throw ResponseStatusException(HttpStatus.UNAUTHORIZED))
}
}
internal class UserDto(val username: String, val password: String? = null)
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/user/UserController.kt | 3767632855 |
package io.github.mpichler94.beeradvisor.user
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.FetchType
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.OneToMany
import jakarta.persistence.SequenceGenerator
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.userdetails.UserDetails
@Entity(name = "Users")
class BeerUser(
@Id
@Column(nullable = false, updatable = false)
@SequenceGenerator(name = "user_sequence", sequenceName = "user_sequence", allocationSize = 1, initialValue = 10000)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_sequence")
val id: Long?,
private val username: String,
private val password: String,
@OneToMany(mappedBy = "user", fetch = FetchType.EAGER)
private val authorities: Set<BeerAuthority> = setOf(),
@Column(columnDefinition = "boolean default true")
private val accountNonExpired: Boolean = true,
@Column(columnDefinition = "boolean default true")
private val accountNonLocked: Boolean = true,
@Column(columnDefinition = "boolean default true")
private val credentialsNonExpired: Boolean = true,
) : UserDetails {
override fun getAuthorities(): MutableCollection<out GrantedAuthority> {
return authorities.toMutableSet()
}
override fun getPassword(): String {
return password
}
override fun getUsername(): String {
return username
}
override fun isAccountNonExpired(): Boolean {
return accountNonExpired
}
override fun isAccountNonLocked(): Boolean {
return accountNonLocked
}
override fun isCredentialsNonExpired(): Boolean {
return credentialsNonExpired
}
override fun isEnabled(): Boolean {
return true
}
}
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/user/BeerUser.kt | 104281037 |
package io.github.mpichler94.beeradvisor.review
import org.springframework.data.repository.CrudRepository
interface ReviewRepository : CrudRepository<Review, Long>
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/review/ReviewRepository.kt | 2300176885 |
package io.github.mpichler94.beeradvisor.review
import io.github.mpichler94.beeradvisor.beer.BeerRepository
import io.github.mpichler94.beeradvisor.user.UserRepository
import io.swagger.v3.oas.annotations.responses.ApiResponse
import jakarta.servlet.http.HttpServletRequest
import jakarta.validation.Valid
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.util.Assert
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.util.Optional
@RestController
@RequestMapping(value = ["/api/beer/{beerId}/review"], produces = [MediaType.APPLICATION_JSON_VALUE])
class ReviewController(
private val repository: ReviewRepository,
private val beerRepository: BeerRepository,
private val userRepository: UserRepository,
) {
@PostMapping
@ApiResponse(responseCode = "201")
private fun createReview(
@PathVariable beerId: Long,
@RequestBody @Valid review: ReviewDto,
request: HttpServletRequest,
): ResponseEntity<ReviewDto> {
val beer = beerRepository.findById(beerId)
Assert.state(beer.isPresent, "Beer $beerId does not exist")
val username = request.userPrincipal.name
val user = userRepository.findByUsername(username)
Assert.state(user.isPresent, "User DB corrupt")
val result = repository.save(Review(null, user.get(), beer.get(), review.stars, review.content))
return ResponseEntity(
ReviewDto(result.author.username, result.content, result.stars),
HttpStatus.CREATED,
)
}
@GetMapping
private fun reviews(): Iterable<ReviewDto> {
return repository.findAll().map { ReviewDto(it.author.username, it.content, it.stars) }
}
@GetMapping("/:beerId")
private fun reviewsForBeer(
@RequestParam beerId: Optional<Long>,
): Iterable<ReviewDto> {
return repository.findAll().map { ReviewDto(it.author.username, it.content, it.stars) }
}
@GetMapping("/{id}")
private fun getReview(
@PathVariable id: Long,
): Optional<ReviewDto> {
return repository.findById(id).map { ReviewDto(it.author.username, it.content, it.stars) }
}
@PutMapping("/{id}")
private fun updateReview(
@PathVariable id: Long,
@RequestBody @Valid reviewDTO: ReviewDto,
): ResponseEntity<Long> {
// reviewService.update(id, reviewDTO)
return ResponseEntity.ok(id)
}
@DeleteMapping("/{id}")
@ApiResponse(responseCode = "204")
fun deleteReview(
@PathVariable(name = "id") id: Long,
) {
// reviewService.delete(id)
}
}
internal class ReviewDto(val author: String?, val content: String, val stars: Int)
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/review/ReviewController.kt | 4134357939 |
package io.github.mpichler94.beeradvisor.review
import io.github.mpichler94.beeradvisor.beer.Beer
import io.github.mpichler94.beeradvisor.user.BeerUser
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.JoinColumn
import jakarta.persistence.ManyToOne
import jakarta.persistence.SequenceGenerator
@Entity(name = "Reviews")
class Review(
@Id
@Column(nullable = false, updatable = false)
@SequenceGenerator(name = "review_sequence", sequenceName = "review_sequence", allocationSize = 1, initialValue = 10000)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "review_sequence")
val id: Long? = null,
@ManyToOne
@JoinColumn(name = "user_id")
val author: BeerUser,
@ManyToOne
@JoinColumn(name = "beer_id")
val beer: Beer,
val stars: Int,
val content: String = "",
)
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/review/Review.kt | 809180342 |
package io.github.mpichler94.beeradvisor
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class BeerAdvisorApplication
fun main(args: Array<String>) {
runApplication<BeerAdvisorApplication>(*args)
}
| beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/BeerAdvisorApplication.kt | 4254707028 |
package com.androidnavbar
import com.facebook.react.bridge.ReactApplicationContext
abstract class AndroidNavbarSpec internal constructor(context: ReactApplicationContext) :
NativeAndroidNavbarSpec(context) {
}
| react-native-android-navbar/android/src/newarch/AndroidNavbarSpec.kt | 1941212610 |
package com.androidnavbar
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.Promise
abstract class AndroidNavbarSpec internal constructor(context: ReactApplicationContext) :
ReactContextBaseJavaModule(context) {
abstract fun changeNavigationBarColor(color: String, light: Boolean, animated: Boolean, promise: Promise)
abstract fun hideNavigationBar(promise: Promise)
abstract fun showNavigationBar(promise: Promise)
}
| react-native-android-navbar/android/src/oldarch/AndroidNavbarSpec.kt | 3934880775 |
package com.androidnavbar
import com.facebook.react.TurboReactPackage
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.NativeModule
import com.facebook.react.module.model.ReactModuleInfoProvider
import com.facebook.react.module.model.ReactModuleInfo
import java.util.HashMap
class AndroidNavbarPackage : TurboReactPackage() {
override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? {
return if (name == AndroidNavbarModule.NAME) {
AndroidNavbarModule(reactContext)
} else {
null
}
}
override fun getReactModuleInfoProvider(): ReactModuleInfoProvider {
return ReactModuleInfoProvider {
val moduleInfos: MutableMap<String, ReactModuleInfo> = HashMap()
val isTurboModule: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
moduleInfos[AndroidNavbarModule.NAME] = ReactModuleInfo(
AndroidNavbarModule.NAME,
AndroidNavbarModule.NAME,
false, // canOverrideExistingModule
false, // needsEagerInit
true, // hasConstants
false, // isCxxModule
isTurboModule // isTurboModule
)
moduleInfos
}
}
}
| react-native-android-navbar/android/src/main/java/com/androidnavbar/AndroidNavbarPackage.kt | 1945612491 |
package com.androidnavbar
import android.animation.ArgbEvaluator
import android.animation.ValueAnimator
import android.app.Activity
import android.graphics.Color
import android.os.Build
import android.view.View
import android.view.Window
import android.view.WindowInsets
import android.view.WindowInsetsController
import android.view.WindowManager
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.UiThreadUtil
import com.facebook.react.module.annotations.ReactModule
import com.facebook.react.turbomodule.core.interfaces.TurboModule
class AndroidNavbarModule internal constructor(context: ReactApplicationContext) :
AndroidNavbarSpec(context) {
private val reactContext = context
override fun getName(): String {
return NAME
}
private fun setNavigationBarTheme(activity: Activity?, light: Boolean) {
if (activity != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
val window = activity.window
var flags = window.decorView.systemUiVisibility
flags = if (light) {
flags or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
} else {
flags and View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR.inv()
}
window.decorView.systemUiVisibility = flags
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
val flag = if (light) {
WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
} else {
0
}
val insetsController = activity.window.insetsController
insetsController?.setSystemBarsAppearance(flag, WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS)
}
}
}
@ReactMethod
override fun changeNavigationBarColor(color: String, light: Boolean, animated: Boolean, promise: Promise) {
val currentActivity = reactContext.currentActivity
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
currentActivity?.let {
UiThreadUtil.runOnUiThread {
try {
val window: Window = it.window
// Clear flags for transparent and translucent, set them later if needed
window.clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
if (color == "transparent" || color == "translucent") {
if (color == "transparent") {
window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
} else {
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
}
}
val colorTo: Int = if (color == "transparent") Color.TRANSPARENT else Color.parseColor(color)
if (animated) {
val colorFrom: Int = window.navigationBarColor
val colorAnimation = ValueAnimator.ofObject(ArgbEvaluator(), colorFrom, colorTo)
colorAnimation.duration = 200 // Duration of the animation
colorAnimation.addUpdateListener { animator ->
window.navigationBarColor = animator.animatedValue as Int
}
colorAnimation.start()
} else {
window.navigationBarColor = colorTo
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// For Android 11 (API level 30) and above
val windowInsetsController = window.insetsController
if (light) {
windowInsetsController?.setSystemBarsAppearance(
WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS,
WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
)
} else {
windowInsetsController?.setSystemBarsAppearance(
0,
WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
)
}
} else {
// For Android 8 (API level 26) to Android 10 (API level 29)
var flags: Int = window.decorView.systemUiVisibility
flags = if (light) {
flags or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
} else {
flags and View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR.inv()
}
window.decorView.systemUiVisibility = flags
}
promise.resolve(true)
} catch (e: Exception) {
promise.reject("error", e)
}
}
} ?: run {
promise.reject("E_NO_ACTIVITY", Throwable("Tried to change the navigation bar while not attached to an Activity"))
}
} else {
promise.reject("API_LEVEL", Throwable("Only Android Lollipop and above is supported"))
}
}
@ReactMethod
override fun hideNavigationBar(promise: Promise) {
val currentActivity = reactContext.currentActivity
if (currentActivity != null) {
UiThreadUtil.runOnUiThread {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// Use WindowInsetsController for Android 11 (API level 30) and above
currentActivity.window.insetsController?.hide(WindowInsets.Type.navigationBars())
} else {
// Use systemUiVisibility for API levels below 30
val decorView: View = currentActivity.window.decorView
decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
}
promise.resolve(true)
} catch (e: Exception) {
promise.reject("error", e)
}
}
} else {
promise.reject("E_NO_ACTIVITY", Throwable("Tried to hide the navigation bar while not attached to an Activity"))
}
}
@ReactMethod
override fun showNavigationBar(promise: Promise) {
val currentActivity = reactContext.currentActivity
if (currentActivity != null) {
UiThreadUtil.runOnUiThread {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// Use WindowInsetsController for Android 11 (API level 30) and above
currentActivity.window.insetsController?.show(WindowInsets.Type.navigationBars())
} else {
// Use systemUiVisibility for API levels below 30
val decorView: View = currentActivity.window.decorView
decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
}
promise.resolve(true)
} catch (e: Exception) {
promise.reject("error", e)
}
}
} else {
promise.reject("E_NO_ACTIVITY", Throwable("Tried to show the navigation bar while not attached to an Activity"))
}
}
companion object {
const val NAME = "AndroidNavbar"
}
}
| react-native-android-navbar/android/src/main/java/com/androidnavbar/AndroidNavbarModule.kt | 439360806 |
import org.gradle.api.Plugin
import org.gradle.api.initialization.Settings
import org.gradle.api.plugins.JavaApplication
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.pkl.config.java.ConfigEvaluator
import org.pkl.config.kotlin.forKotlin
import org.pkl.config.kotlin.to
import org.pkl.core.ModuleSource
import java.io.File
class Configer : Plugin<Settings> {
override fun apply(settings: Settings) {
settings.gradle.beforeProject {
val buildFile = File(project.rootDir, "build.gradle.pkl")
val config = ConfigEvaluator.preconfigured().forKotlin().use { evaluator ->
evaluator.evaluate(ModuleSource.file(buildFile))
}
val product = config["product"].to<String>()
if (product == "jvm/app") {
apply(plugin = "java")
apply(plugin = "application")
extensions.configure<JavaApplication> {
// yeah this shouldn't be hard coded
mainClass.set("Main")
}
}
/*
tasks.create("createConfig") {
val buildFile = File(project.rootDir, "build.gradle.pkl")
val sourceModules = listOf(buildFile.toURI())
val baseOptions = CliBaseOptions(sourceModules)
val options = CliKotlinCodeGeneratorOptions(
base = baseOptions,
outputDir = project.rootDir.toPath(),
)
CliKotlinCodeGenerator(options).run()
}
*/
}
}
}
| grapkl/configer/src/main/kotlin/Configer.kt | 2642287407 |
package com.example.coupproject
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.coupproject", appContext.packageName)
}
} | CoupProject/app/src/androidTest/java/com/example/coupproject/ExampleInstrumentedTest.kt | 4286613483 |
package com.example.coupproject
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)
}
} | CoupProject/app/src/test/java/com/example/coupproject/ExampleUnitTest.kt | 954523722 |
package com.example.coupproject.viewmodel
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.coupproject.domain.model.User
import com.example.coupproject.domain.usecase.login.HasAccessTokenUseCase
import com.example.coupproject.domain.usecase.main.CheckPermissionUseCase
import com.example.coupproject.domain.usecase.main.GetFriendUseCase
import com.example.coupproject.domain.usecase.main.GetMembershipUseCase
import com.example.coupproject.domain.usecase.main.SetMembershipUseCase
import com.google.android.gms.tasks.OnSuccessListener
import com.google.firebase.database.DataSnapshot
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class MainViewModel @Inject constructor(
private val getFriendUseCase: GetFriendUseCase,
private val hasAccessTokenUseCase: HasAccessTokenUseCase,
private val checkPermissionUseCase: CheckPermissionUseCase,
private val getMembershipUseCase: GetMembershipUseCase,
private val setMembershipUseCase: SetMembershipUseCase
) : ViewModel() {
private val _hasMembership = MutableStateFlow(User())
val hasMembership: StateFlow<User> = _hasMembership
fun getFriend(memberId: String, callback: OnSuccessListener<DataSnapshot>) {
viewModelScope.launch(Dispatchers.Main) {
getFriendUseCase(memberId, callback)
.catch { exception ->
Log.e(TAG, exception.message, exception)
}.collect()
}
}
fun saveFriend(user: User) {
viewModelScope.launch {
_hasMembership.emit(user)
}
}
fun getMembership(callback: OnSuccessListener<DataSnapshot>) {
viewModelScope.launch {
getMembershipUseCase(callback).catch { exception ->
Log.e(TAG, exception.message, exception)
}
}
}
companion object {
const val TAG = "MainViewModel"
}
} | CoupProject/app/src/main/java/com/example/coupproject/viewmodel/MainViewModel.kt | 515338443 |
package com.example.coupproject.viewmodel
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.coupproject.domain.usecase.login.GetAccessTokenInfoUseCase
import com.example.coupproject.domain.usecase.login.HasAccessTokenUseCase
import com.example.coupproject.domain.usecase.login.StartKakaoLoginUseCase
import com.example.coupproject.domain.usecase.main.GetFriendUseCase
import com.example.coupproject.domain.usecase.main.GetMembershipUseCase
import com.example.coupproject.view.login.LoginActivity
import com.google.android.gms.tasks.OnSuccessListener
import com.google.firebase.database.DataSnapshot
import com.kakao.sdk.auth.model.OAuthToken
import com.kakao.sdk.user.model.AccessTokenInfo
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class LoginViewModel @Inject constructor(
private val startKakaoLoginUseCase: StartKakaoLoginUseCase,
private val hasAccessTokenUseCase: HasAccessTokenUseCase,
private val getAccessTokenInfoUseCase: GetAccessTokenInfoUseCase,
private val getMembershipUseCase: GetMembershipUseCase,
private val getFriendUseCase: GetFriendUseCase,
) : ViewModel() {
private val _loginResult = MutableSharedFlow<Boolean>()
val loginResult: SharedFlow<Boolean> = _loginResult
fun startKakaoLogin(activity: LoginActivity, callback: (OAuthToken?, Throwable?) -> Unit) {
viewModelScope.launch {
startKakaoLoginUseCase.invoke(activity, callback)
.catch { exception ->
Log.e(TAG, exception.message, exception)
}
.collect {
Log.i(TAG, "ViewModel Collect")
}
}
}
fun hasAccessToken() {
viewModelScope.launch {
hasAccessTokenUseCase().catch { exception ->
Log.e(
TAG,
exception.message,
exception
)
}.collect {
_loginResult.emit(it)
}
}
}
fun getAccessTokenInfo(callback: (AccessTokenInfo?, Throwable?) -> Unit) {
viewModelScope.launch {
getAccessTokenInfoUseCase(callback).catch { exception ->
Log.e(
TAG,
exception.message,
exception
)
}
}
}
fun getMembership(callback: OnSuccessListener<DataSnapshot>) {
viewModelScope.launch {
getMembershipUseCase(callback).catch { Log.e(TAG, "Failed getMembership()", it) }
.collect { Log.i(TAG, "getMembership success") }
}
}
companion object {
const val TAG = "LoginViewModel"
}
} | CoupProject/app/src/main/java/com/example/coupproject/viewmodel/LoginViewModel.kt | 3584146071 |
package com.example.coupproject.viewmodel
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.coupproject.domain.usecase.main.SetMembershipUseCase
import com.google.android.gms.tasks.OnSuccessListener
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class MemberViewModel @Inject constructor(
private val setMembershipUseCase: SetMembershipUseCase
) : ViewModel() {
fun setMembership(name: String, memberId: String, callback: OnSuccessListener<Void>) {
viewModelScope.launch {
setMembershipUseCase.invoke(name, memberId, callback)
.catch { exception ->
Log.e(TAG, exception.message, exception)
}.collect {
Log.i(TAG, "Success SetMemberShip")
}
}
}
companion object {
const val TAG = "MemberViewModel"
}
} | CoupProject/app/src/main/java/com/example/coupproject/viewmodel/MemberViewModel.kt | 3619314968 |
package com.example.coupproject.di
import android.content.Context
import com.example.coupproject.data.repository.KakaoRepositoryImpl
import com.example.coupproject.data.repository.FirebaseRepositoryImpl
import com.example.coupproject.domain.repository.KakaoRepository
import com.example.coupproject.domain.repository.MainRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun provideLoginRepositoryImpl(@ApplicationContext context: Context): KakaoRepository {
return KakaoRepositoryImpl(context)
}
@Provides
@Singleton
fun provideMainRepositoryImpl(@ApplicationContext context: Context): MainRepository {
return FirebaseRepositoryImpl(context)
}
} | CoupProject/app/src/main/java/com/example/coupproject/di/AppModule.kt | 3132041494 |
package com.example.coupproject
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
class CoupBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(p0: Context?, intent: Intent?) {
Log.i("CoupBroadcastReceiver", "성공")
intent?.action?.let {
Log.i("CoupBroadcastReceiver", "$it 액션")
}
}
} | CoupProject/app/src/main/java/com/example/coupproject/CoupBroadcastReceiver.kt | 2344761496 |
package com.example.coupproject.view.member
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.example.coupproject.R
import com.example.coupproject.databinding.ActivityAddMemberBinding
import com.example.coupproject.view.login.LoginActivity
import com.example.coupproject.view.main.MainActivity
import com.example.coupproject.viewmodel.MemberViewModel
import com.kakao.sdk.user.UserApiClient
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class AddMemberActivity : AppCompatActivity() {
private lateinit var binding: ActivityAddMemberBinding
private val viewModel: MemberViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityAddMemberBinding.bind(
layoutInflater.inflate(
R.layout.activity_add_member,
null
)
)
binding.btnOk.setOnClickListener {
if (binding.edtName.text.isNotEmpty()) {
me(binding.edtName.text.toString())
}
}
setContentView(binding.root)
}
fun me(name: String) {
UserApiClient.instance.me { user, error ->
user?.let { users ->
viewModel.setMembership(name, users.id.toString()) {
startActivity(
Intent(this@AddMemberActivity, MainActivity::class.java).putExtra(
"token",
users.id.toString()
)
)
}
}
error?.let {
Log.e(LoginActivity.TAG, it.message, it)
}
}
}
companion object {
const val TAG = "AddMemberActivity"
}
} | CoupProject/app/src/main/java/com/example/coupproject/view/member/AddMemberActivity.kt | 3384086120 |
package com.example.coupproject.view.dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import com.example.coupproject.databinding.ActivityMainBinding
class ProgressDialog : DialogFragment() {
private lateinit var binding: ActivityMainBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return super.onCreateView(inflater, container, savedInstanceState)
}
} | CoupProject/app/src/main/java/com/example/coupproject/view/dialog/ProgressDialog.kt | 2686704539 |
package com.example.coupproject.view.dialog
import android.os.Build
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.Log
import android.view.ViewGroup
import android.view.WindowInsets
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.example.coupproject.BuildConfig
import com.example.coupproject.R
import com.example.coupproject.databinding.ActivityDialogBinding
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import com.google.firebase.storage.FirebaseStorage
class DialogActivity : AppCompatActivity() {
private lateinit var binding: ActivityDialogBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDialogBinding.bind(layoutInflater.inflate(R.layout.activity_dialog, null))
var width = 0
var height = 0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val windowMetrics = windowManager.currentWindowMetrics
val insets =
windowMetrics.windowInsets.getInsetsIgnoringVisibility(WindowInsets.Type.systemBars())
val navi =
windowMetrics.windowInsets.getInsetsIgnoringVisibility(WindowInsets.Type.systemBars())
width = windowMetrics.bounds.width() - insets.left - insets.right
height = windowMetrics.bounds.height() - navi.top + navi.bottom
} else {
val windowMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(windowMetrics)
width = windowMetrics.widthPixels
height = windowMetrics.heightPixels
}
binding.root.layoutParams = ViewGroup.LayoutParams(width, height)
Log.i(TAG, intent.getStringExtra("fileName").toString())
val reference = FirebaseStorage.getInstance()
.getReferenceFromUrl("${BuildConfig.FIREBASE_URI_KEY}images/${intent.getStringExtra("fileName")}")
// reference.getBytes(1024 * 1024).addOnSuccessListener {
// Log.i(TAG, "$it.")
// }.addOnFailureListener { Log.e(TAG, it.message, it) }
reference.downloadUrl.addOnSuccessListener {
Glide.with(this).load(it).into(binding.dialogImage)
}.addOnFailureListener { Log.e(TAG, it.message, it) }
binding.root.setOnClickListener {
finish()
}
setContentView(binding.root)
}
override fun onDestroy() {
super.onDestroy()
photoDelete()
}
private fun photoDelete() {
val storageRef = FirebaseStorage.getInstance(BuildConfig.FIREBASE_URI_KEY).reference
val riversRef = storageRef.child("images/${intent.getStringExtra("fileName")}")
riversRef.delete().addOnSuccessListener {
Log.i(TAG, "${intent.getStringExtra("fileName")} - delete()")
}.addOnFailureListener { Log.e(TAG, "${intent.getStringExtra("fileName")} - deleteFail()") }
Firebase.database.reference.child(intent.getStringExtra("token").toString())
.removeValue().addOnSuccessListener {
Log.i(TAG, "${intent.getStringExtra("token")} - delete()")
}
}
companion object {
const val TAG = "DialogActivity"
}
} | CoupProject/app/src/main/java/com/example/coupproject/view/dialog/DialogActivity.kt | 1552723022 |
package com.example.coupproject.view
import android.Manifest
import android.app.Application
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.coupproject.BuildConfig
import com.kakao.sdk.common.KakaoSdk
import com.kakao.sdk.common.util.Utility
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class CoupApplication : Application() {
override fun onCreate() {
super.onCreate()
KakaoSdk.init(this, BuildConfig.KAKAO_NATIVE_KEY)
Log.i("CoupApplication", Utility.getKeyHash(this))
}
} | CoupProject/app/src/main/java/com/example/coupproject/view/CoupApplication.kt | 3465439063 |
package com.example.coupproject.view.main
import android.app.ActivityManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.viewModelScope
import com.example.coupproject.BuildConfig
import com.example.coupproject.R
import com.example.coupproject.data.service.CoupService
import com.example.coupproject.databinding.ActivityMainBinding
import com.example.coupproject.domain.model.Photo
import com.example.coupproject.domain.model.User
import com.example.coupproject.viewmodel.MainViewModel
import com.google.firebase.database.ktx.database
import com.google.firebase.database.ktx.getValue
import com.google.firebase.ktx.Firebase
import com.google.firebase.storage.FirebaseStorage
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val viewModel: MainViewModel by viewModels()
private val activityResultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
Log.i(TAG, "성공 ${it.data?.data}")
it.data?.data?.let { photoUri ->
photoUpload(photoUri)
}
}
private val broadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
when (intent?.action) {
"com.example.coup_project.START_COUP_SERVICE" -> binding.btnStartService.text =
"서비스 중지"
"com.example.coup_project.END_COUP_SERVICE" -> binding.btnStartService.text =
"서비스 시작"
}
}
}
private var count = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.bind(layoutInflater.inflate(R.layout.activity_main, null))
binding.activity = this
viewModel.getFriend(intent.getStringExtra("token").toString()) {
val member = it.getValue<User>()
member?.let { user ->
viewModel.saveFriend(user)
}
}
if (isMyServiceRunning(CoupService::class.java)) binding.btnStartService.text =
"서비스 중지" else binding.btnStartService.text = "서비스 시작"
viewModel.viewModelScope.launch {
viewModel.hasMembership.collect { user ->
binding.btnAddFriends.visibility =
if (user.friend?.isNotEmpty() == true) View.GONE else View.VISIBLE
}
}
binding.btnAddFriends.setOnClickListener {
}
val intentFilter = IntentFilter().apply {
addAction("com.example.coup_project.START_COUP_SERVICE")
addAction("com.example.coup_project.END_COUP_SERVICE")
}
registerReceiver(broadcastReceiver, intentFilter)
setContentView(binding.root)
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(broadcastReceiver)
}
private fun isMyServiceRunning(serviceClass: Class<*>): Boolean {
try {
val manager =
getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
for (service in manager.getRunningServices(
Int.MAX_VALUE
)) {
if (serviceClass.name == service.service.className) {
return true
}
}
} catch (e: Exception) {
return false
}
return false
}
override fun onResume() {
super.onResume()
checkPermission()
}
private fun checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
if (count > 0) {
Toast.makeText(this, "다른 앱 위에 표시 권한을 체크해주세요.", Toast.LENGTH_SHORT).show()
finish()
return
}
val intent = Intent(
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:$packageName")
)
startActivity(intent)
count += 1
}
// else {
// startService(Intent(this, CoupService::class.java))
// }
}
// else {
// startService(Intent(this, CoupService::class.java))
// }
}
fun startService() {
val token = intent.getStringExtra("token").toString()
if (token.isNotEmpty()) {
if (isMyServiceRunning(CoupService::class.java)) {
Log.i(TAG, "StopService - CoupService")
stopService(Intent(this, CoupService::class.java).putExtra("token", token))
} else {
Log.i(TAG, "StartService - CoupService")
startService(Intent(this, CoupService::class.java).putExtra("token", token))
}
}
}
private fun photoUpload(uri: Uri) {
val storageRef = FirebaseStorage.getInstance(BuildConfig.FIREBASE_URI_KEY).reference
val sdf = SimpleDateFormat("yyyyMMddhhmmss")
val fileName = "taetaewon1"//sdf.format(Date()) + ".jpg"
val riversRef = storageRef.child("images/$fileName")
riversRef.putFile(uri).addOnProgressListener { taskSnapshot ->
val btf = taskSnapshot.bytesTransferred
val tbc = taskSnapshot.totalByteCount
val progress: Double = 100.0 * btf / tbc
Log.i(TAG, "progress : $progress")
}.addOnFailureListener { Log.e(TAG, "Fail $fileName Upload") }
.addOnSuccessListener {
Log.i(TAG, "Success $fileName Upload")
viewModel.hasMembership.value.friend?.let {
Log.i(TAG, "$it let 진")
Firebase.database.reference.child(it)
.child("photo")
.setValue(
Photo(it, "taetaewon1"),
""
)
}
}
Log.i(TAG, "End $fileName Upload")
}
fun selectPhoto() {
val intent = Intent(Intent.ACTION_GET_CONTENT).apply { type = "image/*" }
activityResultLauncher.launch(intent)
}
companion object {
const val TAG = "MainActivity"
}
} | CoupProject/app/src/main/java/com/example/coupproject/view/main/MainActivity.kt | 11240638 |
package com.example.coupproject.view.login
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.coupproject.R
import com.example.coupproject.databinding.ActivityLoginBinding
import com.example.coupproject.view.main.MainActivity
import com.example.coupproject.view.member.AddMemberActivity
import com.example.coupproject.viewmodel.LoginViewModel
import com.kakao.sdk.user.UserApiClient
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class LoginActivity : AppCompatActivity() {
private lateinit var binding: ActivityLoginBinding
private val viewModel: LoginViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLoginBinding.bind(layoutInflater.inflate(R.layout.activity_login, null))
binding.activity = this
setContentView(binding.root)
}
override fun onResume() {
super.onResume()
binding.progress.visibility = View.VISIBLE
// me()
/** 가상머신테스트용 로그인*/
startActivity(
Intent(this@LoginActivity, MainActivity::class.java).putExtra(
"token",
"1223334444"
)
)
requestPermission()
}
fun logout() {
UserApiClient.instance.logout {
Log.e(TAG, "Kakao Logout")
}
}
fun me() {
UserApiClient.instance.me { user, error ->
user?.let {
viewModel.getMembership { snapshot ->
if (snapshot.hasChild(it.id.toString())) {
startActivity(
Intent(this@LoginActivity, MainActivity::class.java).putExtra(
"token",
it.id.toString()
)
)
}
}
}
error?.let {
Log.e(TAG, it.message, it)
}
}
binding.progress.visibility = View.GONE
}
fun startKakaoLogin() {
viewModel.startKakaoLogin(this) { token, error ->
error?.let {
Toast.makeText(this, "KakaoLogin Fail : ${it.message}", Toast.LENGTH_SHORT)
.show()
}
token?.let {
finish()
Log.i(TAG, "$it")
startActivity(Intent(this, AddMemberActivity::class.java))
} ?: Toast.makeText(this, "Error KakaoLogin", Toast.LENGTH_SHORT).show()
}
}
private fun requestPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && PackageManager.PERMISSION_DENIED == ContextCompat.checkSelfPermission(
this,
Manifest.permission.POST_NOTIFICATIONS
)
) {
// 푸쉬 권한 없음
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.POST_NOTIFICATIONS),
NOTIFICATION_PERMISSION_REQUEST_CODE
)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
NOTIFICATION_PERMISSION_REQUEST_CODE -> {
if (grantResults.isNotEmpty()) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
Toast.makeText(
applicationContext,
"NOTIFICATION_PERMISSION_DENIED",
Toast.LENGTH_SHORT
)
.show()
finish()
}
}
}
else -> ""
}
}
private fun getAccessToken() {
viewModel.getAccessTokenInfo { accessTokenInfo, throwable ->
accessTokenInfo?.let {
startActivity(Intent(this@LoginActivity, MainActivity::class.java))
}
}
}
companion object {
const val TAG = "LoginActivity"
const val NOTIFICATION_PERMISSION_REQUEST_CODE = 1995
}
} | CoupProject/app/src/main/java/com/example/coupproject/view/login/LoginActivity.kt | 4153129970 |
package com.example.coupproject.data.repository
import android.content.Context
import android.util.Log
import com.example.coupproject.domain.model.User
import com.example.coupproject.domain.repository.MainRepository
import com.google.android.gms.tasks.OnSuccessListener
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import javax.inject.Inject
class FirebaseRepositoryImpl @Inject constructor(private val context: Context) :
MainRepository {
override fun getFriend(
memberId: String,
callback: OnSuccessListener<DataSnapshot>
): Flow<Void> {
/**roomDb써서 관리할것*/
return flow {
Firebase.database.reference.child("users").child(memberId).get()
.addOnSuccessListener(callback).addOnFailureListener { Log.e(TAG, it.message, it) }
}
}
override fun getMembership(callback: OnSuccessListener<DataSnapshot>): Flow<Void> {
return flow {
Log.i(TAG, "getMembership start")
Firebase.database.reference.child("users").get().addOnSuccessListener(callback)
.addOnFailureListener {
Log.e(TAG, it.message, it)
}
}
}
override fun setMembership(
name: String,
memberId: String,
callback: OnSuccessListener<Void>
): Flow<Unit> {
return flow {
Firebase.database.reference.child("users").child(memberId)
.setValue(User(name, memberId, null, null))
.addOnSuccessListener(callback)
.addOnFailureListener { Log.e(TAG, it.message, it) }
}
}
override fun checkPermission(): Flow<Unit> {
return flow {
Firebase.database.reference.child("users").setValue(User("이름", "123213213"))
emit(Unit)
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// if (!Settings.canDrawOverlays(context)) {
// val intent = Intent(
// Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
// Uri.parse("package:$packageName")
// )
// }
// }
}
}
companion object {
const val TAG = "MainRepositoryImpl"
}
} | CoupProject/app/src/main/java/com/example/coupproject/data/repository/FirebaseRepositoryImpl.kt | 2347427209 |
package com.example.coupproject.data.repository
import android.content.Context
import com.example.coupproject.domain.repository.KakaoRepository
import com.example.coupproject.view.login.LoginActivity
import com.kakao.sdk.auth.AuthApiClient
import com.kakao.sdk.auth.TokenManagerProvider
import com.kakao.sdk.auth.model.OAuthToken
import com.kakao.sdk.user.UserApiClient
import com.kakao.sdk.user.model.AccessTokenInfo
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import javax.inject.Inject
class KakaoRepositoryImpl @Inject constructor(private val context: Context) :
KakaoRepository {
private val userApiClient: UserApiClient = UserApiClient.instance
private val tokenManagerProvider: TokenManagerProvider = TokenManagerProvider.instance
private val authApiClient = AuthApiClient.instance
override fun startKakaoLogin(
activity: LoginActivity,
callback: (OAuthToken?, Throwable?) -> Unit
): Flow<Void> {
return flow {
if (!userApiClient.isKakaoTalkLoginAvailable(activity)) {
throw IllegalAccessException("KakaoTalk Not Install")
}
userApiClient.loginWithKakaoTalk(activity, callback = callback)
}
}
override fun hasAccessToken(): Flow<Boolean> {
return flow {
// if (authApiClient.hasToken()) {
// emit(true)
// userApiClient.accessTokenInfo(callback)
// } else {
// Log.e(TAG, "authApiClient.hasToken() = false")
// emit(false)
// }
emit(authApiClient.hasToken())
}
}
override fun getAccessTokenInfo(callback: (tokenInfo: AccessTokenInfo?, error: Throwable?) -> Unit): Flow<Unit> {
return flow { userApiClient.accessTokenInfo(callback) }
}
companion object {
const val TAG = "LoginRepositoryImpl"
const val LOGIN_ACCESS_TOKEN = 0
const val LOGOUT_ACCESS_TOKEN = 1
}
} | CoupProject/app/src/main/java/com/example/coupproject/data/repository/KakaoRepositoryImpl.kt | 1067222834 |
package com.example.coupproject.data.service
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import com.example.coupproject.R
import com.example.coupproject.domain.model.Photo
import com.example.coupproject.view.dialog.DialogActivity
import com.google.firebase.database.ChildEventListener
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.ktx.database
import com.google.firebase.database.ktx.getValue
import com.google.firebase.ktx.Firebase
class CoupService : Service() {
private var token = ""
private val addValueListener = object : ChildEventListener {
override fun onChildAdded(snapshot: DataSnapshot, previousChildName: String?) {
Log.i(TAG, "onChildAdded()- ${snapshot.key}//${snapshot.value}")
val photo = snapshot.getValue<Photo>()
startActivity(
Intent(
this@CoupService,
DialogActivity::class.java
).putExtra("token", photo?.token)
.putExtra(
"fileName",
photo?.fileName
)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
)
}
override fun onChildChanged(snapshot: DataSnapshot, previousChildName: String?) {
Log.i(TAG, snapshot.key.toString() + "////")
// startActivity(
// Intent(
// this@CoupService,
// DialogActivity::class.java
// )
// .putExtra(
// "fileName",
// snapshot.getValue<Photo>()?.fileName
// )
// .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
// )
}
override fun onChildRemoved(snapshot: DataSnapshot) {
Log.i(TAG, "onChildRemoved()")
}
override fun onChildMoved(snapshot: DataSnapshot, previousChildName: String?) {
Log.i(TAG, "onChildMoved()")
}
override fun onCancelled(error: DatabaseError) {
Log.e(TAG, error.message, error.toException())
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "name"//getString(R.string.channel_name)
val descriptionText = "descriptionText"//getString(R.string.channel_description)
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel("ServiceStart", name, importance).apply {
description = descriptionText
}
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
val notification = NotificationCompat.Builder(this, "ServiceStart")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("CoupService")
.setContentText("Play CoupService..")
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
token = intent?.let { it.getStringExtra("token") }.toString()
Firebase.database.reference.child(token).addChildEventListener(addValueListener)
sendBroadcast(Intent("com.example.coup_project.START_COUP_SERVICE"))
startForeground(1, notification.build())
return START_NOT_STICKY
}
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onCreate() {
super.onCreate()
}
override fun onDestroy() {
super.onDestroy()
Firebase.database.reference.child(token).removeEventListener(addValueListener)
sendBroadcast(Intent("com.example.coup_project.END_COUP_SERVICE"))
Log.i(TAG, "End CoupService")
}
companion object {
const val TAG = "CoupService"
}
} | CoupProject/app/src/main/java/com/example/coupproject/data/service/CoupService.kt | 4216381101 |
package com.example.coupproject.domain.repository
import com.google.android.gms.tasks.OnSuccessListener
import com.google.firebase.database.DataSnapshot
import kotlinx.coroutines.flow.Flow
interface MainRepository {
fun getFriend(memberId: String,callback: OnSuccessListener<DataSnapshot>): Flow<Void>
fun getMembership(callback: OnSuccessListener<DataSnapshot>): Flow<Void>
fun setMembership(
name: String,
memberId: String,
callback: OnSuccessListener<Void>
): Flow<Unit>
fun checkPermission(): Flow<Unit>
} | CoupProject/app/src/main/java/com/example/coupproject/domain/repository/MainRepository.kt | 1561842366 |
package com.example.coupproject.domain.repository
import com.example.coupproject.view.login.LoginActivity
import com.kakao.sdk.auth.model.OAuthToken
import com.kakao.sdk.user.model.AccessTokenInfo
import kotlinx.coroutines.flow.Flow
interface KakaoRepository {
fun startKakaoLogin(
activity: LoginActivity,
callback: (OAuthToken?, Throwable?) -> Unit
): Flow<Void>
fun hasAccessToken(): Flow<Boolean>
fun getAccessTokenInfo(callback: (tokenInfo: AccessTokenInfo?, error: Throwable?) -> Unit): Flow<Unit>
} | CoupProject/app/src/main/java/com/example/coupproject/domain/repository/KakaoRepository.kt | 2140595178 |
package com.example.coupproject.domain.model
import java.util.Date
data class Photo(
val token: String? = "",
val fileName: String? = "",
val name: String? = null,
val date: Date? = null
)
| CoupProject/app/src/main/java/com/example/coupproject/domain/model/Photo.kt | 2128669428 |
package com.example.coupproject.domain.model
data class User(
val name: String? = null,
val token: String? = null,
val friend: String? = null,
val requestFriend: List<User>? = arrayListOf()
)
| CoupProject/app/src/main/java/com/example/coupproject/domain/model/User.kt | 4213644129 |
package com.example.coupproject.domain.model
data class Friend(val name: String, val id: String)
| CoupProject/app/src/main/java/com/example/coupproject/domain/model/Friend.kt | 475833182 |
package com.example.coupproject.domain.usecase.main
import com.example.coupproject.domain.repository.MainRepository
import javax.inject.Inject
class CheckPermissionUseCase @Inject constructor(private val repository: MainRepository) {
operator fun invoke() = repository.checkPermission()
} | CoupProject/app/src/main/java/com/example/coupproject/domain/usecase/main/CheckPermissionUseCase.kt | 3897966434 |
package com.example.coupproject.domain.usecase.main
import com.example.coupproject.domain.repository.MainRepository
import com.google.android.gms.tasks.OnSuccessListener
import com.google.firebase.database.DataSnapshot
import javax.inject.Inject
class GetFriendUseCase @Inject constructor(private val repository: MainRepository) {
operator fun invoke(memberId: String, callback: OnSuccessListener<DataSnapshot>) =
repository.getFriend(memberId, callback)
} | CoupProject/app/src/main/java/com/example/coupproject/domain/usecase/main/GetFriendUseCase.kt | 4245096086 |
package com.example.coupproject.domain.usecase.main
import com.example.coupproject.domain.repository.MainRepository
import com.google.android.gms.tasks.OnSuccessListener
import javax.inject.Inject
class SetMembershipUseCase @Inject constructor(private val repository: MainRepository) {
operator fun invoke(name: String, memberId: String, callback: OnSuccessListener<Void>) =
repository.setMembership(name, memberId, callback)
} | CoupProject/app/src/main/java/com/example/coupproject/domain/usecase/main/SetMembershipUseCase.kt | 2170075584 |
package com.example.coupproject.domain.usecase.main
import com.example.coupproject.domain.repository.MainRepository
import com.google.android.gms.tasks.OnSuccessListener
import com.google.firebase.database.DataSnapshot
import javax.inject.Inject
class GetMembershipUseCase @Inject constructor(private val repository: MainRepository) {
operator fun invoke(callback: OnSuccessListener<DataSnapshot>) =
repository.getMembership(callback)
} | CoupProject/app/src/main/java/com/example/coupproject/domain/usecase/main/GetMembershipUseCase.kt | 3450353332 |
package com.example.coupproject.domain.usecase.login
import com.example.coupproject.domain.repository.KakaoRepository
import com.example.coupproject.view.login.LoginActivity
import com.kakao.sdk.auth.model.OAuthToken
import javax.inject.Inject
class StartKakaoLoginUseCase @Inject constructor(private val repository: KakaoRepository) {
operator fun invoke(
activity: LoginActivity,
callback: (OAuthToken?, Throwable?) -> Unit
) = repository.startKakaoLogin(activity, callback)
} | CoupProject/app/src/main/java/com/example/coupproject/domain/usecase/login/StartKakaoLoginUseCase.kt | 1485340983 |
package com.example.coupproject.domain.usecase.login
import com.example.coupproject.domain.repository.KakaoRepository
import com.kakao.sdk.user.model.AccessTokenInfo
import javax.inject.Inject
class GetAccessTokenInfoUseCase @Inject constructor(private val repository: KakaoRepository) {
operator fun invoke(callback: (AccessTokenInfo?, Throwable?) -> Unit) =
repository.getAccessTokenInfo(callback)
} | CoupProject/app/src/main/java/com/example/coupproject/domain/usecase/login/GetAccessTokenInfoUseCase.kt | 1001297834 |
package com.example.coupproject.domain.usecase.login
import com.example.coupproject.domain.repository.KakaoRepository
import javax.inject.Inject
class HasAccessTokenUseCase @Inject constructor(private val repository: KakaoRepository) {
operator fun invoke() = repository.hasAccessToken()
} | CoupProject/app/src/main/java/com/example/coupproject/domain/usecase/login/HasAccessTokenUseCase.kt | 1254325496 |
package com.example.myapplication
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.myapplication", appContext.packageName)
}
} | jb1/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt | 1188990709 |
package com.example.myapplication
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | jb1/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt | 2019423820 |
package com.example.myapplication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.hallo_word)
val nameEditText: EditText = findViewById(R.id.NameEditText)
val buttonButton: Button = findViewById(R.id.buttonButton)
val buttonTextView: TextView = findViewById(R.id.buttonTextView)
buttonTextView.text = "Halo"
buttonButton.setOnClickListener{
val name = nameEditText.text.toString()
buttonTextView.text = "Halo $name"
}
}
} | jb1/app/src/main/java/com/example/myapplication/MainActivity.kt | 1643621873 |
package de.fruiture.cor.ccs
import de.fruiture.cor.ccs.cc.Type
import de.fruiture.cor.ccs.git.*
import de.fruiture.cor.ccs.git.VersionTag.Companion.versionTag
import de.fruiture.cor.ccs.semver.AlphaNumericIdentifier.Companion.alphanumeric
import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy.Companion.counter
import de.fruiture.cor.ccs.semver.Version.Companion.version
import io.kotest.matchers.shouldBe
import io.mockk.every
import io.mockk.mockk
import kotlin.test.Test
class CCSApplicationTest {
private val oneFeatureAfterMajorRelease = mockk<Git>().apply {
every { getLatestVersionTag() } returns versionTag("1.0.0")
every { getLatestReleaseTag() } returns versionTag("1.0.0")
every { getLogX(from = TagName("1.0.0")) } returns listOf(
GitCommit("cafebabe", ZonedDateTime("2001-01-01T13:00Z"), "feat: a feature is born")
)
}
private val noReleaseYet = mockk<Git>().apply {
every { getLatestVersionTag() } returns null
every { getLatestReleaseTag() } returns null
every { getLogX(from = null) } returns listOf(
GitCommit("cafebabe", ZonedDateTime("2001-01-01T13:00Z"), "feat: a feature is born")
)
}
private val hadABreakingChangeAfterSnapshot = mockk<Git>().apply {
every { getLatestVersionTag() } returns versionTag("1.2.3-SNAPSHOT.5")
every { getLogX(from = TagName("1.2.3-SNAPSHOT.5")) } returns listOf(
GitCommit("cafebabe", ZonedDateTime("2001-01-01T13:00Z"), "feat!: a feature with a breaking change")
)
}
private val afterMultipleReleases = mockk<Git>().apply {
every { getLatestVersionTag(before(version("1.0.0"))) } returns versionTag("1.0.0-RC.3")
every { getLatestReleaseTag(before(version("1.0.0"))) } returns versionTag("vers0.3.7")
every { getLatestVersionTag(until(version("1.0.0"))) } returns versionTag("v1.0.0")
every { getLogX(from = TagName("vers0.3.7"), to = TagName("v1.0.0")) } returns listOf(
GitCommit("cafebabe", ZonedDateTime("2001-01-01T13:00Z"), "feat: range change")
)
}
private val mixedBagOfCommits = mockk<Git>().apply {
every { getLatestVersionTag() } returns versionTag("1.0.0")
every { getLogX(from = TagName("1.0.0")) } returns listOf(
GitCommit("0001", ZonedDateTime("2001-01-01T13:01Z"), "feat: feature1"),
GitCommit("002", ZonedDateTime("2001-01-01T13:02Z"), "fix: fix2"),
GitCommit("003", ZonedDateTime("2001-01-01T13:03Z"), "perf: perf3"),
GitCommit("004", ZonedDateTime("2001-01-01T13:04Z"), "none4")
)
}
@Test
fun `get next release version`() {
CCSApplication(oneFeatureAfterMajorRelease).getNextRelease() shouldBe version("1.1.0")
}
@Test
fun `get next pre-release version`() {
CCSApplication(oneFeatureAfterMajorRelease).getNextPreRelease(counter()) shouldBe version("1.1.0-RC.1")
CCSApplication(oneFeatureAfterMajorRelease).getNextPreRelease(counter("alpha".alphanumeric)) shouldBe version("1.1.0-alpha.1")
}
@Test
fun `get initial release or snapshot`() {
CCSApplication(noReleaseYet).getNextRelease() shouldBe version("0.0.1")
CCSApplication(noReleaseYet).getNextPreRelease(counter("RC".alphanumeric)) shouldBe version("0.0.1-RC.1")
CCSApplication(noReleaseYet).getNextPreRelease(counter()) shouldBe version("0.0.1-RC.1")
}
@Test
fun `get change log`() {
CCSApplication(oneFeatureAfterMajorRelease).getChangeLogJson() shouldBe
"""[{"hash":"cafebabe","date":"2001-01-01T13:00Z","message":"feat: a feature is born",""" +
""""conventional":{"type":"feat","description":"a feature is born"}}]"""
CCSApplication(noReleaseYet).getChangeLogJson() shouldBe
"""[{"hash":"cafebabe","date":"2001-01-01T13:00Z","message":"feat: a feature is born",""" +
""""conventional":{"type":"feat","description":"a feature is born"}}]"""
}
@Test
fun `get change log before a certain version`() {
CCSApplication(afterMultipleReleases).getChangeLogJson(release = true, before = version("1.0.0")) shouldBe
"""[{"hash":"cafebabe","date":"2001-01-01T13:00Z","message":"feat: range change",""" +
""""conventional":{"type":"feat","description":"range change"}}]"""
}
@Test
fun `breaking change is recognized`() {
CCSApplication(hadABreakingChangeAfterSnapshot).getNextRelease() shouldBe version("2.0.0")
CCSApplication(hadABreakingChangeAfterSnapshot).getNextPreRelease(counter()) shouldBe version("2.0.0-RC.1")
}
@Test
fun `get latest release`() {
CCSApplication(oneFeatureAfterMajorRelease).getLatestVersion(true) shouldBe "1.0.0"
CCSApplication(noReleaseYet).getLatestVersion(true) shouldBe null
}
@Test
fun `get latest version`() {
CCSApplication(hadABreakingChangeAfterSnapshot).getLatestVersion() shouldBe "1.2.3-SNAPSHOT.5"
}
@Test
fun `get latest version before another version`() {
CCSApplication(afterMultipleReleases).getLatestVersion(before = version("1.0.0")) shouldBe "1.0.0-RC.3"
CCSApplication(afterMultipleReleases).getLatestVersion(
release = true,
before = version("1.0.0")
) shouldBe "0.3.7"
}
@Test
fun `get markdown`() {
CCSApplication(oneFeatureAfterMajorRelease).getChangeLogMarkdown(
release = false,
sections = Sections(mapOf("Neue Funktionen" to setOf(Type("feat"))))
) shouldBe """
## Neue Funktionen
* a feature is born
""".trimIndent()
}
@Test
fun `get markdown with breaking changes`() {
CCSApplication(hadABreakingChangeAfterSnapshot).getChangeLogMarkdown(
release = false,
sections = Sections().setBreakingChanges("API broken")
) shouldBe """
## API broken
* a feature with a breaking change
""".trimIndent()
}
@Test
fun `summarize various types`() {
CCSApplication(mixedBagOfCommits).getChangeLogMarkdown() shouldBe """
## Features
* feature1
## Bugfixes
* fix2
## Other
* perf3
* none4
""".trimIndent()
}
} | git-ccs/src/jvmTest/kotlin/de/fruiture/cor/ccs/CCSApplicationTest.kt | 2318356779 |
package de.fruiture.cor.ccs
import VERSION
import com.github.ajalt.clikt.testing.test
import de.fruiture.cor.ccs.cc.Type
import de.fruiture.cor.ccs.semver.AlphaNumericIdentifier.Companion.alphanumeric
import de.fruiture.cor.ccs.semver.ChangeType
import de.fruiture.cor.ccs.semver.PreRelease
import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy.Companion.counter
import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy.Companion.plus
import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy.Companion.static
import de.fruiture.cor.ccs.semver.Release
import de.fruiture.cor.ccs.semver.Version.Companion.version
import io.kotest.matchers.shouldBe
import io.kotest.matchers.string.shouldStartWith
import io.mockk.called
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import kotlin.test.Test
class CLITest {
private val app = mockk<CCSApplication>(relaxed = true)
private val cli = CLI(app)
init {
every { app.getNextRelease() } returns version("1.2.3") as Release
every { app.getNextPreRelease(counter()) } returns version("1.2.3-RC.5") as PreRelease
}
@Test
fun `next release`() {
cli.test("next release").output shouldBe "1.2.3"
verify { app.getNextRelease() }
}
@Test
fun `next pre-release`() {
cli.test("next pre-release").output shouldBe "1.2.3-RC.5"
verify { app.getNextPreRelease(counter()) }
}
@Test
fun `next pre-release custom`() {
every { app.getNextPreRelease(counter("alpha".alphanumeric)) } returns version("1.2.3-alpha.5") as PreRelease
cli.test("next pre-release -f alpha.1").output shouldBe "1.2.3-alpha.5"
}
@Test
fun `combined counter and static strategy`() {
every {
app.getNextPreRelease(
counter("alpha".alphanumeric) + static("snap".alphanumeric)
)
} returns version("1.2.3-alpha.1.snap") as PreRelease
cli.test("next pre-release -f alpha.1.snap").output shouldBe "1.2.3-alpha.1.snap"
}
@Test
fun `show help`() {
cli.test("next --help").output shouldStartWith """
Usage: git-ccs next [<options>] <command> [<args>]...
compute the next semantic version based on changes since the last version tag
""".trimIndent()
verify { app wasNot called }
}
@Test
fun `show help when nothing`() {
cli.test("").output shouldStartWith "Usage: git-ccs"
}
@Test
fun `illegal command`() {
cli.test("nope").stderr shouldBe """
Usage: git-ccs [<options>] <command> [<args>]...
Error: no such subcommand nope
""".trimIndent()
verify { app wasNot called }
}
@Test
fun `allow non-bumps`() {
every {
app.getNextRelease(
ChangeMapping() + (Type("default") to ChangeType.NONE)
)
} returns version("1.1.1") as Release
cli.test("next release -n default").output shouldBe "1.1.1"
}
@Test
fun `get latest release tag`() {
every {
app.getLatestVersion(true)
} returns "0.2.3"
cli.test("latest -r").output shouldBe "0.2.3"
}
@Test
fun `get latest release fails if no release yet`() {
every {
app.getLatestVersion(true)
} returns null
val result = cli.test("latest -r")
result.statusCode shouldBe 1
result.stderr shouldBe "no version found\n"
}
@Test
fun `get latest version tag`() {
every { app.getLatestVersion() } returns "0.2.3-SNAP"
cli.test("latest").output shouldBe "0.2.3-SNAP"
}
@Test
fun `get latest -t`() {
every { app.getLatestVersion(before = version("1.0.0")) } returns "1.0.0-RC.5"
cli.test("latest -t 1.0.0").output shouldBe "1.0.0-RC.5"
}
@Test
fun `get log since release`() {
every { app.getChangeLogJson(true) } returns "[{json}]"
cli.test("log --release").output shouldBe "[{json}]"
}
@Test
fun `log -t`() {
every { app.getChangeLogJson(true, before = version("1.0.0")) } returns "[{json}]"
cli.test("log --release --target 1.0.0").output shouldBe "[{json}]"
}
@Test
fun `get markdown`() {
every { app.getChangeLogMarkdown(false) } returns "*markdown*"
cli.test("changes").output shouldBe "*markdown*"
}
@Test
fun `changes -t`() {
every { app.getChangeLogMarkdown(true, target = version("1.0.0")) } returns
"*markdown of changes leading to 1.0.0"
cli.test("changes -rt 1.0.0").output shouldBe "*markdown of changes leading to 1.0.0"
}
@Test
fun `markdown with custom headings`() {
every {
app.getChangeLogMarkdown(
release = false,
sections = Sections(mapOf("Fun" to setOf(Type("feat")))),
level = 1
)
} returns "# Fun"
cli.test("changes -s 'Fun=feat' -l 1").output shouldBe "# Fun"
}
@Test
fun `show version`() {
cli.test("--version").output shouldBe "git-ccs version $VERSION\n"
}
} | git-ccs/src/jvmTest/kotlin/de/fruiture/cor/ccs/CLITest.kt | 1922482177 |
package de.fruiture.cor.ccs
import de.fruiture.cor.ccs.cc.Type
import de.fruiture.cor.ccs.git.GitCommit
import de.fruiture.cor.ccs.git.NON_CONVENTIONAL_COMMIT_TYPE
import de.fruiture.cor.ccs.git.ZonedDateTime
import de.fruiture.cor.ccs.semver.ChangeType
import io.kotest.matchers.shouldBe
import kotlin.test.Test
class ChangeMappingTest {
private val mapping = ChangeMapping()
@Test
fun `default mapping`() {
mapping.of(Type("feat")) shouldBe ChangeType.MINOR
mapping.of(NON_CONVENTIONAL_COMMIT_TYPE) shouldBe ChangeType.PATCH
mapping.of(DEFAULT_COMMIT_TYPE) shouldBe ChangeType.PATCH
}
@Test
fun `commit mapping`() {
mapping.of(
GitCommit("cafe", ZonedDateTime("2001-01-01T12:00:00Z"), "perf!: break API for speed")
) shouldBe ChangeType.MAJOR
mapping.of(
GitCommit("cafe", ZonedDateTime("2001-01-01T12:00:00Z"), "perf: break API for speed")
) shouldBe ChangeType.PATCH
}
@Test
fun `adjust mapping to none-bump`() {
val adjusted = mapping + (DEFAULT_COMMIT_TYPE to ChangeType.NONE)
adjusted.of(Type("doc")) shouldBe ChangeType.NONE
}
} | git-ccs/src/jvmTest/kotlin/de/fruiture/cor/ccs/ChangeMappingTest.kt | 1632591763 |
package de.fruiture.cor.ccs.semver
import de.fruiture.cor.ccs.semver.AlphaNumericIdentifier.Companion.alphanumeric
import de.fruiture.cor.ccs.semver.DigitIdentifier.Companion.digits
import de.fruiture.cor.ccs.semver.NumericIdentifier.Companion.numeric
import de.fruiture.cor.ccs.semver.Version.Companion.version
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.matchers.shouldBe
import kotlin.test.Test
class VersionTest {
@Test
fun `represent version cores`() {
VersionCore.of(
major = 1, minor = 0, patch = 0
).toString() shouldBe "1.0.0"
}
@Test
fun `represent pre-release`() {
PreReleaseIndicator(
listOf(
PreReleaseIdentifier.identifier("alpha".alphanumeric), PreReleaseIdentifier.identifier(26.numeric)
)
).toString() shouldBe "alpha.26"
}
@Test
fun `compare release versions`() {
val v100 = Release(VersionCore.of(1, 0, 0))
val v101 = Release(VersionCore.of(1, 0, 1))
v100.compareTo(v101) shouldBe -1
v101.compareTo(v100) shouldBe 1
}
@Test
fun `compare pre-release versions with releases`() {
val v100Alpha = PreRelease(
VersionCore.of(1, 0, 0),
PreReleaseIndicator.of(
PreReleaseIdentifier.identifier("alpha".alphanumeric)
)
)
val v100 = Release(VersionCore.of(1, 0, 0))
val v001 = Release(VersionCore.of(0, 0, 1))
v100Alpha.compareTo(v100) shouldBe -1
v100.compareTo(v100Alpha) shouldBe 1
v100Alpha.compareTo(v001) shouldBe 1
v001.compareTo(v100Alpha) shouldBe -1
}
@Test
fun `compare pre-releases`() {
val alpha = PreRelease(
VersionCore.of(1, 0, 0),
PreReleaseIndicator.of(
PreReleaseIdentifier.identifier("alpha".alphanumeric)
)
)
val beta = PreRelease(
VersionCore.of(1, 0, 0),
PreReleaseIndicator.of(
PreReleaseIdentifier.identifier("beta".alphanumeric)
)
)
val betaPlus = PreRelease(
VersionCore.of(1, 0, 0),
PreReleaseIndicator.of(
PreReleaseIdentifier.identifier("beta".alphanumeric),
PreReleaseIdentifier.identifier("plus".alphanumeric)
)
)
alpha.compareTo(beta) shouldBe -1
beta.compareTo(alpha) shouldBe 1
beta.compareTo(betaPlus) shouldBe -1
}
@Test
fun `allow build identifiers`() {
Release(
VersionCore.of(2, 1, 3),
Build(
listOf(
BuildIdentifier.identifier("build".alphanumeric),
BuildIdentifier.identifier("000".digits)
)
)
).toString() shouldBe "2.1.3+build.000"
PreRelease(
VersionCore.of(2, 1, 3),
PreReleaseIndicator.of(
PreReleaseIdentifier.identifier("alpha".alphanumeric)
),
Build(
listOf(
BuildIdentifier.identifier("build".alphanumeric),
BuildIdentifier.identifier("000".digits)
)
)
).toString() shouldBe "2.1.3-alpha+build.000"
}
@Test
fun `version strings`() {
Release(VersionCore.of(1, 2, 3)).toString() shouldBe "1.2.3"
PreRelease(
VersionCore.of(1, 2, 3),
PreReleaseIndicator.of(
PreReleaseIdentifier.identifier("alpha".alphanumeric)
)
).toString() shouldBe "1.2.3-alpha"
}
@Test
fun `valid alphanumeric identifiers`() {
AlphaNumericIdentifier("foo")
AlphaNumericIdentifier("foo-bar")
shouldThrow<IllegalArgumentException> {
AlphaNumericIdentifier("0000")
}
AlphaNumericIdentifier("0000a")
}
@Test
fun `parsing versions`() {
version("1.2.3") shouldBe Release(VersionCore.of(1, 2, 3))
version("1.2.3+x23.005") shouldBe Release(
VersionCore.of(1, 2, 3),
Build(listOf(BuildIdentifier.identifier("x23".alphanumeric), BuildIdentifier.identifier("005".digits)))
)
version("1.2.3-alpha.7.go-go+x23.005") shouldBe PreRelease(
VersionCore.of(1, 2, 3),
PreReleaseIndicator(
listOf(
PreReleaseIdentifier.identifier("alpha".alphanumeric),
PreReleaseIdentifier.identifier(7.numeric),
PreReleaseIdentifier.identifier("go-go".alphanumeric)
)
),
Build(listOf(BuildIdentifier.identifier("x23".alphanumeric), BuildIdentifier.identifier("005".digits)))
)
version("1.2.3-alpha.7.go-go") shouldBe PreRelease(
VersionCore.of(1, 2, 3),
PreReleaseIndicator(
listOf(
PreReleaseIdentifier.identifier("alpha".alphanumeric),
PreReleaseIdentifier.identifier(7.numeric),
PreReleaseIdentifier.identifier("go-go".alphanumeric)
)
)
)
}
@Test
fun `extracting version out of strings`() {
Version.extractVersion("v1.2.3") shouldBe version("1.2.3")
Version.extractVersion("version:2.1.0-SNAPSHOT.2") shouldBe version("2.1.0-SNAPSHOT.2")
Version.extractVersion("1.3.9 other stuff") shouldBe version("1.3.9")
Version.extractVersion("1.2prefix1.3.9-RC.7/suffix") shouldBe version("1.3.9-RC.7")
}
}
| git-ccs/src/jvmTest/kotlin/de/fruiture/cor/ccs/semver/VersionTest.kt | 2444821065 |
package de.fruiture.cor.ccs.semver
import de.fruiture.cor.ccs.semver.AlphaNumericIdentifier.Companion.alphanumeric
import de.fruiture.cor.ccs.semver.Build.Companion.build
import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Companion.preRelease
import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy.Companion.counter
import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy.Companion.plus
import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy.Companion.static
import de.fruiture.cor.ccs.semver.Version.Companion.version
import io.kotest.matchers.shouldBe
import kotlin.test.Test
class VersionUsageTest {
@Test
fun `special releases`() {
Version.initial shouldBe version("0.0.1")
Version.stable shouldBe version("1.0.0")
}
@Test
fun `bumping releases`() {
version("1.0.0").next(ChangeType.MINOR) shouldBe version("1.1.0")
version("1.0.0").next(ChangeType.PATCH) shouldBe version("1.0.1")
version("1.0.0").next(ChangeType.MAJOR) shouldBe version("2.0.0")
version("2.3.25").next(ChangeType.PATCH) shouldBe version("2.3.26")
version("2.3.25").next(ChangeType.MINOR) shouldBe version("2.4.0")
version("2.3.25").next(ChangeType.MAJOR) shouldBe version("3.0.0")
version("2.3.25").next(ChangeType.NONE) shouldBe version("2.3.25")
}
@Test
fun `bumping pre-releases drops pre-release but may not bump release`() {
version("1.0.7-rc.1").next(ChangeType.MAJOR) shouldBe version("2.0.0")
version("1.0.7-rc.1").next(ChangeType.MINOR) shouldBe version("1.1.0")
version("1.0.7-rc.1").next(ChangeType.PATCH) shouldBe version("1.0.7")
version("2.3.0-rc.1").next(ChangeType.MAJOR) shouldBe version("3.0.0")
version("2.3.0-rc.1").next(ChangeType.MINOR) shouldBe version("2.3.0")
version("2.3.0-rc.1").next(ChangeType.PATCH) shouldBe version("2.3.0")
version("3.0.0-rc.1").next(ChangeType.MAJOR) shouldBe version("3.0.0")
version("3.0.0-rc.1").next(ChangeType.MINOR) shouldBe version("3.0.0")
version("3.0.0-rc.1").next(ChangeType.PATCH) shouldBe version("3.0.0")
version("1.0.7-rc.1").next(ChangeType.NONE) shouldBe version("1.0.7")
}
@Test
fun `bumping any releases drops build metadata`() {
version("1.0.7-rc.1+commit").next(ChangeType.PATCH) shouldBe version("1.0.7")
version("1.0.7-rc.1+commit").next(ChangeType.MAJOR) shouldBe version("2.0.0")
version("1.0.7+commit").next(ChangeType.MAJOR) shouldBe version("2.0.0")
version("1.0.7+commit").next(ChangeType.PATCH) shouldBe version("1.0.8")
}
@Test
fun `attach pre-release and build metadata`() {
version("1.2.3-snapshot").release shouldBe version("1.2.3")
version("3.2.0").release.preRelease("rc.1") shouldBe version("3.2.0-rc.1")
version("3.2.0").build("job.267") shouldBe version("3.2.0+job.267")
version("3.2.0+job.123").build("job.267") shouldBe version("3.2.0+job.267")
version("4.0.99-RC.1").build("job.008") shouldBe version("4.0.99-RC.1+job.008")
}
@Test
fun `more sugar - append arbitrary pre-release and build metadata`() {
version("1.2.3") + preRelease("RC.5") shouldBe version("1.2.3-RC.5")
version("1.2.3-RC.3") + preRelease("RC.5") shouldBe version("1.2.3-RC.3.RC.5")
version("1.2.3+cafe") + preRelease("RC.5") shouldBe version("1.2.3-RC.5+cafe")
version("1.2.3-alpha+cafe") + preRelease("RC.5") shouldBe version("1.2.3-alpha.RC.5+cafe")
version("1.2.3") + build("c1f2e3") shouldBe version("1.2.3+c1f2e3")
version("1.2.3-pre") + build("c1f2e3") shouldBe version("1.2.3-pre+c1f2e3")
version("1.2.3-pre+cafe") + build("c1f2e3") shouldBe version("1.2.3-pre+cafe.c1f2e3")
}
@Test
fun `bump pre-release only`() {
version("1.2.3-rc.1").nextPreRelease(counter("rc".alphanumeric)) shouldBe version("1.2.3-rc.2")
version("1.2.3-rc").nextPreRelease(counter("rc".alphanumeric)) shouldBe version("1.2.3-rc.2")
version("1.2.3").nextPreRelease() shouldBe version("1.2.3-RC.1")
version("1.2.3").nextPreRelease(counter("RC".alphanumeric)) shouldBe version("1.2.3-RC.1")
val alpha = counter("alpha".alphanumeric)
version("1.2.3-beta").nextPreRelease(alpha) shouldBe version("1.2.3-beta.alpha.1")
version("1.2.3-alpha").nextPreRelease(alpha) shouldBe version("1.2.3-alpha.2")
version("1.2.3-alpha.7").nextPreRelease(alpha) shouldBe version("1.2.3-alpha.8")
version("1.2.3").nextPreRelease(alpha) shouldBe version("1.2.3-alpha.1")
version("1.2.3-alpha.7.junk").nextPreRelease(alpha) shouldBe version("1.2.3-alpha.8.junk")
}
@Test
fun `static pre-releases`() {
version("1.2.3").nextPreRelease(static()) shouldBe version("1.2.3-SNAPSHOT")
version("1.2.3").nextPreRelease(ChangeType.MINOR, static()) shouldBe version("1.3.0-SNAPSHOT")
version("1.2.3-SNAPSHOT").nextPreRelease(ChangeType.PATCH, static()) shouldBe version("1.2.3-SNAPSHOT")
version("1.2.3").nextPreRelease(ChangeType.PATCH, static("foo".alphanumeric)) shouldBe version("1.2.4-foo")
}
@Test
fun `pre release strategy`() {
val lastRelease = version("1.2.3") as Release
val lastPreRelease = version("1.2.4-RC.1") as PreRelease
lastRelease.next(ChangeType.PATCH).nextPreRelease() shouldBe lastPreRelease
lastRelease.nextPreRelease(ChangeType.PATCH) shouldBe lastPreRelease
lastPreRelease.nextPreRelease(ChangeType.NONE) shouldBe version("1.2.4-RC.2")
lastPreRelease.nextPreRelease(ChangeType.PATCH) shouldBe version("1.2.4-RC.2")
lastPreRelease.nextPreRelease(ChangeType.MINOR) shouldBe version("1.3.0-RC.1")
lastPreRelease.nextPreRelease(ChangeType.MAJOR) shouldBe version("2.0.0-RC.1")
(version("2.0.0-RC.1") as PreRelease).nextPreRelease(ChangeType.PATCH) shouldBe
version("2.0.0-RC.2")
}
@Test
fun `counter pre-releases with static suffix`() {
val strategy = counter("RC".alphanumeric) + static("SNAPSHOT".alphanumeric)
val inverse = static("SNAPSHOT".alphanumeric) + counter("RC".alphanumeric)
version("1.2.3").nextPreRelease(ChangeType.PATCH, strategy) shouldBe version("1.2.4-RC.1.SNAPSHOT")
version("1.2.3").nextPreRelease(ChangeType.PATCH, inverse) shouldBe version("1.2.4-SNAPSHOT.RC.1")
version("1.2.4-RC.1.SNAPSHOT").nextPreRelease(ChangeType.PATCH, strategy) shouldBe
version("1.2.4-RC.2.SNAPSHOT")
}
} | git-ccs/src/jvmTest/kotlin/de/fruiture/cor/ccs/semver/VersionUsageTest.kt | 3110317512 |
package de.fruiture.cor.ccs.cc
import de.fruiture.cor.ccs.cc.ConventionalCommitMessage.Companion.message
import io.kotest.matchers.shouldBe
import kotlin.test.Test
class ConventionalCommitMessageTest {
@Test
fun `parse a conventional commit`() {
val msg = message("docs: correct spelling of CHANGELOG")
msg.type shouldBe Type("docs")
msg.description shouldBe Description("correct spelling of CHANGELOG")
msg.scope shouldBe null
}
@Test
fun `parse with scope`() {
val msg = message("fix(parser): support scopes")
msg.type shouldBe Type("fix")
msg.scope shouldBe Scope("parser")
}
@Test
fun `parse with body`() {
val msg = message(
"""
fix: prevent racing of requests
Introduce a request id and a reference to latest request. Dismiss
incoming responses other than from latest request.
""".trimIndent()
)
msg.type shouldBe Type("fix")
msg.description shouldBe Description("prevent racing of requests")
msg.body shouldBe Body("Introduce a request id and a reference to latest request. Dismiss\nincoming responses other than from latest request.")
}
@Test
fun `multi-paragraph body`() {
message(
"""
fix: prevent racing of requests
Introduce a request id and a reference to latest request. Dismiss
incoming responses other than from latest request.
Remove timeouts which were used to mitigate the racing issue but are
obsolete now.
""".trimIndent()
).body shouldBe Body(
"""
Introduce a request id and a reference to latest request. Dismiss
incoming responses other than from latest request.
Remove timeouts which were used to mitigate the racing issue but are
obsolete now.
""".trimIndent()
)
}
@Test
fun `breaking change in headline`() {
message("fix!: bugfix breaks API").breakingChange shouldBe "bugfix breaks API"
}
@Test
fun `breaking change in the footer (and useless newlines)`() {
message(
"""
feat: cool stuff
BREAKING CHANGE: but the api changes
BREAKING CHANGE: but the api changes
""".trimIndent()
).breakingChange shouldBe "but the api changes"
}
@Test
fun `breaking change in the footer after body`() {
val msg = message(
"""
feat: cool stuff
Paragraph1
Paragraph2
BREAKING CHANGE: but the api changes
""".trimIndent()
)
msg.breakingChange shouldBe "but the api changes"
msg.body shouldBe Body(
"""
Paragraph1
Paragraph2
""".trimIndent()
)
}
@Test
fun footers() {
val msg = message(
"""
fun: Fun
Done-By: Me
BREAKING CHANGE: Me too
""".trimIndent()
)
msg.breakingChange shouldBe "Me too"
msg.footers shouldBe listOf(
GenericFooter("Done-By", "Me"),
BreakingChange("Me too")
)
}
@Test
fun `convert to string`() {
ConventionalCommitMessage(
type = Type("feat"),
description = Description("some text"),
scope = Scope("test")
).toString() shouldBe "feat(test): some text"
}
@Test
fun `all aspects in and out`() {
message(
"""
fun(fun)!: Fun
Fun Fun Fun!
More Fun
Done-By: Me
BREAKING-CHANGE: Me too
""".trimIndent()
).toString() shouldBe """
fun(fun)!: Fun
Fun Fun Fun!
More Fun
Done-By: Me
BREAKING-CHANGE: Me too
""".trimIndent()
}
} | git-ccs/src/jvmTest/kotlin/de/fruiture/cor/ccs/cc/ConventionalCommitMessageTest.kt | 1941636800 |
package de.fruiture.cor.ccs.git
import io.kotest.matchers.shouldBe
import io.kotest.matchers.string.shouldContain
import kotlin.test.Test
class KommandSystemCallerTest {
private val caller = KommandSystemCaller()
@Test
fun `invoke git -v`() {
val result = caller.call("git", listOf("-v"))
result.code shouldBe 0
result.stderr shouldBe emptyList()
result.stdout.first() shouldContain Regex("^git version")
}
@Test
fun `invoke git -invalid-option`() {
val result = caller.call("git", listOf("-invalid-option"))
result.code shouldBe 129
result.stderr.first() shouldBe "unknown option: -invalid-option"
}
} | git-ccs/src/jvmTest/kotlin/de/fruiture/cor/ccs/git/KommandSystemCallerTest.kt | 2054064752 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.