path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
proyectoDog/app/src/main/java/com/john/proyectodog/data/models/Dog.kt
3729831901
package com.john.proyectodog.data.models data class Dog( val name: String, val image: String ) { override fun toString(): String { return "Dog(name='$name', image='$image')" } }
proyectoDog/app/src/main/java/com/john/proyectodog/data/models/DogRepositoryInterfaceDao.kt
1083639443
package com.john.proyectodog.data.models interface DogRepositoryInterfaceDao { fun getDogs() : List<Dog> fun getBreedDogs (breed:String) : List<Dog> }
proyectoDog/app/src/main/java/com/john/proyectodog/data/models/Repository.kt
3401952136
package com.john.proyectodog.data.models class Repository { companion object { var dogs:List<Dog> = emptyList() } }
proyectoDog/app/src/main/java/com/john/proyectodog/data/models/DogRepositoryDao.kt
2875042108
package com.john.proyectodog.data.models import com.john.proyectodog.data.service.DogService class DogRepositoryDao : DogRepositoryInterfaceDao { companion object { val myDogRepositoryDao: DogRepositoryDao by lazy{ //lazy delega a un primer acceso DogRepositoryDao() //Me creo sólo este objeto una vez. } } /* Método que a partir de los datos nativos, devuelve la lista de objetos que necesita el modelo. */ override fun getDogs(): List<Dog> { var mutableDogs : MutableList <Dog> = mutableListOf() val dataSource = DogService.service.getDogs() dataSource .forEach{ dog-> mutableDogs .add(Dog(dog. first, dog.second)) } Repository .dogs = mutableDogs //AQUÍ CARGO LOS DATOS EN MEMORIA. return Repository .dogs } override fun getBreedDogs(breed: String): List<Dog> { var mutableDogs : MutableList <Dog> = mutableListOf() val dataSource = DogService.service.getBreedDogs(breed) dataSource .forEach{ dog-> mutableDogs .add(Dog(dog. first, dog.second)) } Repository .dogs = mutableDogs //AQUÍ CARGO LOS DATOS EN MEMORIA. return Repository .dogs } }
proyectoDog/app/src/main/java/com/john/proyectodog/data/dataSorce/Dogs.kt
320298721
package com.john.proyectodog.data.dataSorce object Dogs { val dogs : List<Pair<String, String>> = listOf( Pair( "basenji", "https://images.dog.ceo/breeds/basenji/n02110806_5744.jpg" ), Pair( "pastor aleman","https://images.dog.ceo/breeds/germanshepherd/n02106662_6966.jpg" ), Pair( "san bernardo","https://images.dog.ceo/breeds/stbernard/n02109525_6693.jpg" ), Pair( "pincher", "https://images.dog.ceo/breeds/pinscher-miniature/n02107312_5077.jpg" ), Pair( "collie border","https://images.dog.ceo/breeds/collie-border/n02106166_3850.jpg" ) ) }
proyectoDog/app/src/main/java/com/john/proyectodog/data/service/DogServiceInterface.kt
414219669
package com.john.proyectodog.data.service interface DogServiceInterface { fun getDogs(): List<Pair<String,String>> fun getBreedDogs (breed: String) : List<Pair<String,String>> }
proyectoDog/app/src/main/java/com/john/proyectodog/data/service/DogService.kt
2585414507
package com.john.proyectodog.data.service import com.john.proyectodog.data.dataSorce.Dogs class DogService : DogServiceInterface { companion object { val service: DogService by lazy{ //lazy delega a un primer acceso DogService() //Me creo sólo este objeto una vez. } } //Método que accede a la BBDD y devuelve todos los datos override fun getDogs(): List<Pair<String, String>> { return Dogs.dogs } override fun getBreedDogs(breed: String): List<Pair<String, String>> { val newDogs = Dogs.dogs.filter { it.first == breed } return newDogs } }
proyectoDog/app/src/main/java/com/john/proyectodog/domain/userCase/GetDogsBreedUseCase.kt
1897688754
package com.john.proyectodog.domain.userCase import com.john.proyectodog.data.models.Dog import com.john.proyectodog.data.models.DogRepositoryDao class GetDogsBreedUseCase (private val breed: String){ operator fun invoke() : List<Dog>{ return DogRepositoryDao.myDogRepositoryDao.getBreedDogs(breed) } }
proyectoDog/app/src/main/java/com/john/proyectodog/domain/userCase/GetDogsUseCase.kt
2192441666
package com.john.proyectodog.domain.userCase import com.john.proyectodog.data.models.Dog import com.john.proyectodog.data.models.DogRepositoryDao class GetDogsUseCase { operator fun invoke(): List<Dog>?{ return DogRepositoryDao.myDogRepositoryDao.getDogs() } }
ScreenShotAndShare/app/src/androidTest/java/com/example/screenshotandshare/ExampleInstrumentedTest.kt
1325275286
package com.example.screenshotandshare 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.screenshotandshare", appContext.packageName) } }
ScreenShotAndShare/app/src/test/java/com/example/screenshotandshare/ExampleUnitTest.kt
1544890225
package com.example.screenshotandshare 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) } }
ScreenShotAndShare/app/src/main/java/com/example/screenshotandshare/ui/theme/Color.kt
502064046
package com.example.screenshotandshare.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
ScreenShotAndShare/app/src/main/java/com/example/screenshotandshare/ui/theme/Theme.kt
532626221
package com.example.screenshotandshare.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun ScreenShotAndShareTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
ScreenShotAndShare/app/src/main/java/com/example/screenshotandshare/ui/theme/Type.kt
1324599872
package com.example.screenshotandshare.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
ScreenShotAndShare/app/src/main/java/com/example/screenshotandshare/screenshot/ScreenshotExtension.kt
3508572788
package com.example.screenshotandshare.screenshot import android.app.Activity import android.graphics.Bitmap import android.graphics.Canvas import android.os.Build import android.os.Handler import android.os.Looper import android.view.PixelCopy import android.view.View import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.toAndroidRect fun View.screenshot( bounds: Rect, ): ImageResult { try { val bitmap = Bitmap.createBitmap( bounds.height.toInt(), bounds.width.toInt(), Bitmap.Config.ARGB_8888 ) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Above Android O not using PixelCopy throws exception // https://stackoverflow.com/questions/58314397/java-lang-illegalstateexception-software-rendering-doesnt-support-hardware-bit PixelCopy.request( (this.context as Activity).window, android.graphics.Rect( bounds.left.toInt(), bounds.top.toInt(), bounds.right.toInt(), bounds.bottom.toInt() ), bitmap, {}, Handler(Looper.getMainLooper()) ) }else{ val canvas = Canvas(bitmap) .apply { translate(-bounds.left, -bounds.top) } this.draw(canvas) canvas.setBitmap(null) } return ImageResult.Success(bitmap) } catch (exception: Exception) { return ImageResult.Error(exception) } } fun View.screenshot( bounds: Rect, bitmapCallback: (ImageResult) -> Unit ) { try { val bitmap = Bitmap.createBitmap( bounds.width.toInt(), bounds.height.toInt(), Bitmap.Config.ARGB_8888, ) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Above Android O not using PixelCopy throws exception // https://stackoverflow.com/questions/58314397/java-lang-illegalstateexception-software-rendering-doesnt-support-hardware-bit PixelCopy.request( (this.context as Activity).window, bounds.toAndroidRect(), bitmap, { when (it) { PixelCopy.SUCCESS -> { bitmapCallback.invoke(ImageResult.Success(bitmap)) } PixelCopy.ERROR_DESTINATION_INVALID -> { bitmapCallback.invoke( ImageResult.Error( Exception( "The destination isn't a valid copy target. " + "If the destination is a bitmap this can occur " + "if the bitmap is too large for the hardware to " + "copy to. " + "It can also occur if the destination " + "has been destroyed" ) ) ) } PixelCopy.ERROR_SOURCE_INVALID -> { bitmapCallback.invoke( ImageResult.Error( Exception( "It is not possible to copy from the source. " + "This can happen if the source is " + "hardware-protected or destroyed." ) ) ) } PixelCopy.ERROR_TIMEOUT -> { bitmapCallback.invoke( ImageResult.Error( Exception( "A timeout occurred while trying to acquire a buffer " + "from the source to copy from." ) ) ) } PixelCopy.ERROR_SOURCE_NO_DATA -> { bitmapCallback.invoke( ImageResult.Error( Exception( "The source has nothing to copy from. " + "When the source is a Surface this means that " + "no buffers have been queued yet. " + "Wait for the source to produce " + "a frame and try again." ) ) ) } else -> { bitmapCallback.invoke( ImageResult.Error( Exception( "The pixel copy request failed with an unknown error." ) ) ) } } }, Handler(Looper.getMainLooper()) ) } else { val canvas = Canvas(bitmap) .apply { translate(-bounds.left, -bounds.top) } this.draw(canvas) canvas.setBitmap(null) bitmapCallback.invoke(ImageResult.Success(bitmap)) } } catch (e: Exception) { bitmapCallback.invoke(ImageResult.Error(e)) } }
ScreenShotAndShare/app/src/main/java/com/example/screenshotandshare/screenshot/ImageResult.kt
918264697
package com.example.screenshotandshare.screenshot import android.graphics.Bitmap sealed class ImageResult { //every class and object extends the ImageResult class object Initial : ImageResult() data class Error(val exception: Exception) : ImageResult() data class Success(val bitmapData: Bitmap) :ImageResult() }
ScreenShotAndShare/app/src/main/java/com/example/screenshotandshare/screenshot/ScreenshotBox.kt
3761234375
package com.example.screenshotandshare.screenshot import android.graphics.Bitmap import android.os.Build import android.view.View import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Rect import androidx.compose.ui.layout.boundsInRoot import androidx.compose.ui.layout.boundsInWindow import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalView @Composable fun ScreenShotBox( modifier: Modifier = Modifier, capture:MutableState<Boolean>, capturedBitmap:(Bitmap?)->Unit, content: @Composable () -> Unit ){ val view: View = LocalView.current var composableBounds = remember { mutableStateOf<Rect?>(null) } DisposableEffect(key1 = capture.value ){ if(capture.value){ composableBounds.value?.let{ bounds -> if(bounds.width == 0f || bounds.height == 0f)return@let view.screenshot(bounds){ imageResult: ImageResult -> if (imageResult is ImageResult.Success) { capturedBitmap(imageResult.bitmapData) } } } } onDispose { composableBounds.value?.let{ bounds -> if(bounds.width == 0f || bounds.height == 0f)return@let view.screenshot(bounds){ imageResult: ImageResult -> if (imageResult is ImageResult.Success) { if(!imageResult.bitmapData.isRecycled){ imageResult.bitmapData.recycle() } } } } } } Box(modifier = modifier.fillMaxSize() .onGloballyPositioned { composableBounds.value = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { it.boundsInWindow() } else { it.boundsInRoot() } } ) { content() } }
ScreenShotAndShare/app/src/main/java/com/example/screenshotandshare/MainActivity.kt
3285779114
package com.example.screenshotandshare import android.content.ContentValues import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.os.Bundle import android.provider.MediaStore import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.TextField import androidx.compose.material3.FilledTonalButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.unit.dp import androidx.core.content.ContextCompat import com.example.screenshotandshare.screenshot.ImageResult import com.example.screenshotandshare.screenshot.ScreenShotBox class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyApp() } } @Composable fun MyApp() { var text by remember { mutableStateOf("Hello, World!") } val capture = remember { mutableStateOf(false) } val captureBitmap = remember { mutableStateOf<Bitmap?>(null) } Column( modifier = Modifier .fillMaxSize() .padding(16.dp) ) { ScreenShotBox(capture = capture, capturedBitmap = { captureBitmap.value = it }) { TextField( value = text, onValueChange = { newText -> text = newText }, label = { Text("Enter text") }, modifier = Modifier .fillMaxWidth() .padding(bottom = 16.dp) ) // Clickable composable to take a screenshot and share Box( modifier = Modifier .fillMaxWidth() .height(48.dp) .clip(MaterialTheme.shapes.medium) .background(MaterialTheme.colors.primary) .clickable { capture.value = true }, contentAlignment = Alignment.Center ) { Text( text = "Take Screenshot and Share", color = Color.White ) } } } if(capture.value){ ImageAlertDialog(bitmap = captureBitmap.value) { capture.value = false } } } // Function to share the captured screenshot private fun shareScreenshot(bitmap: Bitmap, context: Context) { val imageUri = context.contentResolver.insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, ContentValues() ) ?: return context.contentResolver.openOutputStream(imageUri)?.use { outputStream -> bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream) } val shareIntent = Intent(Intent.ACTION_SEND).apply { type = "image/jpeg" putExtra(Intent.EXTRA_STREAM, imageUri) } ContextCompat.startActivity( context, Intent.createChooser(shareIntent, "Share screenshot"), null ) } } @Composable private fun ImageAlertDialog(bitmap:Bitmap?, onDismiss: () -> Unit) { androidx.compose.material.AlertDialog( onDismissRequest = onDismiss, confirmButton = { FilledTonalButton(onClick = { onDismiss() }) { Text(text = "Confirm") } }, dismissButton = { FilledTonalButton(onClick = { onDismiss() }) { Text(text = "Dismiss") } }, text = { if(bitmap!= null) { Image( bitmap = bitmap.asImageBitmap(), contentDescription = null ) }else{ Text(text = "Error in capturing") } }) }
bonus-trick/app/src/androidTest/java/miu/edu/localizingdate/ExampleInstrumentedTest.kt
745333722
package miu.edu.localizingdate 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("miu.edu.localizingdate", appContext.packageName) } }
bonus-trick/app/src/test/java/miu/edu/localizingdate/ExampleUnitTest.kt
1995182601
package miu.edu.localizingdate 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) } }
bonus-trick/app/src/main/java/miu/edu/localizingdate/MainActivity.kt
3915972513
package miu.edu.localizingdate import android.content.Context import android.content.res.Configuration import android.os.Build import android.os.Bundle import androidx.annotation.RequiresApi import androidx.annotation.StringRes import androidx.appcompat.app.AppCompatActivity import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async import kotlinx.coroutines.launch import miu.edu.localizingdate.databinding.ActivityMainBinding import org.json.JSONObject import java.io.BufferedReader import java.io.InputStreamReader import java.net.HttpURLConnection import java.net.URL import java.text.SimpleDateFormat import java.time.LocalDateTime import java.time.ZoneId import java.util.Locale class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding @RequiresApi(Build.VERSION_CODES.O) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) GlobalScope.launch(Dispatchers.Main) { val sunriseDeferred = async(Dispatchers.IO) { fetchTime("sunrise") } val sunsetDeferred = async(Dispatchers.IO) { fetchTime("sunset") } val sunriseTime = sunriseDeferred.await() val sunsetTime = sunsetDeferred.await() if (sunriseTime != null && sunsetTime != null) { val localizedSunrise = getLocalizedTime(sunriseTime, this@MainActivity) val localizedSunset = getLocalizedTime(sunsetTime, this@MainActivity) binding.textviewSunrise.text = "${getString(Locale.SIMPLIFIED_CHINESE, R.string.SunriseTime)} $localizedSunrise" binding.textviewSunset.text = "${getString(Locale.SIMPLIFIED_CHINESE, R.string.SunriseTime)} $localizedSunset" } } } private fun Context.getString(locale: Locale, @StringRes resId: Int, vararg formatArgs: Any): String { var conf: Configuration = resources.configuration conf = Configuration(conf) conf.setLocale(locale) val localizedContext = createConfigurationContext(conf) return localizedContext.resources.getString(resId, *formatArgs) } @RequiresApi(Build.VERSION_CODES.O) private fun getLocalizedTime(time: LocalDateTime, context: Context): String { val userPreferredLanguage = Locale.SIMPLIFIED_CHINESE.language val sdf = SimpleDateFormat("hh:mm a", Locale(userPreferredLanguage)) return sdf.format( time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() ) } @RequiresApi(Build.VERSION_CODES.O) private suspend fun fetchTime(type: String): LocalDateTime? { return try { val apiUrl = URL("https://api.sunrise-sunset.org/json?lat=37.7749&lng=-122.4194&formatted=0") val urlConnection: HttpURLConnection = apiUrl.openConnection() as HttpURLConnection try { val reader = BufferedReader(InputStreamReader(urlConnection.inputStream)) val response = StringBuilder() var line: String? while (reader.readLine().also { line = it } != null) { response.append(line) } val jsonResponse = JSONObject(response.toString()) val timeUTC = jsonResponse.getJSONObject("results").getString(type) val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX", Locale.getDefault()) val dateTime = formatter.parse(timeUTC) LocalDateTime.ofInstant(dateTime.toInstant(), ZoneId.systemDefault()) } finally { urlConnection.disconnect() } } catch (e: Exception) { e.printStackTrace() null } } }
chan-spring/src/test/kotlin/chan/spring/demo/DemoApplicationTests.kt
3723174193
package chan.spring.demo import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class DemoApplicationTests { @Test fun contextLoads() { } }
chan-spring/src/test/kotlin/chan/spring/demo/member/service/command/MemberCommandServiceTest.kt
1485311469
package chan.spring.demo.member.service.command import chan.spring.demo.exception.exception.JwtCustomException import chan.spring.demo.exception.exception.MemberException import chan.spring.demo.jwt.service.JwtTokenService import chan.spring.demo.member.domain.Role import chan.spring.demo.member.dto.request.* import chan.spring.demo.member.service.query.MemberQueryService import jakarta.persistence.EntityManager import org.assertj.core.api.Assertions import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.transaction.annotation.Transactional @SpringBootTest class MemberCommandServiceTest @Autowired constructor( private val entityManager: EntityManager, private val memberCommandService: MemberCommandService, private val memberQueryService: MemberQueryService, private val jwtTokenService: JwtTokenService ) { private fun flushAndClear() { entityManager.flush() entityManager.clear() } @Test @Transactional fun signup() { // given val email = "[email protected]" val pw = "1234" val request = SignupDto(email, pw) // when memberCommandService.signup(request) flushAndClear() // then val loginDto = LoginDto(email, pw) val jwtTokenInfo = memberCommandService.login(loginDto) Assertions.assertThat(memberQueryService.getMemberById(jwtTokenInfo.id).auth) .isEqualTo(Role.MEMBER) } @Test @Transactional fun reissueJwtToken() { // given val email = "[email protected]" val pw = "1234" val request = SignupDto(email, pw) memberCommandService.signup(request) flushAndClear() val loginDto = LoginDto(email, pw) val jwtTokenInfo = memberCommandService.login(loginDto) // when val reissueJwtToken = memberCommandService.reissueJwtToken(jwtTokenInfo.id, jwtTokenInfo.refreshToken) flushAndClear() // then val jwtTokenInfo2 = memberCommandService.login(loginDto) Assertions.assertThat(reissueJwtToken.refreshToken.equals(jwtTokenInfo2.refreshToken)).isTrue() } @Test @Transactional fun updatePassword() { // given val email = "[email protected]" val pw = "1234" val request = SignupDto(email, pw) memberCommandService.signup(request) flushAndClear() val loginDto = LoginDto(email, pw) val id = memberCommandService.login(loginDto).id //when val newPw = "1111" val updatePasswordDto = UpdatePasswordDto(newPw, pw) memberCommandService.updatePassword(updatePasswordDto, id) flushAndClear() //then Assertions.assertThat(memberCommandService.login(LoginDto(email, newPw)).id).isEqualTo(id) } @Test @Transactional fun recoveryMember() { // given val email = "[email protected]" val pw = "1234" val request = SignupDto(email, pw) memberCommandService.signup(request) flushAndClear() val loginDto = LoginDto(email, pw) val id = memberCommandService.login(loginDto).id val withdrawDto = WithdrawDto(pw) memberCommandService.withdraw(withdrawDto, id) flushAndClear() // when memberCommandService.recoveryMember(RecoveryDto(email, pw)) flushAndClear() // then Assertions.assertThat(memberQueryService.getMemberById(id)).isNotNull } @Test @Transactional fun withdraw() { // given val email = "[email protected]" val pw = "1234" val request = SignupDto(email, pw) memberCommandService.signup(request) flushAndClear() val loginDto = LoginDto(email, pw) val id = memberCommandService.login(loginDto).id // when val withdrawDto = WithdrawDto(pw) memberCommandService.withdraw(withdrawDto, id) flushAndClear() // then Assertions.assertThatThrownBy { jwtTokenService.getRefreshToken(id) } .isInstanceOf(JwtCustomException::class.java) Assertions.assertThatThrownBy { (memberQueryService.getMemberById(id)) } .isInstanceOf(MemberException::class.java) } }
chan-spring/src/test/kotlin/chan/spring/demo/member/domain/MemberTest.kt
829507047
package chan.spring.demo.member.domain import chan.spring.demo.globalUtil.isMatchPassword import org.assertj.core.api.Assertions import org.junit.jupiter.api.Test class MemberTest { @Test fun isAdmin() { //given val email = "[email protected]" val pw = "1234" //when val admin = Member.create(email, pw) //then Assertions.assertThat(admin.isAdmin()).isTrue() } @Test fun updatePw() { // given val email = "[email protected]" val pw = "1234" val member = Member.create(email, pw) // when val updatedPw = "1111" member.updatePw(updatedPw, pw) // then Assertions.assertThat(isMatchPassword(updatedPw, member.pw)).isTrue() } @Test fun withdraw() { // given val email = "[email protected]" val pw = "1234" val member = Member.create(email, pw) // when member.withdraw() //then Assertions.assertThat(member.auth).isEqualTo(Role.WITHDRAW) } @Test fun recovery() { // given val email = "[email protected]" val pw = "1234" val member = Member.create(email, pw) member.withdraw() // when member.recovery(pw) //then Assertions.assertThat(member.auth).isEqualTo(Role.MEMBER) } }
chan-spring/src/main/kotlin/chan/spring/demo/jwt/dto/JwtTokenInfo.kt
1864836911
package chan.spring.demo.jwt.dto import java.util.UUID data class JwtTokenInfo( val id: UUID, val accessToken: String, val refreshToken: String ) { companion object { fun create( id: UUID, accessToken: String, refreshToken: String ) = JwtTokenInfo(id, accessToken, refreshToken) } }
chan-spring/src/main/kotlin/chan/spring/demo/jwt/cache/JwtCache.kt
915122385
package chan.spring.demo.jwt.cache object JwtCache { const val REFRESH_TOKEN_NAME = "RefreshToken::" }
chan-spring/src/main/kotlin/chan/spring/demo/jwt/filterLogic/JwtTokenProvider.kt
556043768
package chan.spring.demo.jwt.filterLogic import chan.spring.demo.exception.exception.JwtCustomException import chan.spring.demo.exception.message.JwtExceptionMessage import chan.spring.demo.jwt.constant.JwtConstant import chan.spring.demo.jwt.dto.JwtTokenInfo import chan.spring.demo.logger import chan.spring.demo.member.domain.Role import io.jsonwebtoken.* import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.Authentication import org.springframework.security.core.GrantedAuthority import org.springframework.security.core.authority.SimpleGrantedAuthority import org.springframework.security.core.userdetails.User import org.springframework.security.core.userdetails.UserDetails import org.springframework.stereotype.Component import java.util.* @Component class JwtTokenProvider { private val key = Jwts.SIG.HS256.key().build() fun generateToken(authentication: Authentication): JwtTokenInfo { val id = UUID.fromString(authentication.name) return JwtTokenInfo.create(id, generateAccessToken(authentication), generateRefreshToken()) } private fun generateAccessToken(authentication: Authentication): String { return Jwts.builder() .subject(authentication.name) .claim(JwtConstant.CLAIM_NAME, authentication.authorities.iterator().next().authority) .expiration(Date(Date().time + JwtConstant.TWO_HOUR_MS)) .signWith(key) .compact() } fun reissueToken( id: UUID, role: Role ): JwtTokenInfo { return JwtTokenInfo.create(id, generateAccessTokenWhenReissue(id, role), generateRefreshToken()) } private fun generateAccessTokenWhenReissue( id: UUID, role: Role ): String { return Jwts.builder() .subject(id.toString()) .claim(JwtConstant.CLAIM_NAME, role.auth) .expiration(Date(Date().time + JwtConstant.TWO_HOUR_MS)) .signWith(key) .compact() } private fun generateRefreshToken(): String { return Jwts.builder() .expiration(Date(Date().time + JwtConstant.THIRTY_DAY_MS)) .signWith(key) .compact() } fun getAuthentication(accessToken: String): Authentication { val claims = parseClaims(accessToken) val authorities: Collection<GrantedAuthority> = claims[JwtConstant.CLAIM_NAME].toString() .split(JwtConstant.AUTH_DELIMITER) .map { role: String? -> SimpleGrantedAuthority(role) } val principal: UserDetails = User(claims.subject, JwtConstant.EMPTY_PW, authorities) return UsernamePasswordAuthenticationToken(principal, JwtConstant.CREDENTIAL, authorities) } private fun parseClaims(accessToken: String): Claims { return try { Jwts.parser() .verifyWith(key) .build() .parseSignedClaims(accessToken).payload } catch (e: ExpiredJwtException) { e.claims } } fun validateToken(token: String) { if (token.isBlank()) { throw JwtCustomException(JwtExceptionMessage.TOKEN_IS_NULL) } try { Jwts.parser().verifyWith(key).build().parseSignedClaims(token) } catch (e: MalformedJwtException) { logger().info(JwtExceptionMessage.INVALID_TOKEN.message) throw JwtCustomException(JwtExceptionMessage.EMPTY_CLAIMS) } catch (e: ExpiredJwtException) { logger().info(JwtExceptionMessage.EXPIRED_JWT_TOKEN.message) throw JwtCustomException(JwtExceptionMessage.EXPIRED_JWT_TOKEN) } catch (e: UnsupportedJwtException) { logger().info(JwtExceptionMessage.UNSUPPORTED_TOKEN.message) throw JwtCustomException(JwtExceptionMessage.UNSUPPORTED_TOKEN) } catch (e: SecurityException) { logger().info(JwtExceptionMessage.INVALID_TOKEN.message) throw JwtCustomException(JwtExceptionMessage.INVALID_TOKEN) } } }
chan-spring/src/main/kotlin/chan/spring/demo/jwt/filterLogic/JwtAuthenticationFilter.kt
2369479166
package chan.spring.demo.jwt.filterLogic import com.fasterxml.jackson.databind.ObjectMapper import chan.spring.demo.exception.exception.JwtCustomException import chan.spring.demo.jwt.constant.JwtConstant import chan.spring.demo.logger import jakarta.servlet.FilterChain import jakarta.servlet.ServletRequest import jakarta.servlet.ServletResponse import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletResponse import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.MediaType import org.springframework.security.core.context.SecurityContextHolder import org.springframework.web.filter.GenericFilterBean class JwtAuthenticationFilter @Autowired constructor( private val jwtTokenProvider: JwtTokenProvider ) : GenericFilterBean() { override fun doFilter( request: ServletRequest, response: ServletResponse, chain: FilterChain ) { try { resolveToken(request as HttpServletRequest)?.let { jwtTokenProvider.validateToken(it) val authentication = jwtTokenProvider.getAuthentication(it) SecurityContextHolder.getContext().authentication = authentication } chain.doFilter(request, response) } catch (e: JwtCustomException) { val httpResponse = response as HttpServletResponse httpResponse.status = e.jwtExceptionMessage.status httpResponse.contentType = MediaType.APPLICATION_JSON_VALUE val errorResponse = e.message logger().warn(e.message) val objectMapper = ObjectMapper() httpResponse.writer.write(objectMapper.writeValueAsString(errorResponse)) } } private fun resolveToken(request: HttpServletRequest): String? { return request.getHeader(JwtConstant.HEADER) ?.takeIf { it.startsWith(JwtConstant.BEARER_TOKEN) } ?.substring(JwtConstant.TOKEN_SUB_INDEX) } }
chan-spring/src/main/kotlin/chan/spring/demo/jwt/constant/JwtConstant.kt
2201423729
package chan.spring.demo.jwt.constant object JwtConstant { const val HEADER = "Authorization" const val CLAIM_NAME = "auth" const val AUTH_DELIMITER = "," const val EMPTY_PW = "" const val CREDENTIAL = "" const val TWO_HOUR_MS = 7200000 const val THIRTY_DAY_MS = 2592000000 const val BEARER_TOKEN = "Bearer" const val TOKEN_SUB_INDEX = 7 }
chan-spring/src/main/kotlin/chan/spring/demo/jwt/log/JwtServiceLog.kt
3685150778
package chan.spring.demo.jwt.log object JwtServiceLog { const val NOT_EXIST_REFRESH_TOKEN = "Refresh 토큰이 존재하지 않습니다. 회원 ID : " const val UN_MATCH_REFRESH_TOKEN = "Refresh 토큰이 일치하지 않습니다. 회원 ID : " }
chan-spring/src/main/kotlin/chan/spring/demo/jwt/service/JwtTokenService.kt
2406447153
package chan.spring.demo.jwt.service import chan.spring.demo.exception.exception.JwtCustomException import chan.spring.demo.exception.message.JwtExceptionMessage import chan.spring.demo.globalConfig.redis.RedisKeyValueTimeOut import chan.spring.demo.globalConfig.redis.RedisRepository import chan.spring.demo.jwt.cache.JwtCache import chan.spring.demo.jwt.domain.RefreshToken import chan.spring.demo.jwt.dto.JwtTokenInfo import chan.spring.demo.jwt.filterLogic.JwtTokenProvider import chan.spring.demo.jwt.log.JwtServiceLog import chan.spring.demo.logger import chan.spring.demo.member.domain.Role import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import java.util.UUID import java.util.concurrent.TimeUnit @Service class JwtTokenService @Autowired constructor( private val redisRepository: RedisRepository, private val jwtTokenProvider: JwtTokenProvider ) { fun getRefreshToken(id: UUID): RefreshToken = redisRepository.getByKey(JwtCache.REFRESH_TOKEN_NAME + id, RefreshToken::class.java) ?: throw JwtCustomException(JwtExceptionMessage.NOT_EXIST_REFRESH_TOKEN).apply { logger().warn(JwtServiceLog.NOT_EXIST_REFRESH_TOKEN + id) } fun createRefreshToken( id: UUID, refreshToken: String ) { redisRepository.save( JwtCache.REFRESH_TOKEN_NAME + id, RefreshToken.create(id, refreshToken), RedisKeyValueTimeOut(15, TimeUnit.DAYS) ) } fun reissueToken( id: UUID, refreshToken: String, role: Role ): JwtTokenInfo { jwtTokenProvider.validateToken(refreshToken) val key = JwtCache.REFRESH_TOKEN_NAME + id redisRepository.getByKey(key, RefreshToken::class.java) ?.let { check(it.refreshToken.equals(refreshToken)) { logger().warn(JwtServiceLog.UN_MATCH_REFRESH_TOKEN + id) throw JwtCustomException(JwtExceptionMessage.UN_MATCH_REFRESH_TOKEN) } val reissueToken = jwtTokenProvider.reissueToken(id, role) it.reissueRefreshToken(reissueToken.refreshToken) redisRepository.save(key, it) return reissueToken } ?: throw JwtCustomException(JwtExceptionMessage.NOT_EXIST_REFRESH_TOKEN).apply { logger().warn(JwtServiceLog.NOT_EXIST_REFRESH_TOKEN + id) } } fun removeRefreshToken(id: UUID) { redisRepository.delete(JwtCache.REFRESH_TOKEN_NAME + id) } }
chan-spring/src/main/kotlin/chan/spring/demo/jwt/domain/RefreshToken.kt
3189397998
package chan.spring.demo.jwt.domain import java.util.UUID class RefreshToken private constructor( val id: UUID, var refreshToken: String ) { companion object { fun create( id: UUID, refreshToken: String ) = RefreshToken(id, refreshToken) } fun reissueRefreshToken(reissuedRefreshToken: String) { this.refreshToken = reissuedRefreshToken } }
chan-spring/src/main/kotlin/chan/spring/demo/converter/RoleConverter.kt
458002860
package chan.spring.demo.converter import chan.spring.demo.member.domain.Role import jakarta.persistence.AttributeConverter import jakarta.persistence.Converter @Converter class RoleConverter : AttributeConverter<Role, String> { override fun convertToDatabaseColumn(attribute: Role) = attribute.name override fun convertToEntityAttribute(dbData: String) = Role.valueOf(dbData) }
chan-spring/src/main/kotlin/chan/spring/demo/globalConfig/security/SecurityConfig.kt
3632885209
package chan.spring.demo.globalConfig.security import chan.spring.demo.jwt.filterLogic.JwtAuthenticationFilter import chan.spring.demo.jwt.filterLogic.JwtTokenProvider import chan.spring.demo.member.controller.constant.MemberUrl import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.http.SessionCreationPolicy import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.security.web.SecurityFilterChain import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter @Configuration @EnableWebSecurity class SecurityConfig @Autowired constructor( private val jwtTokenProvider: JwtTokenProvider ) { @Bean fun passwordEncoder(): PasswordEncoder = BCryptPasswordEncoder() @Bean fun filterChain(http: HttpSecurity): SecurityFilterChain? { http.csrf { obj -> obj.disable() } http.requestCache { cache -> cache.disable() } http.sessionManagement { session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS) } http.authorizeHttpRequests { path -> path.requestMatchers( MemberUrl.SIGNUP, MemberUrl.LOGIN, MemberUrl.JWT_TOKEN_REISSUE, MemberUrl.RECOVERY_MEMBER ).permitAll().anyRequest().authenticated() } http.addFilterBefore( JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter::class.java ) http.exceptionHandling { exception -> exception.accessDeniedPage(MemberUrl.PROHIBITION) } return http.build() } }
chan-spring/src/main/kotlin/chan/spring/demo/globalConfig/redis/RedisConfig.kt
1960949494
package chan.spring.demo.globalConfig.redis import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule import com.fasterxml.jackson.module.kotlin.KotlinFeature import com.fasterxml.jackson.module.kotlin.KotlinModule import chan.spring.demo.globalConfig.redis.constant.RedisConstant import io.lettuce.core.RedisURI import org.springframework.beans.factory.annotation.Value import org.springframework.cache.CacheManager import org.springframework.cache.annotation.EnableCaching import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.data.redis.cache.RedisCacheConfiguration import org.springframework.data.redis.cache.RedisCacheManager import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory import org.springframework.data.redis.core.RedisTemplate import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer import org.springframework.data.redis.serializer.RedisSerializationContext import org.springframework.data.redis.serializer.StringRedisSerializer import java.time.Duration @Configuration @EnableCaching class RedisConfig( @Value(RedisConstant.REDIS_URL) val url: String ) { @Bean fun lettuceConnectionFactory(): LettuceConnectionFactory { val redisURI: RedisURI = RedisURI.create(url) val configuration = LettuceConnectionFactory.createRedisConfiguration(redisURI) return LettuceConnectionFactory(configuration) } @Bean fun cacheManager(): CacheManager { val objectMapper = ObjectMapper() .registerModules( JavaTimeModule(), KotlinModule.Builder() .withReflectionCacheSize(RedisConstant.REFLECTION_CACHE_SIZE) .configure(KotlinFeature.NullToEmptyCollection, false) .configure(KotlinFeature.NullToEmptyMap, false) .configure(KotlinFeature.NullIsSameAsDefault, false) .configure(KotlinFeature.SingletonSupport, false) .configure(KotlinFeature.StrictNullChecks, false) .build() ) .activateDefaultTyping( BasicPolymorphicTypeValidator.builder() .allowIfBaseType(Any::class.java).build(), ObjectMapper.DefaultTyping.EVERYTHING ) val configuration = RedisCacheConfiguration.defaultCacheConfig() .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(StringRedisSerializer())) .serializeValuesWith( RedisSerializationContext.SerializationPair.fromSerializer( GenericJackson2JsonRedisSerializer(objectMapper) ) ) .entryTtl(Duration.ofMinutes(RedisConstant.TTL)) .disableCachingNullValues() return RedisCacheManager.RedisCacheManagerBuilder .fromConnectionFactory(lettuceConnectionFactory()) .cacheDefaults(configuration) .build() } @Bean fun redisTemplate(): RedisTemplate<String, Any> { return RedisTemplate<String, Any>().apply { this.connectionFactory = lettuceConnectionFactory() this.keySerializer = StringRedisSerializer() this.valueSerializer = StringRedisSerializer() this.hashKeySerializer = StringRedisSerializer() this.hashValueSerializer = StringRedisSerializer() } } }
chan-spring/src/main/kotlin/chan/spring/demo/globalConfig/redis/constant/RedisConstant.kt
1302965249
package chan.spring.demo.globalConfig.redis.constant object RedisConstant { const val REDIS_URL = "\${spring.redis.url}" const val REFLECTION_CACHE_SIZE = 512 const val TTL: Long = 15 }
chan-spring/src/main/kotlin/chan/spring/demo/globalConfig/redis/RedisRepository.kt
2862233390
package chan.spring.demo.globalConfig.redis import com.fasterxml.jackson.databind.ObjectMapper import org.springframework.data.redis.core.RedisTemplate import org.springframework.stereotype.Component import java.util.concurrent.TimeUnit class RedisKeyValueTimeOut( val time: Long, val timeUnit: TimeUnit ) @Component class RedisRepository( private val redisTemplate: RedisTemplate<String, Any>, private val objectMapper: ObjectMapper ) { fun save( key: String, value: Any, timeOut: RedisKeyValueTimeOut? = null ) { timeOut?.let { redisTemplate.opsForValue().set( key, objectMapper.writeValueAsString(value), timeOut.time, timeOut.timeUnit ) } ?: run { redisTemplate.opsForValue().set( key, objectMapper.writeValueAsString(value) ) } } fun delete(key: String) { redisTemplate.delete(key) } fun <T> getByKey( key: String, clazz: Class<T> ): T? { val result = redisTemplate.opsForValue()[key].toString() return if (result.isEmpty()) { null } else { return objectMapper.readValue(result, clazz) } } operator fun <T> get( key: String, clazz: Class<T> ): T? { return getByKey(key = key, clazz = clazz) } operator fun set( key: String, value: Any ) { return save(key = key, value = value) } }
chan-spring/src/main/kotlin/chan/spring/demo/globalConfig/querydsl/QueryDslConfig.kt
1736868055
package chan.spring.demo.globalConfig.querydsl import com.querydsl.jpa.impl.JPAQueryFactory import jakarta.persistence.EntityManager import jakarta.persistence.PersistenceContext import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class QueryDslConfig( @PersistenceContext val entityManager: EntityManager ) { @Bean fun jpaQueryFactory(): JPAQueryFactory = JPAQueryFactory(entityManager) }
chan-spring/src/main/kotlin/chan/spring/demo/DemoApplication.kt
447530623
package chan.spring.demo import org.slf4j.LoggerFactory import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication inline fun <reified T> T.logger() = LoggerFactory.getLogger(T::class.java)!! @SpringBootApplication class DemoApplication fun main(args: Array<String>) { runApplication<DemoApplication>(*args) }
chan-spring/src/main/kotlin/chan/spring/demo/member/dto/response/MemberInfo.kt
529624776
package chan.spring.demo.member.dto.response import chan.spring.demo.member.domain.Role import java.util.* data class MemberInfo( val id: UUID, val auth: Role, val email: String )
chan-spring/src/main/kotlin/chan/spring/demo/member/dto/request/LoginDto.kt
3505864540
package chan.spring.demo.member.dto.request import jakarta.validation.constraints.NotBlank data class LoginDto( @field:NotBlank(message = "이메일을 입력하세요.") val email: String?, @field:NotBlank(message = "비밀번호를 입력하세요.") val pw: String? )
chan-spring/src/main/kotlin/chan/spring/demo/member/dto/request/UpdatePasswordDto.kt
2528651212
package chan.spring.demo.member.dto.request import jakarta.validation.constraints.NotBlank data class UpdatePasswordDto( @field:NotBlank(message = "새 비밀번호를 입력하세요.") val newPassword: String?, @field:NotBlank(message = "기존 비밀번호를 입력하세요.") val oldPassword: String? )
chan-spring/src/main/kotlin/chan/spring/demo/member/dto/request/SignupDto.kt
390465659
package chan.spring.demo.member.dto.request import jakarta.validation.constraints.NotBlank data class SignupDto( @field:NotBlank(message = "이메일을 입력하세요.") val email: String?, @field:NotBlank(message = "비밀번호를 입력하세요.") val pw: String? )
chan-spring/src/main/kotlin/chan/spring/demo/member/dto/request/RecoveryDto.kt
3915503733
package chan.spring.demo.member.dto.request import jakarta.validation.constraints.NotBlank data class RecoveryDto( @field:NotBlank(message = "이메일을 입력하세요.") val email: String?, @field:NotBlank(message = "비밀번호를 입력하세요.") val pw: String? )
chan-spring/src/main/kotlin/chan/spring/demo/member/dto/request/WithdrawDto.kt
2570608344
package chan.spring.demo.member.dto.request import jakarta.validation.constraints.NotBlank data class WithdrawDto( @field:NotBlank(message = "비밀번호를 입력하세요.") val pw: String? )
chan-spring/src/main/kotlin/chan/spring/demo/member/repository/MemberCustomRepositoryImpl.kt
2579773105
package chan.spring.demo.member.repository import com.querydsl.core.types.Projections import com.querydsl.jpa.impl.JPAQueryFactory import chan.spring.demo.exception.exception.MemberException import chan.spring.demo.exception.message.MemberExceptionMessage import chan.spring.demo.member.domain.Member import chan.spring.demo.member.domain.QMember import chan.spring.demo.member.domain.Role import chan.spring.demo.member.dto.response.MemberInfo import java.util.* class MemberCustomRepositoryImpl( private val jpaQueryFactory: JPAQueryFactory, private val member: QMember = QMember.member ) : MemberCustomRepository { override fun findMemberByEmail(email: String): Member { return jpaQueryFactory.selectFrom(member) .where(member.email.eq(email).and(member.auth.ne(Role.WITHDRAW))) .fetchOne() ?: throw MemberException(MemberExceptionMessage.MEMBER_IS_NULL, email) } override fun findMemberById(id: UUID): Member { return jpaQueryFactory.selectFrom(member) .where(member.id.eq(id).and(member.auth.ne(Role.WITHDRAW))) .fetchOne() ?: throw MemberException(MemberExceptionMessage.MEMBER_IS_NULL, id.toString()) } override fun findMemberByEmailIncludeWithdraw(email: String): Member { return jpaQueryFactory.selectFrom(member) .where(member.email.eq(email)) .fetchOne() ?: throw MemberException(MemberExceptionMessage.MEMBER_IS_NULL, email) } override fun findMemberInfoById(id: UUID): MemberInfo { return jpaQueryFactory.select( Projections.constructor( MemberInfo::class.java, member.id, member.auth, member.email ) ) .from(member) .where(member.id.eq(id).and(member.auth.ne(Role.WITHDRAW))) .fetchOne() ?: throw MemberException(MemberExceptionMessage.MEMBER_IS_NULL, id.toString()) } override fun findAuthById(id: UUID): Role { return jpaQueryFactory.select(member.auth) .from(member) .where(member.id.eq(id).and(member.auth.ne(Role.WITHDRAW))) .fetchOne() ?: throw MemberException(MemberExceptionMessage.MEMBER_IS_NULL, id.toString()) } }
chan-spring/src/main/kotlin/chan/spring/demo/member/repository/MemberRepository.kt
2584784151
package chan.spring.demo.member.repository import chan.spring.demo.member.domain.Member import org.springframework.data.jpa.repository.JpaRepository interface MemberRepository : JpaRepository<Member, Long>, MemberCustomRepository
chan-spring/src/main/kotlin/chan/spring/demo/member/repository/MemberCustomRepository.kt
3119944128
package chan.spring.demo.member.repository import chan.spring.demo.member.domain.Member import chan.spring.demo.member.domain.Role import chan.spring.demo.member.dto.response.MemberInfo import java.util.* interface MemberCustomRepository { fun findMemberByEmail(email: String): Member fun findMemberById(id: UUID): Member fun findMemberByEmailIncludeWithdraw(email: String): Member fun findMemberInfoById(id: UUID): MemberInfo fun findAuthById(id: UUID): Role }
chan-spring/src/main/kotlin/chan/spring/demo/member/controller/response/MemberResponse.kt
3895216291
package chan.spring.demo.member.controller.response import chan.spring.demo.member.dto.response.MemberInfo import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity object MemberResponse { private const val SIGNUP_SUCCESS = "회원가입에 성공하였습니다.\n반갑습니다." private const val LOGIN_SUCCESS = "로그인에 성공하였습니다.\n환영합니다." private const val UPDATE_PW_SUCCESS = "비밀번호를 성공적으로 변경하였습니다." private const val LOGOUT_SUCCESS = "로그아웃에 성공하였습니다." private const val RECOVERY_SUCCESS = "계정 복구에 성공하였습니다." private const val WITHDRAW_SUCCESS = "회원탈퇴를 성공적으로 마쳤습니다.\n안녕히가세요." fun infoSuccess(member: MemberInfo) = ResponseEntity.ok(member) fun signupSuccess() = ResponseEntity.status(HttpStatus.CREATED).body(SIGNUP_SUCCESS) fun loginSuccess() = ResponseEntity.ok(LOGIN_SUCCESS) fun updatePwSuccess() = ResponseEntity.ok(UPDATE_PW_SUCCESS) fun logOutSuccess() = ResponseEntity.ok(LOGOUT_SUCCESS) fun recoverySuccess() = ResponseEntity.ok(RECOVERY_SUCCESS) fun withdrawSuccess() = ResponseEntity.ok(WITHDRAW_SUCCESS) }
chan-spring/src/main/kotlin/chan/spring/demo/member/controller/MemberController.kt
3701950676
package chan.spring.demo.member.controller import chan.spring.demo.logger import chan.spring.demo.member.dto.request.* import chan.spring.demo.exception.exception.MemberException import chan.spring.demo.exception.message.MemberExceptionMessage import chan.spring.demo.jwt.dto.JwtTokenInfo import chan.spring.demo.member.controller.constant.MemberControllerConstant import chan.spring.demo.member.controller.constant.MemberRequestHeaderConstant import chan.spring.demo.member.controller.constant.MemberUrl import chan.spring.demo.member.controller.response.MemberResponse import chan.spring.demo.member.dto.response.MemberInfo import chan.spring.demo.member.log.MemberControllerLog import chan.spring.demo.member.service.command.MemberCommandService import chan.spring.demo.member.service.query.MemberQueryService import jakarta.servlet.http.HttpServletResponse import jakarta.validation.Valid import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import java.security.Principal import java.util.* @RestController class MemberController @Autowired constructor( private val memberQueryService: MemberQueryService, private val memberCommandService: MemberCommandService ) { @GetMapping(MemberUrl.INFO) fun getMemberInfo(principal: Principal): ResponseEntity<MemberInfo> { val member = memberQueryService.getMemberById(id = UUID.fromString(principal.name)) return MemberResponse.infoSuccess(member) } @PostMapping(MemberUrl.SIGNUP) fun signup( @RequestBody @Valid signupDto: SignupDto ): ResponseEntity<String> { memberCommandService.signup(signupDto) logger().info(MemberControllerLog.SIGNUP_SUCCESS + signupDto.email) return MemberResponse.signupSuccess() } @PostMapping(MemberUrl.LOGIN) fun login( @RequestBody @Valid loginDto: LoginDto, response: HttpServletResponse ): ResponseEntity<String> { val tokenInfo = memberCommandService.login(loginDto) response.apply { addHeader(MemberControllerConstant.ACCESS_TOKEN, tokenInfo.accessToken) addHeader(MemberControllerConstant.REFRESH_TOKEN, tokenInfo.refreshToken) addHeader(MemberControllerConstant.MEMBER_ID, tokenInfo.id.toString()) } logger().info(MemberControllerLog.LOGIN_SUCCESS + loginDto.email) return MemberResponse.loginSuccess() } @PutMapping(MemberUrl.JWT_TOKEN_REISSUE) fun jwtTokenReissue( @RequestHeader(MemberRequestHeaderConstant.ID) id: String?, @RequestHeader(MemberRequestHeaderConstant.REFRESH_TOKEN) refreshToken: String? ): ResponseEntity<JwtTokenInfo> { if (id.isNullOrBlank() || refreshToken.isNullOrBlank()) { throw MemberException(MemberExceptionMessage.TOKEN_REISSUE_HEADER_IS_NULL, "UNRELIABLE-MEMBER") } val memberId = UUID.fromString(id) val reissueJwtToken = memberCommandService.reissueJwtToken(memberId, refreshToken) logger().info(MemberControllerLog.JWT_TOKEN_REISSUE_SUCCESS + memberId) return ResponseEntity.ok(reissueJwtToken) } @PatchMapping(MemberUrl.UPDATE_PASSWORD) fun updatePassword( @RequestBody @Valid updatePasswordDto: UpdatePasswordDto, principal: Principal ): ResponseEntity<String> { val memberId = UUID.fromString(principal.name) memberCommandService.updatePassword(updatePasswordDto, memberId) logger().info(MemberControllerLog.UPDATE_PW_SUCCESS + memberId) return MemberResponse.updatePwSuccess() } @PostMapping(MemberUrl.LOGOUT) fun logout(principal: Principal): ResponseEntity<String> { val memberId = UUID.fromString(principal.name) memberCommandService.logout(memberId) logger().info(MemberControllerLog.LOGOUT_SUCCESS + memberId) return MemberResponse.logOutSuccess() } @PostMapping(MemberUrl.RECOVERY_MEMBER) fun recoveryMember( @RequestBody @Valid recoveryDto: RecoveryDto ): ResponseEntity<String> { memberCommandService.recoveryMember(recoveryDto) logger().info(MemberControllerLog.RECOVERY_SUCCESS + recoveryDto.email) return MemberResponse.recoverySuccess() } @DeleteMapping(MemberUrl.WITHDRAW) fun withdraw( @RequestBody @Valid withdrawDto: WithdrawDto, principal: Principal ): ResponseEntity<String> { val memberId = UUID.fromString(principal.name) memberCommandService.withdraw(withdrawDto, memberId) logger().info(MemberControllerLog.WITHDRAW_SUCCESS + memberId) return MemberResponse.withdrawSuccess() } }
chan-spring/src/main/kotlin/chan/spring/demo/member/controller/constant/MemberUrl.kt
2326422416
package chan.spring.demo.member.controller.constant object MemberUrl { const val SIGNUP = "/member/signup" const val LOGIN = "/member/login" const val INFO = "/member/info" const val JWT_TOKEN_REISSUE = "/auth/reissue" const val UPDATE_PASSWORD = "/member/update/password" const val LOGOUT = "/member/logout" const val RECOVERY_MEMBER = "/member/recovery" const val WITHDRAW = "/member/withdraw" const val PROHIBITION = "/prohibition" }
chan-spring/src/main/kotlin/chan/spring/demo/member/controller/constant/MemberControllerConstant.kt
610005557
package chan.spring.demo.member.controller.constant object MemberControllerConstant { const val ACCESS_TOKEN = "access-token" const val REFRESH_TOKEN = "refresh-token" const val MEMBER_ID = "member-id" }
chan-spring/src/main/kotlin/chan/spring/demo/member/controller/constant/MemberRequestHeaderConstant.kt
1327604481
package chan.spring.demo.member.controller.constant object MemberRequestHeaderConstant { const val ID = "id" const val REFRESH_TOKEN = "refresh-token" }
chan-spring/src/main/kotlin/chan/spring/demo/member/log/MemberServiceLog.kt
4249911603
package chan.spring.demo.member.log object MemberServiceLog { const val SUSPEND_MEMBER = "정지된 회원입니다. 회원 Email : " const val WRONG_PW = "잘못된 비밀번호. 회원 ID : " }
chan-spring/src/main/kotlin/chan/spring/demo/member/log/MemberControllerLog.kt
3404465270
package chan.spring.demo.member.log object MemberControllerLog { const val SIGNUP_SUCCESS = "회원가입 성공. 회원 Email : " const val LOGIN_SUCCESS = "로그인 성공. 회원 Email : " const val UPDATE_PW_SUCCESS = "비밀번호 변경 성공. 회원 ID : " const val LOGOUT_SUCCESS = "회원 로그아웃 성공. 회원 ID : " const val RECOVERY_SUCCESS = "회원 계정 복구 성공. 회원 Email : " const val WITHDRAW_SUCCESS = "회원탈퇴 성공. 회원 UUID : " const val JWT_TOKEN_REISSUE_SUCCESS = "JWT 토큰 갱신 성공. 회원 ID : " }
chan-spring/src/main/kotlin/chan/spring/demo/member/service/command/CustomUserDetailsService.kt
1180184266
package chan.spring.demo.member.service.command import chan.spring.demo.member.domain.Member import chan.spring.demo.member.domain.Role import chan.spring.demo.member.repository.MemberCustomRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.security.core.userdetails.User import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.stereotype.Service @Service class CustomUserDetailsService @Autowired constructor( private val memberRepository: MemberCustomRepository ) : UserDetailsService { override fun loadUserByUsername(email: String): UserDetails { val member = memberRepository.findMemberByEmail(email) return createUserDetails(member) } private fun createUserDetails(member: Member): UserDetails { return when (member.auth) { Role.ADMIN -> { createAdmin(member) } else -> { createMember(member) } } } private fun createAdmin(member: Member): UserDetails { return User.builder() .username(member.id.toString()) .password(member.password) .roles(Role.ADMIN.name) .build() } private fun createMember(member: Member): UserDetails { return User.builder() .username(member.id.toString()) .password(member.password) .roles(Role.MEMBER.name) .build() } }
chan-spring/src/main/kotlin/chan/spring/demo/member/service/command/MemberCommandService.kt
736695683
package chan.spring.demo.member.service.command import chan.spring.demo.logger import chan.spring.demo.exception.exception.MemberException import chan.spring.demo.exception.message.MemberExceptionMessage import chan.spring.demo.globalUtil.isMatchPassword import chan.spring.demo.jwt.dto.JwtTokenInfo import chan.spring.demo.jwt.filterLogic.JwtTokenProvider import chan.spring.demo.jwt.service.JwtTokenService import chan.spring.demo.member.domain.Member import chan.spring.demo.member.dto.request.* import chan.spring.demo.member.log.MemberServiceLog import chan.spring.demo.member.repository.MemberRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder import org.springframework.security.core.Authentication import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.util.* @Service @Transactional class MemberCommandService @Autowired constructor( private val memberRepository: MemberRepository, private val authenticationManagerBuilder: AuthenticationManagerBuilder, private val jwtTokenProvider: JwtTokenProvider, private val jwtTokenService: JwtTokenService ) { fun signup(signupDto: SignupDto) { with(signupDto) { Member.create(email!!, pw!!).also { memberRepository.save(it) } } } fun login(loginDto: LoginDto): JwtTokenInfo { val authentication: Authentication = authenticationManagerBuilder .`object` .authenticate(UsernamePasswordAuthenticationToken(loginDto.email, loginDto.pw)) return jwtTokenProvider.generateToken(authentication).also { jwtTokenService.createRefreshToken(it.id, it.refreshToken) } } fun reissueJwtToken( id: UUID, refreshToken: String ): JwtTokenInfo { val auth = memberRepository.findAuthById(id) return jwtTokenService.reissueToken(id, refreshToken, auth) } fun updatePassword( updatePasswordDto: UpdatePasswordDto, id: UUID ) { with(updatePasswordDto) { memberRepository.findMemberById(id).also { it.updatePw(newPassword!!, oldPassword!!) } } } fun logout(id: UUID) { jwtTokenService.removeRefreshToken(id) } fun recoveryMember(recoveryDto: RecoveryDto) { with(recoveryDto) { memberRepository.findMemberByEmailIncludeWithdraw(email!!).also { it.recovery(pw!!) } } } fun withdraw( withdrawDto: WithdrawDto, id: UUID ) { memberRepository.findMemberById(id) .takeIf { isMatchPassword(withdrawDto.pw!!, it.pw) } ?.also { it.withdraw() jwtTokenService.removeRefreshToken(id) } ?: run { logger().warn(MemberServiceLog.WRONG_PW + id) throw MemberException(MemberExceptionMessage.WRONG_PASSWORD, id.toString()) } } }
chan-spring/src/main/kotlin/chan/spring/demo/member/service/query/MemberQueryService.kt
1842247072
package chan.spring.demo.member.service.query import chan.spring.demo.member.repository.MemberCustomRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.util.* @Service @Transactional(readOnly = true) class MemberQueryService @Autowired constructor( private val memberRepository: MemberCustomRepository ) { fun getMemberById(id: UUID) = memberRepository.findMemberInfoById(id) }
chan-spring/src/main/kotlin/chan/spring/demo/member/domain/constant/MemberConstant.kt
374465378
package chan.spring.demo.member.domain.constant object MemberConstant { const val PW_TYPE = "VARCHAR(100)" const val ROLE_TYPE = "VARCHAR(13)" const val ADMIN_EMAIL = "[email protected]" }
chan-spring/src/main/kotlin/chan/spring/demo/member/domain/Member.kt
906973947
package chan.spring.demo.member.domain import chan.spring.demo.converter.RoleConverter import chan.spring.demo.exception.exception.MemberException import chan.spring.demo.exception.message.MemberExceptionMessage import chan.spring.demo.globalUtil.UUID_TYPE import chan.spring.demo.globalUtil.createUUID import chan.spring.demo.globalUtil.encodePassword import chan.spring.demo.globalUtil.isMatchPassword import chan.spring.demo.member.domain.constant.MemberConstant import jakarta.persistence.* import org.springframework.security.core.GrantedAuthority import org.springframework.security.core.authority.SimpleGrantedAuthority import org.springframework.security.core.userdetails.UserDetails import java.util.* @Entity class Member private constructor( @Id @Column(columnDefinition = UUID_TYPE) val id: UUID = createUUID(), @Convert(converter = RoleConverter::class) @Column( nullable = false, columnDefinition = MemberConstant.ROLE_TYPE ) var auth: Role, @Column(nullable = false, unique = true) val email: String, @Column(nullable = false, columnDefinition = MemberConstant.PW_TYPE) var pw: String ) : UserDetails { companion object { private fun findFitAuth(email: String) = if (email == MemberConstant.ADMIN_EMAIL) Role.ADMIN else Role.MEMBER fun create( email: String, pw: String ): Member { return Member( auth = findFitAuth(email), email = email, pw = encodePassword(pw) ) } } fun isAdmin() = auth == Role.ADMIN fun updatePw( newPassword: String, oldPassword: String ) { require(isMatchPassword(oldPassword, pw)) { throw MemberException(MemberExceptionMessage.WRONG_PASSWORD, id.toString()) } pw = encodePassword(newPassword) } fun withdraw() { this.auth = Role.WITHDRAW } fun recovery(inputPw: String) { require( isMatchPassword(inputPw, pw) ) { throw MemberException(MemberExceptionMessage.WRONG_PASSWORD, id.toString()) } this.auth = Role.MEMBER } override fun getAuthorities(): MutableCollection<out GrantedAuthority> = arrayListOf<GrantedAuthority>(SimpleGrantedAuthority(auth.auth)) override fun getUsername() = id.toString() override fun getPassword() = pw override fun isAccountNonExpired() = true override fun isAccountNonLocked() = true override fun isCredentialsNonExpired() = true override fun isEnabled() = true }
chan-spring/src/main/kotlin/chan/spring/demo/member/domain/Role.kt
4153554959
package chan.spring.demo.member.domain enum class Role(val auth: String) { MEMBER("ROLE_MEMBER"), ADMIN("ROLE_ADMIN"), WITHDRAW("ROLE_WITHDRAW") }
chan-spring/src/main/kotlin/chan/spring/demo/globalUtil/UUIDUtil.kt
3617902517
package chan.spring.demo.globalUtil import java.util.* const val UUID_TYPE = "BINARY(16)" fun createUUID(): UUID = UUID.randomUUID()
chan-spring/src/main/kotlin/chan/spring/demo/globalUtil/DateTimeUtil.kt
1438188613
package chan.spring.demo.globalUtil import java.time.Instant import java.time.LocalDate import java.time.LocalDateTime const val DATETIME_TYPE = "BIGINT(12)" const val DATE_TYPE = "INT(8)" fun getCurrentTimestamp(): Int { return Instant.now().epochSecond.toInt() } fun getDatetimeDigit(dateTime: LocalDateTime): Long { val year = dateTime.year.toString() val month = checkSingleDigit(dateTime.monthValue) val day = checkSingleDigit(dateTime.dayOfMonth) val hour = checkSingleDigit(dateTime.hour) val minute = checkSingleDigit(dateTime.minute) return "$year$month$day$hour$minute".toLong() } fun getDateDigit(date: LocalDate): Int { val year = date.year.toString() val month = checkSingleDigit(date.monthValue) val day = checkSingleDigit(date.dayOfMonth) return "$year$month$day".toInt() } fun convertDateToLocalDate(date: Int): LocalDate { val stringDate = date.toString() val year = stringDate.substring(0, 4).toInt() val month = stringDate.substring(4, 6).toInt() val day = stringDate.substring(6).toInt() return LocalDate.of(year, month, day) } private fun checkSingleDigit(digit: Int): String { return if (digit in 0..9) { "0$digit" } else { digit.toString() } }
chan-spring/src/main/kotlin/chan/spring/demo/globalUtil/PasswordUtil.kt
455926569
package chan.spring.demo.globalUtil import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder fun encodePassword(password: String): String = BCryptPasswordEncoder().encode(password) fun isMatchPassword( password: String, originalEncodedPassword: String ) = BCryptPasswordEncoder().matches(password, originalEncodedPassword)
chan-spring/src/main/kotlin/chan/spring/demo/globalUtil/PageQueryUtil.kt
864612930
package chan.spring.demo.globalUtil import com.querydsl.core.types.dsl.BooleanExpression import com.querydsl.core.types.dsl.EntityPathBase import com.querydsl.core.types.dsl.NumberPath fun <T, Q : EntityPathBase<T>> ltLastId( lastId: Long?, qEntity: Q, idPathExtractor: (Q) -> NumberPath<Long> ): BooleanExpression? { return lastId?.takeIf { it > 0 }?.let { idPathExtractor(qEntity).lt(it) } } fun <T, Q : EntityPathBase<T>> ltLastTimestamp( lastTimestamp: Int?, qEntity: Q, timestampPathExtractor: (Q) -> NumberPath<Int> ): BooleanExpression? { return lastTimestamp?.takeIf { it > 0 }?.let { timestampPathExtractor(qEntity).lt(it) } } fun <T> findLastIdOrDefault( foundData: List<T>, idExtractor: (T) -> Long ): Long { return foundData.lastOrNull()?.let { idExtractor(it) } ?: 0 }
chan-spring/src/main/kotlin/chan/spring/demo/exception/controllerAdvice/GlobalControllerAdvice.kt
2822401591
package chan.spring.demo.exception.controllerAdvice import chan.spring.demo.exception.controllerAdvice.constant.GlobalAdviceConstant import jakarta.validation.ConstraintViolationException import org.springframework.dao.DataIntegrityViolationException import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.MethodArgumentNotValidException import org.springframework.web.bind.annotation.ExceptionHandler import org.springframework.web.bind.annotation.RestControllerAdvice import java.util.* @RestControllerAdvice class GlobalControllerAdvice { @ExceptionHandler(DataIntegrityViolationException::class) fun handleDuplicateEntityValueException(): ResponseEntity<String> { return ResponseEntity .status(HttpStatus.BAD_REQUEST) .body(GlobalAdviceConstant.DUPLICATE_ENTITY_VAL) } @ExceptionHandler(MethodArgumentNotValidException::class) fun handleValidationExceptions(exception: MethodArgumentNotValidException): ResponseEntity<String> { val bindingResult = exception.bindingResult val errorMessage = Objects .requireNonNull(bindingResult.fieldError) ?.defaultMessage return ResponseEntity.badRequest().body(errorMessage) } @ExceptionHandler(ConstraintViolationException::class) fun handleConstraintViolationException(ex: ConstraintViolationException): ResponseEntity<*> { return ResponseEntity .status(HttpStatus.BAD_REQUEST) .body(ex.message) } }
chan-spring/src/main/kotlin/chan/spring/demo/exception/controllerAdvice/MemberControllerAdvice.kt
2337200362
package chan.spring.demo.exception.controllerAdvice import chan.spring.demo.exception.controllerAdvice.constant.MemberAdviceConstant import chan.spring.demo.exception.exception.JwtCustomException import chan.spring.demo.exception.exception.MemberException import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.security.authentication.BadCredentialsException import org.springframework.web.bind.annotation.ExceptionHandler import org.springframework.web.bind.annotation.RestControllerAdvice @RestControllerAdvice class MemberControllerAdvice { @ExceptionHandler(BadCredentialsException::class) fun handleLoginFail(): ResponseEntity<String> { return ResponseEntity .status(HttpStatus.BAD_REQUEST) .body(MemberAdviceConstant.LOGIN_FAIL) } @ExceptionHandler(MemberException::class) fun handleMemberException(memberException: MemberException): ResponseEntity<String> { return ResponseEntity .status(memberException.memberExceptionMessage.status) .body(memberException.message + memberException.memberIdentifier) } @ExceptionHandler(JwtCustomException::class) fun handleJwtCustomException(jwtCustomException: JwtCustomException): ResponseEntity<String> { return ResponseEntity .status(jwtCustomException.jwtExceptionMessage.status) .body(jwtCustomException.message) } }
chan-spring/src/main/kotlin/chan/spring/demo/exception/controllerAdvice/constant/MemberAdviceConstant.kt
3500484945
package chan.spring.demo.exception.controllerAdvice.constant object MemberAdviceConstant { const val LOGIN_FAIL = "로그인에 실패했습니다." }
chan-spring/src/main/kotlin/chan/spring/demo/exception/controllerAdvice/constant/GlobalAdviceConstant.kt
2613627020
package chan.spring.demo.exception.controllerAdvice.constant object GlobalAdviceConstant { const val DUPLICATE_ENTITY_VAL = "데이터 베이스 무결성 조건을 위반하였습니다." }
chan-spring/src/main/kotlin/chan/spring/demo/exception/message/JwtExceptionMessage.kt
3631953171
package chan.spring.demo.exception.message enum class JwtExceptionMessage(val status: Int, val message: String) { TOKEN_IS_NULL(404, "Token Is Null"), INVALID_TOKEN(401, "Invalid JWT Token"), EXPIRED_JWT_TOKEN(401, "Expired Jwt Token"), UNSUPPORTED_TOKEN(401, "Unsupported JWT Token"), EMPTY_CLAIMS(404, "JWT claims string is empty."), NOT_EXIST_REFRESH_TOKEN(404, "Refresh Token is not exist"), UN_MATCH_REFRESH_TOKEN(401, "Un Match Refresh Token") }
chan-spring/src/main/kotlin/chan/spring/demo/exception/message/MemberExceptionMessage.kt
2826933838
package chan.spring.demo.exception.message enum class MemberExceptionMessage(val status: Int, val message: String) { WRONG_PASSWORD(400, "비밀번호를 틀렸습니다. 회원식별자 : "), MEMBER_IS_NULL(404, "회원이 존재하지 않습니다. 회원식별자 : "), TOKEN_REISSUE_HEADER_IS_NULL(404, "토큰 갱신 헤더가 비어있습니다.") }
chan-spring/src/main/kotlin/chan/spring/demo/exception/exception/MemberException.kt
508066932
package chan.spring.demo.exception.exception import chan.spring.demo.exception.message.MemberExceptionMessage class MemberException( val memberExceptionMessage: MemberExceptionMessage, val memberIdentifier: String? ) : RuntimeException(memberExceptionMessage.message)
chan-spring/src/main/kotlin/chan/spring/demo/exception/exception/JwtCustomException.kt
1319417922
package chan.spring.demo.exception.exception import chan.spring.demo.exception.message.JwtExceptionMessage class JwtCustomException(val jwtExceptionMessage: JwtExceptionMessage) : RuntimeException(jwtExceptionMessage.message)
AesDecryption/app/src/androidTest/java/com/example/aesdecryption/ExampleInstrumentedTest.kt
3254532223
package com.example.aesdecryption 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.aesdecryption", appContext.packageName) } }
AesDecryption/app/src/test/java/com/example/aesdecryption/ExampleUnitTest.kt
401737945
package com.example.aesdecryption 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) } }
AesDecryption/app/src/main/java/com/example/aesdecryption/Extension.kt
4088452463
package com.example.aesdecryption fun Char.fromHexToInt() : Int { return if(this in '0' .. '9') this.code - '0'.code else this.code - 'a'.code + 10 }
AesDecryption/app/src/main/java/com/example/aesdecryption/MainActivity.kt
2666287106
package com.example.aesdecryption import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Toast import com.example.aesdecryption.databinding.ActivityMainBinding import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.BufferedReader import java.io.InputStreamReader import java.net.ServerSocket import java.net.Socket class MainActivity : AppCompatActivity() { private lateinit var binding : ActivityMainBinding private val aes = CBC() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.apply { decryptButton.setOnClickListener { if(inputEditText.text?.isNotEmpty() == true){ CoroutineScope(Dispatchers.Main).launch{ val res = async(Dispatchers.Default){ aes.decrypt(inputEditText.text.toString()) }.await() output.setText(res) } } else{ Toast.makeText(this@MainActivity,"Fill in all information",Toast.LENGTH_SHORT).show() } } } val socket = ServerSocket(50000) try{ CoroutineScope(Dispatchers.IO).launch { while(true){ val client = socket.accept() val reader = BufferedReader(InputStreamReader(client.getInputStream())) val secretKey = reader.readLine() val iv = reader.readLine() val cipher = reader.readLine() withContext(Dispatchers.Main){ binding.inputEditText.setText(cipher) } aes.setIV(iv) aes.setSecretKey(secretKey) } } }catch(ex : Exception) { ex.printStackTrace() } } }
AesDecryption/app/src/main/java/com/example/aesdecryption/Constant.kt
225282360
package com.example.aesdecryption val iSBox = arrayOf( arrayOf( 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb ), arrayOf( 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb ), arrayOf( 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e ), arrayOf( 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25 ), arrayOf( 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92 ), arrayOf( 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84 ), arrayOf( 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06 ), arrayOf( 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b ), arrayOf( 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73 ), arrayOf( 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e ), arrayOf( 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b ), arrayOf( 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4 ), arrayOf( 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f ), arrayOf( 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef ), arrayOf( 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61 ), arrayOf( 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6,0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d ) ) val invMixCol = arrayOf( arrayOf(0x0e, 0x0b, 0x0d, 0x09), arrayOf(0x09, 0x0e, 0x0b, 0x0d), arrayOf(0x0d, 0x09, 0x0e, 0x0b), arrayOf(0x0b, 0x0d, 0x09, 0x0e) ) val sBox = arrayOf( arrayOf(0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76), arrayOf(0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0), arrayOf(0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15), arrayOf(0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75), arrayOf(0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84), arrayOf(0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF), arrayOf(0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8), arrayOf(0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2), arrayOf(0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73), arrayOf(0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB), arrayOf(0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79), arrayOf(0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08), arrayOf(0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A), arrayOf(0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E), arrayOf(0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF), arrayOf(0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16) ) val roundConstant = arrayOf(0,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,0x36,0x6c,0xd8,0xab,0x4d,0x9a)
AesDecryption/app/src/main/java/com/example/aesdecryption/CBC.kt
3322770181
package com.example.aesdecryption import android.util.Log class CBC { private lateinit var _secretKey : String private lateinit var iv : Array<Array<Int>> private var word = Array(4){Array(4){0} } private var numOfRound : Int = 0 private val numOfRoundKeyMap = mapOf(16 to 44,24 to 52,32 to 60) fun setIV(temp : String) { iv = Array(4){Array(4){0} } for(i in 0 until 4){ for(j in 0 until 4){ iv[i][j] = temp[4*i+j].fromHexToInt() } } } private fun rotWord(word : Array<Int>) : Array<Int>{ val temp = word[0] for(i in 0 until 3){ word[i] = word[i+1] } word[3] = temp return word } fun subWord(word : Array<Int>) : Array<Int>{ for(i in 0 until 4){ word[i] = subByte(word[i]) } return word } fun subByte(byte : Int ) : Int{ return throughSBox(byte) } private fun throughSBox(value : Int) : Int{ var hex = Integer.toHexString(value) hex = padByte(hex) val first = hex[0].fromHexToInt() val second = hex[1].fromHexToInt() return sBox[first][second] } fun copyWord(a : Array<Int>,b : Array<Int>) { for(i in 0 until 4){ a[i] = b[i] } } fun rCon(word : Array<Int>,round : Int) : Array<Int>{ word[0] = word[0] xor roundConstant[round] return word } fun keyExpansion(){ val keyLength = _secretKey.length/2 for(i in 0 until keyLength/4){ for(j in 0 until 4){ word[i][j] = "${_secretKey[2*(4*i+j)]}${_secretKey[2*(4*i+j)+1]}".toInt(16) } } for(i in keyLength/4 until numOfRoundKeyMap[keyLength]!!){ for(j in 0 until 4){ var temp = Array(4){0} copyWord(temp,word[i-1]) if(i%(keyLength/4) == 0){ temp = rCon(subWord(rotWord(temp)),i/(keyLength/4)) } word[i] = xorWord(temp,word[i-(keyLength/4)]) } } for(j in 0 until 44){ val i = 0 Log.i("word[$] ","${word[j][i] } ${word[j][i+1] } ${word[j][i+2] } ${word[j][i+3] }") } } fun setSecretKey(key : String){ _secretKey = key when(_secretKey.length){ 32 -> { numOfRound = 10 word = Array(44){Array(4){0} } } 48 -> { numOfRound = 12 word = Array(52){Array(4){0} } } 64 -> { numOfRound = 14 word = Array(60){Array(4){0} } } } keyExpansion() } private fun hexToState(hex : String,blocks : Int) : Array<Array<Array<Int>>>{ val state = Array(blocks){Array(4){Array(4){0} } } for(i in 0 until blocks){ for(j in 0 until 4){ for(k in 0 until 4){ state[i][j][k] = "${hex[i*32+j*8+2*k]}${hex[i*32+j*8+2*k+1]}".toInt(16) } } } return state } private fun copy(a1 : Array<Array<Int>>,a2 : Array<Array<Int>>){ for(i in 0 until 4){ for(j in 0 until 4){ a2[i][j] = a1[i][j] } } } fun addRoundKey(state : Array<Array<Int>>,round : Int){ for(i in 0 until 4){ state[i] = xorWord(state[i], word[4*round + i]) } } fun invSubState(state: Array<Array<Int>>){ for(i in 0 until 4){ for(j in 0 until 4){ state[i][j] = invSubByte(state[i][j]) } } } fun intArrayToPlainText(state : Array<Array<Array<Int>>>,blocks : Int) : String{ var res = "" for(k in 0 until blocks){ if(k == blocks - 1){ if(state[k][3][3] <= 15){ var temp = state[k][3][3] var isPadded = true var i = 3 var j = 3 while(temp > 0){ if(state[k][i][j] != state[k][3][3]){ isPadded = false break } j-- if(j == -1){ i-- j = 3 } temp-- } if(isPadded){ if(0 == state[k+1][0][0]){ i = 0 j = 0 temp = 0 while(temp < 16 - state[k][3][3]){ res += state[k][i][j].toChar() j++ if(j == 4){ i++ j = 0 } temp++ } return res } } } } for(i in 0 until 4){ for(j in 0 until 4){ res += state[k][i][j].toChar() } } } return res } private fun throughISBox(value : Int) : Int{ var hex = Integer.toHexString(value) hex = padByte(hex) val first = hex[0].fromHexToInt() val second = hex[1].fromHexToInt() return iSBox[first][second] } fun invSubByte(byte : Int) : Int{ return throughISBox(byte) } fun padByte(str : String) : String{ var res = str if(str.length == 1){ res = "0${str}" } return res } fun byteMultiplication(byte1 : Int,byte2 : Int) : Int{ if(byte2 == 0x01) return byte1 var res = 0 var a = byte1 var b = byte2 for(i in 0 until 8){ if(b and 0x01 == 0x01){ res = a xor res } var temp = 0 if(a and 0x80 == 0x80){ temp = 0x1b } a = (a shl 1)%256 xor temp b = b shr 1 } return res } fun invMixColumn(state : Array<Array<Int>>) : Array<Array<Int>>{ val temp = Array(4){Array(4){0} } for(i in 0 until 4){ for(j in 0 until 4){ for(k in 0 until 4){ temp[j][i] = temp[j][i] xor byteMultiplication(invMixCol[i][k],state[j][k]) } } } return temp } fun xorWord(word1 : Array<Int>,word2 : Array<Int>) : Array<Int>{ for(i in 0 until 4){ word1[i] = word1[i] xor word2[i] } return word1 } fun xor4Words(state : Array<Array<Int>>,iV : Array<Array<Int>>){ for(i in 0 until 4){ state[i] = xorWord(state[i], iV[i]) } } fun invShiftRow(state : Array<Array<Int>>){ for(i in 1 until 4){ for(k in 0 until i){ val temp = state[3][i] for (j in 3 downTo 1){ state[j][i] = state[j-1][i] } state[0][i] = temp } } } fun decrypt(cipherText : String) : String{ var iVTemp = iv val blocks = cipherText.length/16/2 val state = hexToState(cipherText,blocks) for(n in 0 until blocks-1){ // Store Cn-1 val temp = Array(4){Array(4){0}} copy(state[n],temp) // Pn = Cn-1 xor D(Kn,Cn) addRoundKey(state[n],numOfRound) for(i in numOfRound-1 downTo 1){ invShiftRow(state[n]) invSubState(state[n]) addRoundKey(state[n],i) state[n] = invMixColumn(state[n]) } invShiftRow(state[n]) invSubState(state[n]) addRoundKey(state[n],0) xor4Words(state[n],iVTemp) iVTemp = temp } return intArrayToPlainText(state,blocks-1) } }
graph-tree-analyser/src/test/kotlin/ru/dmitriyt/graphtreeanalyser/ReducedTreePack2TypeSubGraphs.kt
2285201469
package ru.dmitriyt.graphtreeanalyser import org.junit.jupiter.api.Test import ru.dmitriyt.graphtreeanalyser.data.GraphCache import ru.dmitriyt.graphtreeanalyser.data.TreeUtil import ru.dmitriyt.graphtreeanalyser.data.algorithm.ReducedTreePack2Type import ru.dmitriyt.graphtreeanalyser.data.algorithm.ReducedTreePackEquals1 import kotlin.test.assertEquals class ReducedTreePack2TypeSubGraphs { // [:H`ESgp`^, :H`EKWTjB, :H`EKWT`B, :H`EKIOlB, :H`EKIO`B] @Test fun test() { val graph6 = ":H`ESgp`^" val type = ReducedTreePack2Type.solve(GraphCache[graph6]) assertEquals(1, type) } }
graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/Args.kt
2960125869
package ru.dmitriyt.graphtreeanalyser class Args( val n: Int, val isMulti: Boolean = DEFAULT_IS_MULTI, val partSize: Int = DEFAULT_PART_SIZE, val useCache: Boolean = false, ) { companion object { const val DEFAULT_IS_MULTI = false const val DEFAULT_PART_SIZE = 64 } }
graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/Main.kt
113726303
package ru.dmitriyt.graphtreeanalyser import kotlinx.coroutines.runBlocking import ru.dmitriyt.graphtreeanalyser.data.algorithm.ReducedTreePack2Type import ru.dmitriyt.graphtreeanalyser.data.algorithm.ReducedTreePackEquals2 import ru.dmitriyt.graphtreeanalyser.presentation.graphs fun main(rawArgs: Array<String>): Unit = runBlocking { // repeat(20) { // val args = ArgsManager(rawArgs).parse() val args = Args( n = 12, isMulti = 12 > 10, ) graphs(n = args.n) { multiThreadingEnabled = args.isMulti generate(generator = "gentreeg") .filter(ReducedTreePackEquals2) .apply { calculateInvariant(ReducedTreePack2Type) } } // } }
graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/AbstractGraphCode.kt
3592977748
package ru.dmitriyt.graphtreeanalyser.data sealed class AbstractGraphCode { data class SingleComponent(val code: List<Int>) : AbstractGraphCode() data class MultiComponent(val codes: List<List<Int>>) : AbstractGraphCode() }
graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/repository/SolveRepository.kt
2148973004
package ru.dmitriyt.graphtreeanalyser.data.repository import com.google.gson.GsonBuilder import com.google.gson.reflect.TypeToken import ru.dmitriyt.graphtreeanalyser.domain.SolveResult import ru.dmitriyt.graphtreeanalyser.domain.model.GraphResult import ru.dmitriyt.graphtreeanalyser.domain.model.GraphTaskInfo import java.io.File object SolveRepository { private val solveStorage = File("results").apply { if (!exists()) { mkdir() } } private val gson = GsonBuilder().setPrettyPrinting().create() fun get(graphTaskInfo: GraphTaskInfo, n: Int): SolveResult? { val file = getSolveFile(graphTaskInfo, n) if (!file.exists()) return null return runCatching { when (graphTaskInfo) { is GraphTaskInfo.Condition -> { val typeToken = object : TypeToken<List<String>>() {}.type SolveResult.Condition( graphs = gson.fromJson(file.readLines().joinToString("\n"), typeToken), ) } is GraphTaskInfo.Invariant -> { val typeToken = object : TypeToken<Map<String, Int>>() {}.type SolveResult.Invariant( invariants = gson.fromJson<Map<String, Int>>(file.readLines().joinToString("\n"), typeToken) .map { GraphResult(it.key, it.value) }, ) } } } .onFailure { it.printStackTrace() } .getOrNull() } fun set(graphTaskInfo: GraphTaskInfo, n: Int, solveResult: SolveResult) { val file = getSolveFile(graphTaskInfo, n) file.createNewFile() when (solveResult) { is SolveResult.Condition -> { file.writeText(gson.toJson(solveResult.graphs)) } is SolveResult.Invariant -> { file.writeText(gson.toJson(solveResult.invariants.map { it.graph6 to it.invariant }.toMap())) } } } private fun getSolveFile(graphTaskInfo: GraphTaskInfo, n: Int): File { val graphTaskName = when (graphTaskInfo) { is GraphTaskInfo.Invariant -> graphTaskInfo.task.toString() is GraphTaskInfo.Condition -> graphTaskInfo.task.toString() } return File(solveStorage, "${graphTaskName}_$n.json") } }
graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/TreeUtil.kt
1448146436
package ru.dmitriyt.graphtreeanalyser.data fun Graph.getAbstractCode(): AbstractGraphCode { val components = getComponents() fun getTreeCode(tree: Graph): List<Int> { val center = TreeUtil.getTreeCenter(tree) return TreeUtil.getCanonicalCode(tree, center) } return if (components.size == 1) { AbstractGraphCode.SingleComponent(getTreeCode(components.first())) } else { AbstractGraphCode.MultiComponent(components.map { getTreeCode(it) }.sortedBy { it.toCodeString() }) } } fun Graph.getComponents(): List<Graph> { val components = mutableListOf<List<Int>>() val vertexes = mapList.keys val visited = mutableMapOf<Int, Boolean>() vertexes.forEach { visited[it] = false } while (!visited.all { it.value }) { val componentVertexes = TreeUtil.dfsWithoutEdge(this, vertexes.first { visited[it] == false }, -1) componentVertexes.forEach { visited[it] = true } components.add(componentVertexes) } return components.map { componentVertexes -> Graph( mapList.filter { componentVertexes.contains(it.key) }.map { entry -> entry.key to entry.value.filter { componentVertexes.contains(it) } }.toMap() ) } } object TreeUtil { fun bfs(g: Graph, source: Int): List<Int> { val d = MutableList(g.n) { Int.MAX_VALUE } d[source] = 0 val q = ArrayDeque<Int>() q.addLast(source) while (q.isNotEmpty()) { val u = q.removeLast() g.mapList[u].orEmpty().forEach { v -> if (d[v] == Int.MAX_VALUE) { d[v] = d[u] + 1 q.addLast(v) } } } return d } fun getTreeCenterVertexes(g: Graph): Set<Int> { val actualVertexes = g.mapList.keys.toMutableSet() while (actualVertexes.size > 2) { val vertexesToRemove = mutableListOf<Int>() g.mapList.forEach { (vertex, vertexes) -> if (actualVertexes.contains(vertex)) { if (vertexes.count { actualVertexes.contains(it) } == 1) { vertexesToRemove.add(vertex) } } } vertexesToRemove.forEach { vertex -> actualVertexes.remove(vertex) } } return actualVertexes } fun getTreeCenter(g: Graph): Int { val actualVertexes = getTreeCenterVertexes(g) if (actualVertexes.size == 1) { return actualVertexes.first() } val center1 = actualVertexes.first() val center2 = actualVertexes.last() val graph1Vertexes = dfsWithoutEdge(g, center1, center2) val graph2Vertexes = dfsWithoutEdge(g, center2, center1) if (graph1Vertexes.size < graph2Vertexes.size) { return center1 } if (graph2Vertexes.size < graph1Vertexes.size) { return center2 } val graph1 = g.filterVertexes { graph1Vertexes.contains(it) } val graph2 = g.filterVertexes { graph2Vertexes.contains(it) } return if (getCanonicalCode(graph1, center1).toCodeString() >= getCanonicalCode( graph2, center2 ).toCodeString() ) { center1 } else { center2 } } fun dfsWithoutEdge(g: Graph, start: Int, skip: Int): List<Int> { val visited = mutableMapOf<Int, Boolean>() fun dfs(u: Int) { visited[u] = true g.mapList[u]?.forEach { vertex -> if (vertex != skip && visited[vertex] != true) { dfs(vertex) } } } dfs(start) return visited.filter { it.value }.keys.toList() } fun getCanonicalCode(g: Graph, center: Int): List<Int> = try { val codes = g.mapList.map { entry -> entry.key to mutableListOf<Int>() }.toMap().toMutableMap() val leaves = g.getLeaves() leaves.forEach { vertex -> codes[vertex]?.add(1) } val levels = dijkstra(g, center) val used = mutableListOf<Int>() g.mapList.keys.forEach { i -> if (codes[i]?.isEmpty() == true && i != center) { used.add(i) codeHelper(g, center, codes, i, null, used, levels) } } var count = 1 repeat(g.mapList[center]!!.size) { i -> count += codes[g.mapList[center]!![i]]?.get(0) ?: 0 } codes[center]?.add(count) val h = mutableListOf<List<Int>>() repeat(g.mapList[center]!!.size) { i -> h.add(codes[g.mapList[center]?.get(i)]!!) } h.sortBy { it.toCodeString() } h.forEach { hi -> hi.forEach { hij -> codes[center]?.add(hij) } } val code = mutableListOf<Int>() codes[center]?.forEach { code.add(it) } code } catch (e: Exception) { throw e } private fun codeHelper( g: Graph, center: Int, codes: MutableMap<Int, MutableList<Int>>, start: Int, parent: Int?, used: MutableList<Int>, levels: Map<Int, Int> ) { g.mapList[start]?.forEach { v -> if (v != center && codes[v]?.size == 0 && v != parent && !used.contains(v) && levels[v]!! >= levels[start]!!) { codeHelper(g, center, codes, v, parent, used, levels) } } var count = 1 g.mapList[start]?.forEach { v -> if (v != parent && v != center && levels[v]!! >= levels[start]!!) { count += codes[v]?.get(0)!! } } codes[start]?.add(count) val h = mutableListOf<List<Int>>() g.mapList[start]?.forEach { v -> if (v != parent && v != center && levels[v]!! >= levels[start]!!) { h.add(codes[v].orEmpty()) } } h.sortBy { it.toCodeString() } h.forEach { hi -> hi.forEach { hij -> codes[start]?.add(hij) } } } private fun dijkstra(g: Graph, center: Int): Map<Int, Int> { val used = mutableSetOf<Int>() val d = g.mapList.map { entry -> entry.key to Int.MAX_VALUE }.toMap().toMutableMap() d[center] = 0 repeat(g.mapList.size) { var v: Int? = null g.mapList.keys.forEach { j -> if (!used.contains(j) && (v == null || d[j]!! < d[v]!!)) { v = j } } if (v == null) { return d } used.add(v!!) g.mapList[v]?.forEach { j -> if (d[v]!! + 1 < d[j]!!) { d[j] = d[v]!! + 1 } } } return d } } fun List<Int>.toCodeString(): String { return map { 'a' + it }.joinToString("") } fun Graph.getLeaves(): List<Int> { val leaves = mutableListOf<Int>() mapList.forEach { (vertex, vertexes) -> if (vertexes.size == 1) { leaves.add(vertex) } } return leaves }
graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/AbstractCondition.kt
3834714781
package ru.dmitriyt.graphtreeanalyser.data.algorithm import ru.dmitriyt.graphtreeanalyser.data.Graph import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphCondition import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphInvariant open class AbstractCondition(private val graphInvariant: GraphInvariant, private val invariantValue: Int) : GraphCondition { override fun check(graph: Graph): Boolean { return graphInvariant.solve(graph) == invariantValue } }
graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/LeavesCount.kt
2444742619
package ru.dmitriyt.graphtreeanalyser.data.algorithm import ru.dmitriyt.graphtreeanalyser.data.Graph import ru.dmitriyt.graphtreeanalyser.data.getLeaves import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphInvariant data object LeavesCount : GraphInvariant { override fun solve(graph: Graph): Int { return graph.getLeaves().size } }
graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/TreeCenterSizeEquals1.kt
3048121768
package ru.dmitriyt.graphtreeanalyser.data.algorithm data object TreeCenterSizeEquals1 : AbstractCondition(graphInvariant = TreeCenterSize, invariantValue = 1)
graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/TreeRadius.kt
517861763
package ru.dmitriyt.graphtreeanalyser.data.algorithm import ru.dmitriyt.graphtreeanalyser.data.Graph import ru.dmitriyt.graphtreeanalyser.data.TreeUtil.bfs import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphInvariant data object TreeRadius : GraphInvariant { override fun solve(graph: Graph): Int { val e = graph.mapList.keys.map { bfs(graph, it).max() } return e.min() } }
graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/ReducedTreePackEquals2.kt
145180486
package ru.dmitriyt.graphtreeanalyser.data.algorithm data object ReducedTreePackEquals2 : AbstractCondition(graphInvariant = ReducedTreePack, invariantValue = 2)
graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/TreeIsStarBicentral.kt
3811171220
package ru.dmitriyt.graphtreeanalyser.data.algorithm import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphCondition import ru.dmitriyt.graphtreeanalyser.presentation.and data object TreeIsStarBicentral : GraphCondition by (ReducedTreePackEquals1 and TreeCenterSizeEquals2)
graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/TreeCenterSize.kt
1307197563
package ru.dmitriyt.graphtreeanalyser.data.algorithm import ru.dmitriyt.graphtreeanalyser.data.Graph import ru.dmitriyt.graphtreeanalyser.data.TreeUtil import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphInvariant data object TreeCenterSize : GraphInvariant { override fun solve(graph: Graph): Int { return TreeUtil.getTreeCenterVertexes(graph).size } }
graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/ReducedTreePackEquals1.kt
4229454435
package ru.dmitriyt.graphtreeanalyser.data.algorithm data object ReducedTreePackEquals1 : AbstractCondition(graphInvariant = ReducedTreePack, invariantValue = 1)
graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/TreeDiameter.kt
1386781881
package ru.dmitriyt.graphtreeanalyser.data.algorithm import ru.dmitriyt.graphtreeanalyser.data.Graph import ru.dmitriyt.graphtreeanalyser.data.TreeUtil.bfs import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphInvariant data object TreeDiameter : GraphInvariant { override fun solve(graph: Graph): Int { val u = bfs(graph, 0).withIndex().maxBy { it.value }.index return bfs(graph, u).max() } }
graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/ReducedTreePack.kt
35483751
package ru.dmitriyt.graphtreeanalyser.data.algorithm import ru.dmitriyt.graphtreeanalyser.data.AbstractGraphCode import ru.dmitriyt.graphtreeanalyser.data.Graph import ru.dmitriyt.graphtreeanalyser.data.getAbstractCode import ru.dmitriyt.graphtreeanalyser.data.getLeaves import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphInvariant data object ReducedTreePack : GraphInvariant { override fun solve(graph: Graph): Int { val treePack = mutableListOf<AbstractGraphCode>() val leaves = graph.getLeaves() leaves.forEach { vertex -> val newGraph = graph.filterVertexes { it != vertex } treePack.add(newGraph.getAbstractCode()) } return treePack.toSet().size } }
graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/TreeCenterSizeEquals2.kt
1814221767
package ru.dmitriyt.graphtreeanalyser.data.algorithm data object TreeCenterSizeEquals2 : AbstractCondition(graphInvariant = TreeCenterSize, invariantValue = 2)
graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/TreeIsStarCentral.kt
3923409644
package ru.dmitriyt.graphtreeanalyser.data.algorithm import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphCondition import ru.dmitriyt.graphtreeanalyser.presentation.and data object TreeIsStarCentral : GraphCondition by (ReducedTreePackEquals1 and TreeCenterSizeEquals1)
graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/algorithm/ReducedTreePack2Type.kt
129165146
package ru.dmitriyt.graphtreeanalyser.data.algorithm import ru.dmitriyt.graphtreeanalyser.data.AbstractGraphCode import ru.dmitriyt.graphtreeanalyser.data.Graph import ru.dmitriyt.graphtreeanalyser.data.TreeUtil import ru.dmitriyt.graphtreeanalyser.data.getAbstractCode import ru.dmitriyt.graphtreeanalyser.data.getLeaves import ru.dmitriyt.graphtreeanalyser.domain.Logger import ru.dmitriyt.graphtreeanalyser.domain.algorithm.GraphInvariant data object ReducedTreePack2Type : GraphInvariant { override fun solve(graph: Graph): Int { val type = getGraphType(graph) println("GRAPH_TYPE = $type") return type } private fun getGraphType(graph: Graph): Int { val graphs = getScSbSubGraphs(graph) ?: run { // получили больше двух компонент SC/SB Logger.e("получили больше двух компонент SC/SB") return 0 } if (graphs.size == 2) { // нашли два каких то подграфа SC или SB val graph1 = graphs[0] val graph2 = graphs[1] if (TreeIsStarCentral.check(graph1) && TreeIsStarCentral.check(graph2)) { // два SC графа // проверим что пересекаются они только по цепи val commonVertexes = graph1.mapList.keys.toSet().intersect(graph2.mapList.keys.toSet()) if (commonVertexes.size == 1) { // это путь нулевой длины - точка пересечения двух SC Logger.i("это путь нулевой длины - точка пересечения двух SC") return 1 } else if (commonVertexes.isNotEmpty()) { // SC1 и SC2 с общей частью больше чем 1 вершина, и это по идее тип 3, // потом надо будет доработать проверки исключения других графов, если будут Logger.i("SC1 и SC2 с общей частью больше чем 1 вершина") return 3 } else { // два SC соединены через цепь (цепь в них не входит по этой проге) val overVertexes = graph.mapList.keys - graph1.mapList.keys - graph2.mapList.keys if (isPath(graph, overVertexes) && isPathConnectedToCenterOfSCB(graph, graph1, overVertexes) && isPathConnectedToCenterOfSCB(graph, graph2, overVertexes) ) { Logger.i("два SC соединены через цепь") return 1 } else { val center1 = TreeUtil.getTreeCenterVertexes(graph1).first() val center2 = TreeUtil.getTreeCenterVertexes(graph2).first() if (graph.mapList[center1].orEmpty().contains(center2)) { // два SC соединены просто друг с другом за вершины через нулевую цепь Logger.i("два SC соединены просто друг с другом за вершины через нулевую цепь") return 1 } else { Logger.e("нашли два SC, но они не соединены через цепь (возможно нулевую)") // нашли два SC, но они не соединены через цепь (возможно нулевую) } } } } else if (TreeIsStarBicentral.check(graph1) && TreeIsStarBicentral.check(graph2)) { // два BC графа val center1 = TreeUtil.getTreeCenterVertexes(graph1) val center2 = TreeUtil.getTreeCenterVertexes(graph2) if (center1 == center2) { // а тут есть варианты, мы нашли SB и SB с одинаковым центром, но вдруг у них еще есть другая общая часть val commonVertexes = graph1.mapList.keys.toSet().intersect(graph2.mapList.keys.toSet()) if (commonVertexes.size > 2) { // по идее тут общая часть больше чем две вершины центральных, но больше ничего не проверял по типу 4 return 4 } else { return 2 } } else { Logger.e("непонятная пока что штука - SB и SB, которые имеют разный центр, по идее, такого не может быть") // непонятная пока что штука - SB и SB, которые имеют разный центр, по идее, такого не может быть } } else { // тут неправильно считаем графы, на примере n9/18 Logger.e("совершенно непонятная штука, по идее такой не должно быть (SC и SB)") Logger.e("${getGraphStarType(graph1)} : ${graph1.mapList.keys} and ${getGraphStarType(graph2)} ${graph2.mapList.keys}") // совершенно непонятная штука, по идее такой не должно быть (SC и SB) } } else if (graphs.size == 1) { // может быть случай, когда к цепи крепится SC за середину, т.е. цепь это вырожденный случай второго SC (так как только один лист) val graph1 = graphs[0] val overVertexes = graph.mapList.keys - graph1.mapList.keys if (TreeIsStarCentral.check(graph1) && isPath(graph, overVertexes) && isPathConnectedToCenterOfSCB(graph, graph1, overVertexes) ) { Logger.i("к цепи крепится SC за середину") return 1 } else { Logger.e("нашли 1 граф SC/SB, но это не SC/SB + P") // нашли 1 граф, но это не SC + P } } else { Logger.e("нашли > 2 графов, вообще непонятно что такое") // нашли > 2 графов, вообще непонятно что такое } return 0 } /** * Получение графов SC/SB, которые имеются в графе [graph] с приведенной колодой 2 (по подобным листьями) * Идем и отсекаем листья другого подобия, пока не получим SC/SB */ fun getScSbSubGraphs(graph: Graph): List<Graph>? { val leaveToSubgraphCode = mutableListOf<Pair<Int, AbstractGraphCode>>() graph.getLeaves().forEach { vertex -> val newGraph = graph.filterVertexes { it != vertex } leaveToSubgraphCode.add(vertex to newGraph.getAbstractCode()) } val sameLeavesGroups = leaveToSubgraphCode.groupBy { it.second }.map { (_, value) -> value.map { it.first } } Logger.i("sameLeavesGroups:") if (sameLeavesGroups.size > 2) { // получили больше 2х подобных листьев, значит это не граф с количеством приведенной колоды 2 return null } val graphs = sameLeavesGroups.mapNotNull { leavesGroup -> Logger.i("sameLeavesGroup $leavesGroup") // leavesGroup - вершины, при удалении которых получаются подобные графы // т.е. будем убирать все остальные листья, пока не получим дерево с количеством приведенной колоды 1 var currentGraph = graph.copy() var otherLeaves = currentGraph.getLeaves().toSet() - leavesGroup.toSet() var forceStop = false while ( !(ReducedTreePackEquals1.check(currentGraph) && // ищем граф SC или SB currentGraph.getLeaves().toSet() == leavesGroup.toSet()) && // чтобы листья были только те, что в группе otherLeaves.isNotEmpty() && // пока есть что откусывать !forceStop ) { val oldGraph = currentGraph currentGraph = currentGraph.filterVertexes { !otherLeaves.contains(it) } forceStop = oldGraph == currentGraph // остановимся, если граф не поменялся otherLeaves = currentGraph.getLeaves().toSet() - leavesGroup.toSet() } // нашли граф SC или SB, (если нет, то потом разберемся с этим кейсом currentGraph.takeIf { ReducedTreePackEquals1.check(currentGraph) } } return graphs } fun getPathStartEnd(g: Graph, path: Set<Int>): Pair<Int, Int> { if (path.isEmpty()) { error("path is empty") } if (path.size == 1) return path.first() to path.first() val (start, end) = path.filter { vertex -> path.count { g.mapList[vertex]?.contains(it) == true } == 1 } return start to end } fun isPath(g: Graph, path: Set<Int>): Boolean { if (path.isEmpty()) return false if (path.size == 1) return true val mutablePath = path.toMutableSet() val startVertex = path.find { vertex -> path.count { g.mapList[vertex]?.contains(it) == true } == 1 } var currentVertex = startVertex mutablePath.remove(currentVertex) while (currentVertex != null) { currentVertex = g.mapList[currentVertex].orEmpty().find { mutablePath.contains(it) } mutablePath.remove(currentVertex) } return mutablePath.isEmpty() } private fun isPathConnectedToCenterOfSCB(g: Graph, scb: Graph, path: Set<Int>): Boolean { val graph1Center = TreeUtil.getTreeCenterVertexes(scb).first() return getPathStartEnd(g, path).let { (pathStart, pathEnd) -> g.mapList[graph1Center].orEmpty().let { it.contains(pathStart) || it.contains(pathEnd) } } } private fun getGraphStarType(graph: Graph): String { if (TreeIsStarCentral.check(graph)) { return "SC" } else if (TreeIsStarBicentral.check(graph)) { return "SB" } else { return "ER" } } }
graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/ByteReader6.kt
2182366193
package ru.dmitriyt.graphtreeanalyser.data internal class ByteReader6(s6: String) { private val mBytes: ByteArray private val mSize: Int private var mPos: Int private var mBit = 0 init { mBytes = s6.toByteArray() mSize = s6.length mPos = mBit } // ! whether k bits are available fun haveBits(k: Int): Boolean { return mPos + (mBit + k - 1) / 6 < mSize } // ! return the next integer encoded in graph6 fun getNumber(): Int { assert(mPos < mSize) var c = mBytes[mPos] assert(c >= 63) c = (c - 63).toByte() ++mPos if (c < 126) return c.toInt() assert(false) return 0 } // ! return the next bit encoded in graph6 fun getBit(): Int { assert(mPos < mSize) var c = mBytes[mPos] assert(c >= 63) c = (c - 63).toByte() c = (c.toInt() shr 5 - mBit).toByte() mBit++ if (mBit == 6) { mPos++ mBit = 0 } return c.toInt() and 0x01 } // ! return the next bits as an integer fun getBits(k: Int): Int { var v = 0 for (i in 0 until k) { v *= 2 v += getBit() } return v } }
graph-tree-analyser/src/main/kotlin/ru/dmitriyt/graphtreeanalyser/data/GraphCache.kt
345405774
package ru.dmitriyt.graphtreeanalyser.data import java.util.concurrent.ConcurrentHashMap object GraphCache { private val cache = ConcurrentHashMap<String, Graph>() operator fun get(graph6: String): Graph { return cache[graph6] ?: run { val graph = Graph.fromSparse6(graph6) cache[graph6] = graph graph } } }