content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package ir.ehsan.asmrcarousel.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 AsmrCarouselTheme( 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 ) }
Blurred-Carousel/app/src/main/java/ir/ehsan/asmrcarousel/ui/theme/Theme.kt
3873800785
package ir.ehsan.asmrcarousel.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 ) */ )
Blurred-Carousel/app/src/main/java/ir/ehsan/asmrcarousel/ui/theme/Type.kt
3198048671
package ir.ehsan.asmrcarousel import android.graphics.RenderEffect import android.graphics.RuntimeShader import android.graphics.Shader import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.annotation.RequiresApi import androidx.compose.animation.core.Spring import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.spring import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer 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.foundation.layout.size import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.PagerState import androidx.compose.foundation.pager.VerticalPager import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Star import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.scale import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asComposeRenderEffect import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.vector.rememberVectorPainter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.zIndex import ir.ehsan.asmrcarousel.ui.theme.AsmrCarouselTheme import kotlinx.coroutines.flow.collect import java.util.stream.LongStream.Builder import kotlin.math.ceil import kotlin.math.floor import kotlin.math.roundToInt class MainActivity : ComponentActivity() { @RequiresApi(Build.VERSION_CODES.TIRAMISU) @OptIn(ExperimentalFoundationApi::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AsmrCarouselTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { val pagerState = rememberPagerState(pageCount = { locations.count() }) Column { HorizontalPager( state = pagerState, modifier = Modifier .weight(.7f) .padding(top = 32.dp), pageSpacing = 1.dp, beyondBoundsPageCount = locations.count() ) { page -> Box(modifier = Modifier .zIndex(page * 2f) .padding( start = 64.dp, end = 32.dp ) .graphicsLayer { val startOffset = pagerState.startOffsetForPage(page) translationX = size.width * (startOffset * .99f) alpha = (2f - startOffset) / 2 val blur = (startOffset * 20).coerceAtLeast(.1f) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { renderEffect = RenderEffect .createBlurEffect( blur, blur, Shader.TileMode.DECAL ) .asComposeRenderEffect() } val scale = 1f - (startOffset * .1f) scaleX = scale scaleY = scale } .clip(RoundedCornerShape(20.dp))) { Image( painter = painterResource(id = locations[page].image), contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize() ) } } Row( modifier = Modifier .padding(horizontal = 16.dp) .fillMaxWidth() .weight(.3f), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { val verticalState = rememberPagerState(pageCount = { locations.count() }) VerticalPager( state = verticalState, modifier = Modifier .weight(1f) .height(86.dp), userScrollEnabled = false, horizontalAlignment = Alignment.Start ) { page -> Column(verticalArrangement = Arrangement.Center) { Text( text = locations[page].title, style = MaterialTheme.typography.headlineLarge.copy( fontWeight = FontWeight.Thin, fontSize = 28.sp ) ) Spacer(modifier = Modifier.height(8.dp)) Text( text = locations[page].subtitle, style = MaterialTheme.typography.bodyLarge.copy( fontWeight = FontWeight.Bold, fontSize = 14.sp ) ) } } LaunchedEffect(Unit) { snapshotFlow { Pair( pagerState.currentPage, pagerState.currentPageOffsetFraction ) }.collect { (page, offset) -> verticalState.scrollToPage(page, offset) } } val interpolatedRating by remember { derivedStateOf { val position = pagerState.offsetForPage(0) val from = floor(position).roundToInt() val to = ceil(position).roundToInt() val fromRating = locations[from].rating.toFloat() val toRating = locations[to].rating.toFloat() val fraction = position - position.toInt() fromRating + ((toRating - fromRating) * fraction) } } RatingBar(rating = interpolatedRating) } } } } } } } @Composable fun RatingBar(modifier: Modifier = Modifier, rating: Float) { Row(modifier = Modifier) { for (i in 1..5) { val animatedScale by animateFloatAsState( targetValue = if (floor(rating) >= i) { 1f } else if (ceil(rating) < i) { 0f } else { rating - rating.toInt() }, animationSpec = spring( stiffness = Spring.StiffnessMedium ) ) Box(contentAlignment = Alignment.Center) { Icon( painter = rememberVectorPainter(image = Icons.Rounded.Star), contentDescription = null, modifier = Modifier.alpha(.1f) ) Icon( painter = rememberVectorPainter(image = Icons.Rounded.Star), contentDescription = null, modifier = Modifier.scale(animatedScale), tint = Color(0xFFCA9220) ) } } } } @OptIn(ExperimentalFoundationApi::class) fun PagerState.offsetForPage(page: Int) = (currentPage - page) + currentPageOffsetFraction @OptIn(ExperimentalFoundationApi::class) fun PagerState.startOffsetForPage(page: Int) = offsetForPage(page).coerceAtLeast(0f)
Blurred-Carousel/app/src/main/java/ir/ehsan/asmrcarousel/MainActivity.kt
2611524187
package ir.ehsan.asmrcarousel data class Location( val image:Int, val title:String, val subtitle:String, val rating:Int, ) val locations = listOf( Location( image = R.drawable.tabriz, title = "Tabriz", subtitle = "A city in iran", rating = 5 ), Location( image = R.drawable.dubai, subtitle = "A city in United Arab Emirates", rating = 3, title = "Dubai" ), Location( image = R.drawable.los_angeles, title = "Los Angeles", rating = 4, subtitle = "A sprawling Southern California city", ), Location( image = R.drawable.london, title = "London", rating = 3, subtitle = "Capital of England and the United Kingdom", ), Location( image = R.drawable.sweden, title = "Sweden", rating = 5, subtitle = "A beautiful country", ), Location( image = R.drawable.kazan, title = "Kazan", rating = 2, subtitle = "A city in russia", ), )
Blurred-Carousel/app/src/main/java/ir/ehsan/asmrcarousel/Location.kt
1816223666
import androidx.compose.ui.window.ComposeUIViewController fun MainViewController() = ComposeUIViewController { App() }
MoviesMultiplatform/composeApp/src/iosMain/kotlin/MainViewController.kt
3500059733
import platform.UIKit.UIDevice class IOSPlatform: Platform { override val name: String = UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersion } actual fun getPlatform(): Platform = IOSPlatform()
MoviesMultiplatform/composeApp/src/iosMain/kotlin/Platform.ios.kt
110407275
import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.material.Text 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 co.touchlab.kermit.Logger import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.painterResource @OptIn(ExperimentalResourceApi::class) @Composable fun App() { MaterialTheme { var showContent by remember { mutableStateOf(false) } val greeting = remember { Greeting().greet() } Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { Button(onClick = { logMe()}) { Text("Click me!") } AnimatedVisibility(showContent) { Column( Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { Image(painterResource("compose-multiplatform.xml"), null) Text("Compose: $greeting") } } } } } private fun logMe() { Logger.i("myTag") { "myMessage" } }
MoviesMultiplatform/composeApp/src/commonMain/kotlin/App.kt
1829236148
interface Platform { val name: String } expect fun getPlatform(): Platform
MoviesMultiplatform/composeApp/src/commonMain/kotlin/Platform.kt
960794953
class Greeting { private val platform = getPlatform() fun greet(): String { return "Hello, ${platform.name}!" } }
MoviesMultiplatform/composeApp/src/commonMain/kotlin/Greeting.kt
2562376394
package nick.mirosh.cinema import App import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { App() } } } @Preview @Composable fun AppAndroidPreview() { App() }
MoviesMultiplatform/composeApp/src/androidMain/kotlin/nick/mirosh/cinema/MainActivity.kt
1050392727
import android.os.Build class AndroidPlatform : Platform { override val name: String = "Android ${Build.VERSION.SDK_INT}" } actual fun getPlatform(): Platform = AndroidPlatform()
MoviesMultiplatform/composeApp/src/androidMain/kotlin/Platform.android.kt
3472575554
package com.example.messageshareapp 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.messageshareapp", appContext.packageName) } }
Message-Share-App/app/src/androidTest/java/com/example/messageshareapp/ExampleInstrumentedTest.kt
2847873654
package com.example.messageshareapp 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) } }
Message-Share-App/app/src/test/java/com/example/messageshareapp/ExampleUnitTest.kt
1498957046
package com.example.messageshareapp import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.messageshareapp.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.btnShowToast.setOnClickListener { Log.i("Main Activity", "Toast Button was clicked") Toast.makeText(this, "Button was clicked !!", Toast.LENGTH_LONG).show() } binding.btnSendMsgToNextActivity.setOnClickListener { val message: String = binding.etUserMessage.text.toString() Toast.makeText(this, message, Toast.LENGTH_SHORT).show() val intent = Intent(this, SecondActivity::class.java) intent.putExtra("user_message", message) startActivity(intent) } binding.btnShareToOtherApps.setOnClickListener { val message: String = binding.etUserMessage.text.toString() val intent = Intent() intent.action = Intent.ACTION_SEND intent.putExtra(Intent.EXTRA_TEXT, message) intent.type = "text/plain" startActivity(Intent.createChooser(intent, "Share WithHe : ")) } binding.btnRecyclerviewDemo.setOnClickListener { val intent = Intent(this, HobbiesActivity::class.java) } } }
Message-Share-App/app/src/main/java/com/example/messageshareapp/MainActivity.kt
354232264
package com.example.messageshareapp import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.messageshareapp.databinding.ActivitySecondBinding class SecondActivity : AppCompatActivity(){ private lateinit var binding: ActivitySecondBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySecondBinding.inflate(layoutInflater) setContentView(binding.root) val bundle: Bundle? = intent.extras val msg = bundle!!.getString("user_message") Toast.makeText(this, msg, Toast.LENGTH_SHORT).show() binding.txtvUsermessage.text = msg } }
Message-Share-App/app/src/main/java/com/example/messageshareapp/SecondActivity.kt
3247929780
package com.example.messageshareapp import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.example.messageshareapp.databinding.ActivityHobbiesBinding class HobbiesActivity : AppCompatActivity(){ private lateinit var binding: ActivityHobbiesBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityHobbiesBinding.inflate(layoutInflater) setContentView(binding.root) } }
Message-Share-App/app/src/main/java/com/example/messageshareapp/HobbiesActivity.kt
2999313954
package com.example.notesapplication 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.notesapplication", appContext.packageName) } }
NotesApplication/app/src/androidTest/java/com/example/notesapplication/ExampleInstrumentedTest.kt
3547696338
package com.example.notesapplication 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) } }
NotesApplication/app/src/test/java/com/example/notesapplication/ExampleUnitTest.kt
2351116410
package com.example.notesapplication import android.graphics.Bitmap import androidx.lifecycle.ViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow class MainViewModel: ViewModel() { private val _bitmaps = MutableStateFlow<List<Bitmap>>(emptyList()) val bitmaps = _bitmaps.asStateFlow() fun onTakePhoto(bitmap: Bitmap) { _bitmaps.value += bitmap } }
NotesApplication/app/src/main/java/com/example/notesapplication/MainViewModel.kt
3668211162
package com.example.notesapplication.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)
NotesApplication/app/src/main/java/com/example/notesapplication/ui/theme/Color.kt
1562069227
package com.example.notesapplication.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 NotesApplicationTheme( 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 ) }
NotesApplication/app/src/main/java/com/example/notesapplication/ui/theme/Theme.kt
1998437733
package com.example.notesapplication.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 ) */ )
NotesApplication/app/src/main/java/com/example/notesapplication/ui/theme/Type.kt
1618706786
package com.example.notesapplication import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch class SplashViewModel: ViewModel() { private val _isReady = MutableStateFlow(false) val isReady = _isReady.asStateFlow() init { viewModelScope.launch { delay(3000L) _isReady.value = true } } }
NotesApplication/app/src/main/java/com/example/notesapplication/SplashViewModel.kt
1054490007
package com.example.notesapplication import android.Manifest import android.animation.ObjectAnimator import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.Matrix import android.os.Bundle import android.util.Log import android.view.View import android.view.animation.AccelerateDecelerateInterpolator import android.view.animation.OvershootInterpolator import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.camera.core.ImageCapture.OnImageCapturedCallback import androidx.camera.core.ImageCaptureException import androidx.camera.core.ImageProxy import androidx.camera.view.CameraController import androidx.camera.view.LifecycleCameraController import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Photo import androidx.compose.material.icons.filled.PhotoCamera import androidx.compose.material3.BottomSheetScaffold import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.rememberBottomSheetScaffoldState import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.core.animation.doOnEnd import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewmodel.compose.viewModel import androidx.lifecycle.viewmodel.viewModelFactory import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import androidx.room.Room import androidx.room.RoomDatabase import com.ahmedapps.roomdatabase.data.NotesDatabase //import com.ahmedapps.roomdatabase.ui.theme.RoomDatabaseTheme import com.example.notesapplication.presentation.AddNoteScreen import com.example.notesapplication.presentation.NotesScreen import com.example.notesapplication.presentation.NotesViewModel import com.example.notesapplication.Message import kotlinx.coroutines.launch class MainActivity : ComponentActivity() { private val database by lazy { Room.databaseBuilder( applicationContext, NotesDatabase::class.java, "notes.db" ).build() } private val viewModel by viewModels<NotesViewModel> ( factoryProducer = { object : ViewModelProvider.Factory { override fun<T: ViewModel> create(modelClass: Class<T>): T { return NotesViewModel(database.dao) as T } } } ) private val viewModel2 by viewModels<SplashViewModel>() @OptIn(ExperimentalMaterial3Api::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) installSplashScreen().apply { setKeepOnScreenCondition { !viewModel2.isReady.value } /*setOnExitAnimationListener { screen -> val zoomX = ObjectAnimator.ofFloat( screen.iconView, View.SCALE_X, 0.4f, 0.0f ) zoomX.interpolator = OvershootInterpolator() zoomX.duration = 500L zoomX.doOnEnd { screen.remove() } val zoomY = ObjectAnimator.ofFloat( screen.iconView, View.SCALE_Y, 0.4f, 0.0f ) zoomY.interpolator = OvershootInterpolator() zoomY.duration = 500L zoomY.doOnEnd { screen.remove() } val rotation = ObjectAnimator.ofFloat( screen.iconView, View.ROTATION, 0f, 360f ) rotation.interpolator = AccelerateDecelerateInterpolator() rotation.duration = 500L zoomX.start() zoomY.start() rotation.start() }*/ } if(!hasRequiredPermissions()) { ActivityCompat.requestPermissions( this, CAMERAX_PERMISSIONS,0 ) } setContent { MaterialTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { val state by viewModel.state.collectAsState() val navController = rememberNavController() NavHost(navController= navController, startDestination = "Conversation") { composable("Conversation") { Conversation( state = state, navController = navController, onEvent = viewModel::onEvent, messages = SampleData.conversationSample ) } composable("AddNoteScreen") { AddNoteScreen( state = state, navController = navController, onEvent = viewModel::onEvent ) } composable("Camera") { Camera( navController = navController ) } } } } } } private fun hasRequiredPermissions(): Boolean { return CAMERAX_PERMISSIONS.all { ContextCompat.checkSelfPermission( applicationContext, it ) == PackageManager.PERMISSION_GRANTED } } companion object { private val CAMERAX_PERMISSIONS = arrayOf( Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, ) } }
NotesApplication/app/src/main/java/com/example/notesapplication/MainActivity.kt
3957724413
package com.example.notesapplication import android.content.Context import android.graphics.Bitmap import android.graphics.Camera import android.graphics.Matrix import android.util.Log import androidx.camera.core.ImageCapture import androidx.camera.core.ImageCaptureException import androidx.camera.core.ImageProxy import androidx.camera.view.CameraController import androidx.camera.view.LifecycleCameraController import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Photo import androidx.compose.material.icons.filled.PhotoCamera import androidx.compose.material3.BottomSheetScaffold import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.rememberBottomSheetScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.core.content.ContextCompat import androidx.navigation.NavController import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @Composable fun Camera( navController: NavController ) { val context = LocalContext.current val scope = rememberCoroutineScope() val scaffoldState = rememberBottomSheetScaffoldState() val controller = remember { LifecycleCameraController(context).apply { setEnabledUseCases( CameraController.IMAGE_CAPTURE or CameraController.VIDEO_CAPTURE ) } } val camViewModel = androidx.lifecycle.viewmodel.compose.viewModel<MainViewModel>() val bitmaps by camViewModel.bitmaps.collectAsState() BottomSheetScaffold( scaffoldState = scaffoldState, sheetPeekHeight = 0.dp, sheetContent = { PhotoBottomSheetContent( bitmaps = bitmaps, modifier = Modifier .fillMaxWidth() ) } ) { padding -> Box( modifier = Modifier .fillMaxSize() .padding(padding) ) { CameraPreview( controller = controller, modifier = Modifier .fillMaxSize() ) Row( modifier = Modifier .fillMaxWidth() .align(Alignment.BottomCenter) .padding(16.dp), horizontalArrangement = Arrangement.SpaceAround ) { IconButton( onClick = { scope.launch { scaffoldState.bottomSheetState.expand() } }, modifier = Modifier.padding(8.dp) ) { Icon( imageVector = Icons.Default.Photo, contentDescription = "Open gallery", tint = Color.White ) } IconButton( onClick = { takePhoto( context = context, controller = controller, onPhotoTaken = camViewModel::onTakePhoto ) }, modifier = Modifier.padding(8.dp) ) { Icon( imageVector = Icons.Default.PhotoCamera, contentDescription = "Take Photo", tint = Color.White ) } } Row ( modifier = Modifier .fillMaxWidth() .align(Alignment.TopStart) .padding(16.dp), horizontalArrangement = Arrangement.Start, verticalAlignment = Alignment.CenterVertically ) { IconButton( onClick = { navController.popBackStack() }, modifier = Modifier.padding(8.dp) ) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = "Save and go back", tint = Color.White ) } } } } } private fun takePhoto( context: Context, controller: LifecycleCameraController, onPhotoTaken: (Bitmap) -> Unit ) { controller.takePicture( ContextCompat.getMainExecutor(context), object : ImageCapture.OnImageCapturedCallback() { override fun onCaptureSuccess(image: ImageProxy) { super.onCaptureSuccess(image) val matrix = Matrix().apply { postRotate(image.imageInfo.rotationDegrees.toFloat()) } val rotatedBitmap = Bitmap.createBitmap( image.toBitmap(), 0, 0, image.width, image.height, matrix, true ) onPhotoTaken(rotatedBitmap) } override fun onError(exception: ImageCaptureException) { super.onError(exception) Log.e("Camera", "Couldn't take photo: ", exception) } } ) }
NotesApplication/app/src/main/java/com/example/notesapplication/Camera.kt
798887009
package com.example.notesapplication import androidx.camera.view.LifecycleCameraController import androidx.camera.view.PreviewView import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.viewinterop.AndroidView @Composable fun CameraPreview( controller: LifecycleCameraController, modifier: Modifier = Modifier ) { val lifecycleOwner = LocalLifecycleOwner.current AndroidView( factory = { PreviewView(it).apply { this.controller = controller controller.bindToLifecycle(lifecycleOwner) } }, modifier = modifier ) }
NotesApplication/app/src/main/java/com/example/notesapplication/CameraPreview.kt
3483126267
package com.example.notesapplication import android.content.Context import android.graphics.Bitmap import android.graphics.Matrix import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.camera.core.ImageCapture import androidx.camera.core.ImageCaptureException import androidx.camera.core.ImageProxy import androidx.camera.view.CameraController import androidx.camera.view.LifecycleCameraController import androidx.compose.foundation.clickable import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.Image import androidx.compose.ui.res.painterResource import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.ui.draw.clip import androidx.compose.ui.unit.dp import androidx.compose.foundation.border import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.clickable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.animation.animateColorAsState import androidx.compose.animation.animateContentSize import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Camera import androidx.compose.material.icons.filled.Photo import androidx.compose.material.icons.filled.PhotoCamera import androidx.compose.material.icons.filled.Settings import androidx.compose.material3.BottomSheetScaffold import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.rememberBottomSheetScaffoldState import androidx.compose.runtime.collectAsState import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import androidx.core.content.ContextCompat import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import androidx.navigation.NavHostController import androidx.navigation.compose.rememberNavController import coil.compose.rememberImagePainter import com.ahmedapps.roomdatabase.data.Note import com.ahmedapps.roomdatabase.presentation.NotesEvent import com.example.notesapplication.presentation.AddNoteScreen import com.example.notesapplication.presentation.NoteState import com.example.notesapplication.presentation.NotesViewModel import kotlinx.coroutines.launch import java.io.File data class Message(val author: String, val body: String, val note: Note?) @Composable fun MessageCard( msg: Message, state: NoteState ) { Row(modifier = Modifier.padding(all = 8.dp)) { //profile picture Box( modifier = Modifier .size(40.dp) .clip(CircleShape) .border(1.5.dp, MaterialTheme.colorScheme.primary, CircleShape) .background(Color.LightGray) ) { // Display profile picture state.description.value?.let { filePath -> val profilePictureFile = File(filePath) Image( painter = rememberImagePainter(profilePictureFile), contentDescription = "Profile Picture", modifier = Modifier.fillMaxSize(), contentScale = ContentScale.Crop ) } } Spacer(modifier = Modifier.width(8.dp)) // We keep track if the message is expanded or not in this variable var isExpanded by remember { mutableStateOf(false) } // surfaceColor will be updated gradually from one color to the other val surfaceColor by animateColorAsState( if (isExpanded) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surface, ) // We toggle the isExpanded variable when we click on this Column Column(modifier = Modifier.clickable { isExpanded = !isExpanded }) { Text( text = state.title.value,//msg.author, color = MaterialTheme.colorScheme.secondary, style = MaterialTheme.typography.titleSmall ) Spacer(modifier = Modifier.height(4.dp)) Surface( shape = MaterialTheme.shapes.medium, shadowElevation = 1.dp, color = surfaceColor, modifier = Modifier .animateContentSize() .padding(1.dp) ) { Text( text = msg.body, modifier = Modifier.padding(all = 4.dp), maxLines = if (isExpanded) Int.MAX_VALUE else 1, style = MaterialTheme.typography.bodyMedium ) } } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun Conversation( navController: NavController, messages: List<Message>, state: NoteState, onEvent: (NotesEvent) -> Unit ) { LazyColumn { item { // Row to hold both buttons Row( horizontalArrangement = Arrangement.SpaceBetween, // Align items at the start and end modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { // Settings button at the top left FloatingActionButton( onClick = { navController.navigate("AddNoteScreen") } ) { Icon( imageVector = Icons.Default.Settings, contentDescription = "Settings" ) } FloatingActionButton( onClick = { navController.navigate("Camera") } ) { Icon( imageVector = Icons.Default.Camera, contentDescription = "Settings" ) } } } items(messages) { message -> MessageCard(message, state) } } }
NotesApplication/app/src/main/java/com/example/notesapplication/HomeScreen.kt
4251073807
package com.example.notesapplication /** * SampleData for Jetpack Compose Tutorial */ object SampleData { // Sample conversation data val conversationSample = listOf( Message( "Lexi", "Test...Test...Test...", null ), Message( "Lexii", """List of Android versions: |Android KitKat (API 19) |Android Lollipop (API 21) |Android Marshmallow (API 23) |Android Nougat (API 24) |Android Oreo (API 26) |Android Pie (API 28) |Android 10 (API 29) |Android 11 (API 30) |Android 12 (API 31)""".trim(), null ), Message( "Lexi", """I think Kotlin is my favorite programming language. |It's so much fun!""".trim(), null ), Message( "Lexii", "Searching for alternatives to XML layouts...", null ), Message( "Lexi", """Hey, take a look at Jetpack Compose, it's great! |It's the Android's modern toolkit for building native UI. |It simplifies and accelerates UI development on Android. |Less code, powerful tools, and intuitive Kotlin APIs :)""".trim(), null ), Message( "Lexii", "It's available from API 21+ :)", null ), Message( "Lexii", "Writing Kotlin for UI seems so natural, Compose where have you been all my life?", null ), Message( "Lexi", "Android Studio next version's name is Arctic Fox", null ), Message( "Lexii", "Android Studio Arctic Fox tooling for Compose is top notch ^_^", null ), Message( "Lexii", "I didn't know you can now run the emulator directly from Android Studio", null ), Message( "Lexi", "Compose Previews are great to check quickly how a composable layout looks like", null ), Message( "Lexii", "Previews are also interactive after enabling the experimental setting", null ), Message( "Lexi", "Have you tried writing build.gradle with KTS?", null ), ) }
NotesApplication/app/src/main/java/com/example/notesapplication/SampleData.kt
3955889714
package com.example.notesapplication import android.graphics.Bitmap import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells import androidx.compose.foundation.lazy.staggeredgrid.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.unit.dp @Composable fun PhotoBottomSheetContent( bitmaps: List<Bitmap>, modifier: Modifier = Modifier ) { if(bitmaps.isEmpty()) { Box( modifier = modifier .padding(16.dp), contentAlignment = Alignment.Center ) { Text("There are no photos yet") } } else { LazyVerticalStaggeredGrid( columns = StaggeredGridCells.Fixed(2), horizontalArrangement = Arrangement.spacedBy(16.dp), verticalItemSpacing = 16.dp, contentPadding = PaddingValues(16.dp), modifier = modifier ) { items(bitmaps) { bitmap -> Image( bitmap = bitmap.asImageBitmap(), contentDescription = null, modifier = Modifier .clip(RoundedCornerShape(10.dp)) ) } } } }
NotesApplication/app/src/main/java/com/example/notesapplication/PhotoBottomSheetContent.kt
2352635332
package com.ahmedapps.roomdatabase.data import androidx.room.Database import androidx.room.RoomDatabase @Database( entities = [Note::class], version = 1 ) abstract class NotesDatabase: RoomDatabase(){ abstract val dao: NoteDao }
NotesApplication/app/src/main/java/com/example/notesapplication/data/NotesDatabase.kt
626136242
package com.ahmedapps.roomdatabase.data import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class Note( val title: String, val description: String, // uri of profile picture val dateAdded: Long, // älä poista @PrimaryKey(autoGenerate = true) val id: Int = 0 )
NotesApplication/app/src/main/java/com/example/notesapplication/data/Note.kt
542356672
package com.ahmedapps.roomdatabase.data import androidx.room.Dao import androidx.room.Delete import androidx.room.Query import androidx.room.Upsert import kotlinx.coroutines.flow.Flow @Dao interface NoteDao { @Upsert suspend fun upsertNote(note: Note) //@Delete //suspend fun deleteNote(note: Note) @Query("SELECT * FROM note") fun getNote(): Flow<Note> @Query("SELECT * FROM note") fun getAllNotes(): Flow<List<Note>> @Query("SELECT title FROM note WHERE id = :noteId") // Adjust this query as per your requirement fun getTitleById(noteId: Long): Flow<String> /*@Query("SELECT * FROM note ORDER BY dateAdded") fun getNotesOrderdByDateAdded(): Flow<List<Note>> @Query("SELECT * FROM note ORDER BY name ASC") fun getNotesOrderdByTitle(): Flow<List<Note>>*/ }
NotesApplication/app/src/main/java/com/example/notesapplication/data/NoteDao.kt
4175694997
package com.example.notesapplication.presentation import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import com.example.notesapplication.MainActivity class Notifications(private val context: Context) { fun triggerNotification(context: Context) { val intent = Intent(context, MainActivity::class.java) val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) val builder = NotificationCompat.Builder(context, "channelId") //.setSmallIcon(R.drawable.notification_icon) .setSmallIcon(android.R.drawable.ic_dialog_info) .setContentTitle("Phone Lifted Up") .setContentText("You lifted up your phone!") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent(pendingIntent) try { with(NotificationManagerCompat.from(context)) { notify(1234, builder.build()) } } catch (e: SecurityException) { // Handle SecurityException gracefully e.printStackTrace() } } fun createNotificationChannel(context: Context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val name = "My Channel" val descriptionText = "Channel Description" val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel("channelId", name, importance).apply { description = descriptionText enableLights(true) //lightColor = Color.RED } val notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } } fun enableNotifications(context: Context) { val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notificationId = 1 val intent = Intent(context, MainActivity::class.java) val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) val notification = NotificationCompat.Builder(context, "channelId") .setSmallIcon(android.R.drawable.ic_dialog_info) .setContentTitle("Notifications Enabled") .setContentText("You can now receive notifications!") .setContentIntent(pendingIntent) //opens app .setAutoCancel(true) .setPriority(NotificationCompat.PRIORITY_HIGH) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .build() notificationManager.notify(notificationId, notification) } }
NotesApplication/app/src/main/java/com/example/notesapplication/presentation/Notifications.kt
1866817056
package com.example.notesapplication.presentation import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer 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.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.rounded.Add import androidx.compose.material.icons.rounded.Delete import androidx.compose.material.icons.rounded.Sort import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import coil.compose.rememberImagePainter import com.ahmedapps.roomdatabase.presentation.NotesEvent import com.example.notesapplication.R @OptIn(ExperimentalMaterial3Api::class) @Composable fun NotesScreen( state: NoteState, navController: NavController, onEvent: (NotesEvent) -> Unit ) { Scaffold( topBar = { Row( modifier = Modifier .fillMaxWidth() .height(55.dp) .background(MaterialTheme.colorScheme.primary) .padding(16.dp), verticalAlignment = Alignment.CenterVertically ) { Text( text = stringResource(id = R.string.app_name), modifier = Modifier.weight(1f), fontSize = 17.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onPrimary ) } }, floatingActionButton = { FloatingActionButton(onClick = { state.title.value = "" state.description.value = "" navController.navigate("Conversation") }) { Icon( imageVector = Icons.Default.Settings, contentDescription = "Settings") } } ) { paddingValues -> LazyColumn( contentPadding = paddingValues, modifier = Modifier .fillMaxSize() .padding(8.dp), verticalArrangement = Arrangement.spacedBy(16.dp) ) { items(state.notes.size) { index -> NoteItem( state = state, index = index, onEvent = onEvent ) } } } } @Composable fun NoteItem( state: NoteState, index: Int, onEvent: (NotesEvent) -> Unit ) { Row( modifier = Modifier .fillMaxWidth() .clip(RoundedCornerShape(10.dp)) .background(MaterialTheme.colorScheme.primaryContainer) .padding(12.dp) ) { Column( modifier = Modifier.weight(1f) ) { Text( text = state.notes[index].title, fontSize = 18.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onSecondaryContainer ) Spacer(modifier = Modifier.height(8.dp)) Box( modifier = Modifier.size(60.dp) .clip(CircleShape) .background(MaterialTheme.colorScheme.primary) ) { Image( painter = rememberImagePainter(state.notes[index].description), contentDescription = "Note Image", modifier = Modifier .clip(CircleShape), contentScale = ContentScale.Crop ) } } /*IconButton( onClick = { onEvent(NotesEvent.DeleteNote(state.notes[index])) } ) { Icon( imageVector = Icons.Rounded.Delete, contentDescription = "Delete Note", modifier = Modifier.size(35.dp), tint = MaterialTheme.colorScheme.onPrimaryContainer ) }*/ } }
NotesApplication/app/src/main/java/com/example/notesapplication/presentation/NotesScreen.kt
2540455303
package com.example.notesapplication.presentation import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.ContentResolver import android.content.Context import android.content.Intent import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import android.net.Uri import android.os.Build import android.util.Log import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border 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.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.rounded.Check import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import coil.compose.rememberImagePainter import com.ahmedapps.roomdatabase.presentation.NotesEvent import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.Dp import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat.getSystemService import androidx.core.content.FileProvider import com.example.notesapplication.MainActivity import java.io.File import java.io.FileOutputStream @Composable fun AddNoteScreen( state: NoteState, navController: NavController, onEvent: (NotesEvent) -> Unit ) { val context = LocalContext.current val notificationClass = Notifications(context) var selectedImageUri by remember { mutableStateOf<Uri?>(null) } var selectedImageFile by remember { mutableStateOf<File?>(null) } val sensorManager = LocalContext.current.getSystemService(Context.SENSOR_SERVICE) as SensorManager val accelerometer: Sensor? = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) DisposableEffect(sensorManager) { val listener = object : SensorEventListener { override fun onSensorChanged(event: SensorEvent?) { event?.let { if (it.sensor.type == Sensor.TYPE_ACCELEROMETER) { val gravity = FloatArray(3) val alpha = 0.8f gravity[0] = alpha * gravity[0] + (1 - alpha) * it.values[0] gravity[1] = alpha * gravity[1] + (1 - alpha) * it.values[1] gravity[2] = alpha * gravity[2] + (1 - alpha) * it.values[2] val x = it.values[0] - gravity[0] val y = it.values[1] - gravity[1] val z = it.values[2] - gravity[2] val threshold = 8f // You may need to adjust this threshold based on testing if (x > threshold || y > threshold || z > threshold) { Log.d("Sensor", "Phone lifted up") notificationClass.triggerNotification(context) } } } } override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) { // Not used in this example } } sensorManager.registerListener(listener, accelerometer, SensorManager.SENSOR_DELAY_NORMAL) onDispose { sensorManager.unregisterListener(listener) } } val singlePhotoPickerLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.PickVisualMedia(), onResult = { uri -> if (uri != null) { Log.d("PhotoPicker", "Selected URI: $uri") //selectedImageUri = uri // Copy the selected image URI to internal storage val copiedFile = copyImageToAppStorage(context, context.contentResolver, uri) if (copiedFile != null) { Log.d("PhotoPicker", "Image copied to internal storage: ${copiedFile.absolutePath}") // Update the state with the copied image URI state.description.value = copiedFile.absolutePath selectedImageFile = copiedFile } else { Log.e("PhotoPicker", "Failed to copy image to internal storage") } } else { Log.d("PhotoPicker", "No media selected") } } ) Scaffold( floatingActionButton = { FloatingActionButton(onClick = { onEvent(NotesEvent.SaveNote( title = state.title.value, description = state.description.value )) navController.popBackStack() }) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = "Save and go back" ) } } ) { paddingValues -> Column( modifier = Modifier .padding(paddingValues) .fillMaxSize() ) { TextField( modifier = Modifier .fillMaxWidth() .padding(16.dp), value = state.title.value, onValueChange = { state.title.value = it }, textStyle = TextStyle( fontWeight = FontWeight.SemiBold, fontSize = 17.sp ), placeholder = { Text(text = "Enter name:") } ) Box( modifier = Modifier .size(100.dp) .padding(16.dp) .clip(CircleShape) .background(Color.LightGray) .border(2.dp, MaterialTheme.colorScheme.primary, CircleShape) .clickable { singlePhotoPickerLauncher.launch( PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly) ) } ) { state.description.value?.let { filePath -> val profilePictureFile = File(filePath) Image( painter = rememberImagePainter(profilePictureFile), contentDescription = "Profile Picture", modifier = Modifier.fillMaxSize(), contentScale = ContentScale.Crop ) } } Box( modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { Button( onClick = { notificationClass.createNotificationChannel(context) notificationClass.enableNotifications(context) }, modifier = Modifier.fillMaxWidth() ) { Text(text = "Enable Notifications", color = Color.White) } } } } } fun copyImageToAppStorage(context: Context, contentResolver: ContentResolver, imageUri: Uri): File? { val inputStream = contentResolver.openInputStream(imageUri) val filesDir = context.filesDir val outputFile = File(filesDir, "copied_image.jpg") try { inputStream?.use { input -> FileOutputStream(outputFile).use { output -> val buffer = ByteArray(4 * 1024) // buffer size var read: Int while (input.read(buffer).also { read = it } != -1) { output.write(buffer, 0, read) } output.flush() } } return outputFile } catch (e: Exception) { e.printStackTrace() } return null }
NotesApplication/app/src/main/java/com/example/notesapplication/presentation/AddNoteScreen.kt
2718893498
package com.example.notesapplication.presentation import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import com.ahmedapps.roomdatabase.data.Note data class NoteState( val notes: List<Note> = emptyList(), val title: MutableState<String> = mutableStateOf(""), val description: MutableState<String> = mutableStateOf("") )
NotesApplication/app/src/main/java/com/example/notesapplication/presentation/NoteState.kt
3186420934
package com.ahmedapps.roomdatabase.presentation import com.ahmedapps.roomdatabase.data.Note sealed interface NotesEvent { object SortNotes: NotesEvent data class DeleteNote(val note: Note): NotesEvent data class SaveNote( val title: String, val description: String ): NotesEvent }
NotesApplication/app/src/main/java/com/example/notesapplication/presentation/NotesEvent.kt
4081584839
package com.example.notesapplication.presentation import android.util.Log import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.ahmedapps.roomdatabase.data.Note import com.ahmedapps.roomdatabase.data.NoteDao import com.ahmedapps.roomdatabase.presentation.NotesEvent import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class NotesViewModel( private val dao: NoteDao ) : ViewModel() { private val noteFlow = dao.getNote().stateIn(viewModelScope, SharingStarted.WhileSubscribed(), null) val _state = MutableStateFlow(NoteState()) val state = combine(_state, noteFlow) { state, note -> state.copy( title = mutableStateOf(note?.title ?: ""), description = mutableStateOf(note?.description ?: "") ) }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), NoteState()) fun onEvent(event: NotesEvent) { when (event) { is NotesEvent.SaveNote -> { val note = Note( title = state.value.title.value, description = state.value.description.value, dateAdded = System.currentTimeMillis() // älä poista ) viewModelScope.launch { // Check if a note already exists, if so, update it noteFlow.value?.let { existingNote -> val updatedNote = existingNote.copy( title = note.title, description = note.description ) dao.upsertNote(updatedNote) } ?: dao.upsertNote(note) } } // Other events handling if needed else -> { } } } }
NotesApplication/app/src/main/java/com/example/notesapplication/presentation/NotesViewModel.kt
1629090312
package com.example.loinandregister.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) )
Login_Register-using-JetPackCompose/app/src/main/java/com/example/loinandregister/ui/theme/Shape.kt
2978270548
package com.example.loinandregister.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5)
Login_Register-using-JetPackCompose/app/src/main/java/com/example/loinandregister/ui/theme/Color.kt
4202408232
package com.example.loinandregister.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color private val DarkColorPalette = darkColors( primary = Purple200, primaryVariant = Purple700, secondary = Teal200, background = Color.White, ) private val LightColorPalette = lightColors( primary = Purple500, primaryVariant = Purple700, secondary = Teal200 /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) @Composable fun LoinandRegisterTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = Typography, shapes = Shapes, content = content ) }
Login_Register-using-JetPackCompose/app/src/main/java/com/example/loinandregister/ui/theme/Theme.kt
2365401815
package com.example.loinandregister.ui.theme import androidx.compose.material.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( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) /* Other default text styles to override button = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.W500, fontSize = 14.sp ), caption = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp ) */ )
Login_Register-using-JetPackCompose/app/src/main/java/com/example/loinandregister/ui/theme/Type.kt
2498128277
package com.example.loinandregister import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.example.loinandregister.ui.theme.LoinandRegisterTheme import com.example.loinandregister.view.LoginPage import com.example.loinandregister.view.RegisterPage class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LoinandRegisterTheme { navigatePage() } } } } @Composable fun navigatePage() { val navController= rememberNavController() NavHost(navController = navController, startDestination ="login_Page" , builder = { composable("login_Page" , content = { LoginPage(navController = navController)}) //LoginPage de el fun ell f Login File composable("register_Page" , content = { RegisterPage(navController = navController) }) // }) }
Login_Register-using-JetPackCompose/app/src/main/java/com/example/loinandregister/MainActivity.kt
843194784
package com.example.loinandregister.view import android.widget.Toast import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import com.example.loinandregister.R import com.example.loinandregister.ui.theme.Purple200 @Composable fun LoginPage(navController: NavController){ val context = LocalContext.current val scaffoldState = rememberScaffoldState() val emailVal = remember { mutableStateOf("") } val passwordVal = remember { mutableStateOf("") } val passwordVisibility = remember { mutableStateOf(false) } Box(modifier = Modifier .fillMaxSize() .background(color = Color.White) , contentAlignment = Alignment.Center) { Column(horizontalAlignment = Alignment.CenterHorizontally , verticalArrangement = Arrangement.Center , modifier = Modifier.fillMaxSize()) { // el column da el view elly h7ot feh image w zabt el alignment bta3ha mn el column attributes Box(modifier = Modifier.background(color = Color.White), contentAlignment = Alignment.TopCenter){ // gwa el box da h7ot rl image Image(modifier= Modifier .width(400.dp) .height(350.dp) , painter = painterResource(R.drawable.login), contentDescription= "Login Image" , contentScale = ContentScale.Fit ) } Spacer(modifier = Modifier.padding(20.dp)) // space ben el image w el ba2y Scaffold(modifier = Modifier.fillMaxSize() , scaffoldState = scaffoldState) { Column(horizontalAlignment = Alignment.CenterHorizontally , verticalArrangement = Arrangement.Center , modifier = Modifier .fillMaxWidth() .background(Color.White) .padding(10.dp)) { Text(text = "Sign In" , fontSize = 24.sp , fontWeight = FontWeight.Bold , color = Color.Black) Spacer(modifier = Modifier.padding(20.dp)) // space ben el signin title w el ba2y Column(horizontalAlignment = Alignment.CenterHorizontally , verticalArrangement = Arrangement.Center) { OutlinedTextField(value = emailVal.value, onValueChange = { emailVal.value=it //lma el value bta3 em emial hsalo change , ezn it de hya el new value f b assign it ll el emailVal } , label = { Text(text = "Email Address" , color = Color.Black)} , // label de ha label el edittext placeholder = { Text(text = "Email Address" , color = Color.Black)} , //placeholder de hya el hint f el edit text singleLine = true, modifier = Modifier.fillMaxWidth(0.8f), colors= TextFieldDefaults.outlinedTextFieldColors(unfocusedBorderColor = Color.Black , textColor = Color.Black), // de en elly hktbo ykon black ) OutlinedTextField( value = passwordVal.value, onValueChange = { passwordVal.value = it //lma el value bta3 em emial hsalo change , ezn it de hya el new value f b assign it ll el emailVal }, trailingIcon = { IconButton(onClick = { passwordVisibility.value= !passwordVisibility.value }) { Icon(painter = painterResource(id=R.drawable.ic_baseline_remove_red_eye_24), contentDescription ="Password" , tint = if (passwordVisibility.value) Purple200 else Color.Gray) } }, visualTransformation = if(passwordVisibility.value) VisualTransformation.None else PasswordVisualTransformation(), label = { Text( text = "Password", color = Color.Black ) }, // label de ha label el edittext placeholder = { Text( text = "Password", color = Color.Black ) }, //placeholder de hya el hint f el edit text singleLine = true, modifier = Modifier.fillMaxWidth(0.8f), colors = TextFieldDefaults.outlinedTextFieldColors( unfocusedBorderColor = Color.Black, textColor = Color.Black) // de en elly hktbo ykon black ) Spacer(modifier = Modifier.padding(20.dp)) // space ben el edittexts title w el ba2y Button(onClick = { when { emailVal.value.isEmpty() -> { Toast.makeText( context, "Please Fill The Email Address", Toast.LENGTH_SHORT ).show() } passwordVal.value.isEmpty() -> { Toast.makeText( context, "Please Fill The Password ", Toast.LENGTH_SHORT ).show() } else -> Toast.makeText( context, "Logged Successfully ", Toast.LENGTH_SHORT ).show() } } , modifier = Modifier .fillMaxWidth(0.8f) .height(50.dp), colors = ButtonDefaults.buttonColors(backgroundColor = Color.White) , ) { Text(text = "Sign In", fontSize = 22.sp , color = Color.Black) } Spacer(modifier = Modifier.padding(20.dp)) // space ben el signin button w el crate account Text( text = "Create An Account?", color = Color.Black, fontSize = 22.sp, modifier = Modifier.clickable { navController.navigate("register_Page") }) Spacer(modifier = Modifier.padding(20.dp)) } } } } //modifier.fillmaxsize : يعني خليت البوكس ياخد الصفحه كامله ويخلي الباك جراوند ابيض } }
Login_Register-using-JetPackCompose/app/src/main/java/com/example/loinandregister/view/Login.kt
404918752
package com.example.loinandregister.view import android.widget.Toast import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import com.example.loinandregister.R import com.example.loinandregister.ui.theme.Purple200 @Composable fun RegisterPage(navController: NavController) { val context = LocalContext.current val scaffoldState = rememberScaffoldState() val nameVal = remember { mutableStateOf("") } val emailVal = remember { mutableStateOf("") } val phoneVal = remember { mutableStateOf("") } val passwordVal = remember { mutableStateOf("") } val repasswordVal = remember { mutableStateOf("") } val passwordVisibility = remember { mutableStateOf(false) } val repasswordVisibility = remember { mutableStateOf(false) } Box( modifier = Modifier .fillMaxSize() .background(color = Color.White), contentAlignment = Alignment.Center ) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier.fillMaxSize() ) { // el column da el view elly h7ot feh image w zabt el alignment bta3ha mn el column attributes Box( modifier = Modifier.background(color = Color.White), contentAlignment = Alignment.TopCenter ) { // gwa el box da h7ot rl image Image( modifier = Modifier .width(400.dp) .height(350.dp), painter = painterResource(R.drawable.register_img), contentDescription = "Register Image", contentScale = ContentScale.Fit ) } Spacer(modifier = Modifier.padding(20.dp)) // space ben el image w el ba2y Scaffold(modifier = Modifier.fillMaxSize() , scaffoldState = scaffoldState) { Column(horizontalAlignment = Alignment.CenterHorizontally , verticalArrangement = Arrangement.Center , modifier = Modifier .fillMaxWidth() .background(Color.White) .padding(10.dp)) { Text(text = "Sign Up" , fontSize = 24.sp , fontWeight = FontWeight.Bold , color = Color.Black) Spacer(modifier = Modifier.padding(20.dp)) // space ben el signup title w el ba2y Column(horizontalAlignment = Alignment.CenterHorizontally , verticalArrangement = Arrangement.Center) { OutlinedTextField(value = nameVal.value, onValueChange = { nameVal.value=it } , label = { Text(text = "Name" , color = Color.Black) } , // label de ha label el edittext placeholder = { Text(text = "Name" , color = Color.Black) } , //placeholder de hya el hint f el edit text singleLine = true, modifier = Modifier.fillMaxWidth(0.8f), colors= TextFieldDefaults.outlinedTextFieldColors(unfocusedBorderColor = Color.Black , textColor = Color.Black), // de en elly hktbo ykon black ) OutlinedTextField(value = emailVal.value, onValueChange = { emailVal.value=it //lma el value bta3 em emial hsalo change , ezn it de hya el new value f b assign it ll el emailVal } , label = { Text(text = "Email Address" , color = Color.Black) } , // label de ha label el edittext placeholder = { Text(text = "Email Address" , color = Color.Black) } , //placeholder de hya el hint f el edit text singleLine = true, modifier = Modifier.fillMaxWidth(0.8f), colors= TextFieldDefaults.outlinedTextFieldColors(unfocusedBorderColor = Color.Black , textColor = Color.Black), // de en elly hktbo ykon black ) OutlinedTextField(value = phoneVal.value, onValueChange = { phoneVal.value=it } , label = { Text(text = "Phone Number" , color = Color.Black) } , // label de ha label el edittext placeholder = { Text(text = "Phone Number", color = Color.Black) } , //placeholder de hya el hint f el edit text singleLine = true, modifier = Modifier.fillMaxWidth(0.8f), colors= TextFieldDefaults.outlinedTextFieldColors(unfocusedBorderColor = Color.Black , textColor = Color.Black), // de en elly hktbo ykon black ) OutlinedTextField( value = passwordVal.value, onValueChange = { passwordVal.value = it }, trailingIcon = { IconButton(onClick = { passwordVisibility.value= !passwordVisibility.value }) { Icon(painter = painterResource(id=R.drawable.ic_baseline_remove_red_eye_24), contentDescription ="Password" , tint = if (passwordVisibility.value) Purple200 else Color.Gray) } }, visualTransformation = if(passwordVisibility.value) VisualTransformation.None else PasswordVisualTransformation(), label = { Text( text = "Password", color = Color.Black ) }, // label de ha label el edittext placeholder = { Text( text = "Password", color = Color.Black ) }, //placeholder de hya el hint f el edit text singleLine = true, modifier = Modifier.fillMaxWidth(0.8f), colors = TextFieldDefaults.outlinedTextFieldColors( unfocusedBorderColor = Color.Black, textColor = Color.Black) // de en elly hktbo ykon black ) OutlinedTextField( value = repasswordVal.value, onValueChange = { repasswordVal.value = it }, trailingIcon = { IconButton(onClick = { repasswordVisibility.value= !repasswordVisibility.value }) { Icon(painter = painterResource(id=R.drawable.ic_baseline_remove_red_eye_24), contentDescription ="Password" , tint = if (passwordVisibility.value) Purple200 else Color.Gray) } }, visualTransformation = if(repasswordVisibility.value) VisualTransformation.None else PasswordVisualTransformation(), label = { Text( text = "Confirm Password", color = Color.Black ) }, // label de ha label el edittext placeholder = { Text( text = "Confirm Password", color = Color.Black ) }, //placeholder de hya el hint f el edit text singleLine = true, modifier = Modifier.fillMaxWidth(0.8f), colors = TextFieldDefaults.outlinedTextFieldColors( unfocusedBorderColor = Color.Black, textColor = Color.Black) // de en elly hktbo ykon black ) Spacer(modifier = Modifier.padding(20.dp)) // space ben el edittexts title w el ba2y Button(onClick = { when { emailVal.value.isEmpty() -> { Toast.makeText( context, "Please Fill The Email Address", Toast.LENGTH_SHORT ).show() } nameVal.value.isEmpty() -> { Toast.makeText( context, "Please Fill The Name", Toast.LENGTH_SHORT ).show() } phoneVal.value.isEmpty() -> { Toast.makeText( context, "Please Fill The Phone Number", Toast.LENGTH_SHORT ).show() } passwordVal.value.isEmpty() -> { Toast.makeText( context, "Please Fill The Password ", Toast.LENGTH_SHORT ).show() } repasswordVal.value.isEmpty() -> { Toast.makeText( context, "Please Fill The Confirm Password ", Toast.LENGTH_SHORT ).show() } else -> Toast.makeText( context, "Registered Successfully ", Toast.LENGTH_SHORT ).show() } } , modifier = Modifier .fillMaxWidth(0.8f) .height(50.dp), colors = ButtonDefaults.buttonColors(backgroundColor = Color.White) , ) { Text(text = "Sign Up", fontSize = 22.sp , color = Color.Black) } Spacer(modifier = Modifier.padding(20.dp)) // space ben el signup button w el crate account Text( text = "Login Instead?", color = Color.Black, fontSize = 22.sp, modifier = Modifier.clickable { navController.navigate("login_Page") }) Spacer(modifier = Modifier.padding(20.dp)) } } } } } }
Login_Register-using-JetPackCompose/app/src/main/java/com/example/loinandregister/view/Register.kt
1834451177
package com.rahuleus.gary 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.rahuleus.gary", appContext.packageName) } }
Gary/Gary/app/src/androidTest/java/com/rahuleus/gary/ExampleInstrumentedTest.kt
2075456203
package com.rahuleus.gary 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) } }
Gary/Gary/app/src/test/java/com/rahuleus/gary/ExampleUnitTest.kt
1793243790
package com.rahuleus.gary.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)
Gary/Gary/app/src/main/java/com/rahuleus/gary/ui/theme/Color.kt
2912215956
package com.rahuleus.gary.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 GaryTheme( 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 ) }
Gary/Gary/app/src/main/java/com/rahuleus/gary/ui/theme/Theme.kt
2705918080
package com.rahuleus.gary.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 ) */ )
Gary/Gary/app/src/main/java/com/rahuleus/gary/ui/theme/Type.kt
1425987889
package com.rahuleus.gary import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.result.contract.ActivityResultContracts import com.google.mlkit.vision.barcode.common.Barcode import java.io.IOException import org.jsoup.Jsoup /*import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContract import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import com.rahuleus.gary.ui.theme.GaryTheme import androidx.compose.ui.tooling.preview.Preview*/ import com.rahuleus.gary.databinding.ActivityMainBinding class MainActivity : ComponentActivity() { private val cameraPermission = android.Manifest.permission.CAMERA private lateinit var binding: ActivityMainBinding private var we="https://in.openfoodfacts.org/product/" private val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted -> if(isGranted) this.startScanner() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.button.setOnClickListener{ requestCameraAndStartScanner() } } private fun requestCameraAndStartScanner(){ if(isPermissionGranted(cameraPermission)){ startScanner() } else{ requestCameraPermission() } } private fun startScanner(){ ScannerActivity.startScanner(this){barcodes -> barcodes.forEach{barcode -> when(barcode.format){ Barcode.FORMAT_EAN_13 -> { webReader(barcode.rawValue.toString()) //binding.textViewQrContent.text } else ->{ "INVALID".also { binding.textViewQrAllergen.text = it } } } } } } private fun webReader(bsite: String) { val url = buildString { append(we) append(bsite) } try { val document = Jsoup.connect(url).get() val content = "$document" val words =content.split(" ") extractor(words) } catch (e: IOException) { println("database found no match") e.printStackTrace() } } private fun extractor(sentence: List<String>){ val Checker2= "Allergens" val Checker="ingredients" val breaker="Food" var foundtarget=false var foundtarget2=false val Allergens=mutableListOf<String>() val Ingredients= mutableListOf<String>() for ( words in sentence) { if(words == breaker) break else if (words == Checker) { foundtarget= true } else if(foundtarget==true){ if(words == (Checker2)) { foundtarget=false foundtarget2=true } else Ingredients.add(words) } else if(foundtarget2==true){ Allergens.add(words) } } binding.textViewQrAllergen.text = Allergens.toString() binding.textViewQrIngredient.text = Ingredients.toString() } private fun requestCameraPermission() { when{ shouldShowRequestPermissionRationale(cameraPermission) -> { cameraPermissionRequest { openPermissionSetting() } } else -> { requestPermissionLauncher.launch(cameraPermission) } } } }
Gary/Gary/app/src/main/java/com/rahuleus/gary/MainActivity.kt
2092859246
@file:Suppress("KotlinConstantConditions") package com.rahuleus.gary import android.app.AlertDialog import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS import androidx.core.content.ContextCompat //import fun Context.isPermissionGranted(permission: String): Boolean { return ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED } inline fun Context.cameraPermissionRequest (crossinline positive: () -> Unit) { AlertDialog.Builder(this) .setTitle("Camera Permission Required") .setMessage("Without accessing the camera it is not possible to SCAN QR Codes...") .setPositiveButton("Allow Camera") { dialog, which -> positive.invoke() }.setNegativeButton("Cancel") { dialog, which -> }.show() } fun Context.openPermissionSetting() { Intent(ACTION_APPLICATION_DETAILS_SETTINGS).also { val uri: Uri = Uri.fromParts("package", packageName, null) it.data = uri startActivity(it) } }
Gary/Gary/app/src/main/java/com/rahuleus/gary/Utils.kt
1799974392
package com.rahuleus.gary import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.camera.core.CameraSelector import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageProxy import androidx.camera.core.Preview import androidx.camera.lifecycle.ProcessCameraProvider import androidx.core.content.ContextCompat /*import android.graphics.Camera import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import androidx.activity.enableEdgeToEdge*/ import com.google.common.util.concurrent.ListenableFuture import com.google.mlkit.vision.barcode.BarcodeScanner import com.google.mlkit.vision.barcode.BarcodeScannerOptions import com.google.mlkit.vision.barcode.BarcodeScanning import com.google.mlkit.vision.barcode.common.Barcode import com.google.mlkit.vision.common.InputImage import com.rahuleus.gary.databinding.ActivityScannerBinding import java.util.concurrent.Executors class ScannerActivity : AppCompatActivity() { private lateinit var binding: ActivityScannerBinding private lateinit var imageAnalysis: ImageAnalysis private lateinit var cameraSelector: CameraSelector private lateinit var cameraProviderFuture: ListenableFuture<ProcessCameraProvider> private lateinit var processCameraProvider: ProcessCameraProvider private lateinit var cameraPreview: Preview override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityScannerBinding.inflate(layoutInflater) setContentView(binding.root) cameraSelector = CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build() cameraProviderFuture = ProcessCameraProvider.getInstance(this) cameraProviderFuture.addListener( { processCameraProvider = cameraProviderFuture.get() bindCameraPreview() bindInputAnalyser() }, ContextCompat.getMainExecutor(this) ) } private fun bindCameraPreview() { cameraPreview = Preview.Builder() .setTargetRotation(binding.previewView.display.rotation) .build() cameraPreview.setSurfaceProvider(binding.previewView.surfaceProvider) processCameraProvider.bindToLifecycle(this, cameraSelector, cameraPreview) } private fun bindInputAnalyser() { val barcodeScanner: BarcodeScanner = BarcodeScanning.getClient( BarcodeScannerOptions.Builder() .setBarcodeFormats(Barcode.FORMAT_QR_CODE, Barcode.FORMAT_EAN_13) .build() ) imageAnalysis = ImageAnalysis.Builder() .setTargetRotation(binding.previewView.display.rotation) .build() val cameraExecutor = Executors.newSingleThreadExecutor() imageAnalysis.setAnalyzer(cameraExecutor) { imageProxy -> processImageProxy(barcodeScanner, imageProxy) } processCameraProvider.bindToLifecycle(this, cameraSelector, imageAnalysis) } @SuppressLint("UnsafeOptInUsageError") private fun processImageProxy( barcodeScanner: BarcodeScanner, imageProxy: ImageProxy ){ val inputImage = InputImage.fromMediaImage(imageProxy.image!!, imageProxy.imageInfo.rotationDegrees) barcodeScanner.process(inputImage) .addOnSuccessListener{ barcodes -> if(barcodes.isNotEmpty()){ onScan?.invoke(barcodes) onScan =null finish() } }.addOnFailureListener{ it.printStackTrace() }.addOnCompleteListener{ imageProxy.close() } } companion object{ private var onScan:((barcode:List<Barcode>) -> Unit)?=null fun startScanner(context: Context, onScan: (barcodes: List<Barcode>) -> Unit){ this.onScan=onScan Intent(context, ScannerActivity::class.java).also{ context.startActivity(it) } } } }
Gary/Gary/app/src/main/java/com/rahuleus/gary/ScannerActivity.kt
2599524478
package com.example.phonebook2 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.phonebook2", appContext.packageName) } }
W9-Contact-App-Fragment-Kotlin/app/src/androidTest/java/com/example/phonebook2/ExampleInstrumentedTest.kt
3222604114
package com.example.phonebook2 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) } }
W9-Contact-App-Fragment-Kotlin/app/src/test/java/com/example/phonebook2/ExampleUnitTest.kt
30918942
package com.example.phonebook2 import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.ListView import androidx.navigation.findNavController import androidx.navigation.fragment.findNavController class ListFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { setHasOptionsMenu(true) return inflater.inflate(R.layout.fragment_list, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val contacts = listOf( ItemModel(R.drawable.img1, "Tuấn Anh"), ItemModel(R.drawable.img1, "Tuấn Anh"), ItemModel(R.drawable.img1, "Tuấn Anh"), ItemModel(R.drawable.img1, "Tuấn Anh"), ItemModel(R.drawable.img1, "Tuấn Anh"), ItemModel(R.drawable.img1, "Tuấn Anh"), ItemModel(R.drawable.img1, "Tuấn Anh"), ItemModel(R.drawable.img1, "Tuấn Anh"), ItemModel(R.drawable.img1, "Tuấn Anh"), ItemModel(R.drawable.img1, "Tuấn Anh"), ItemModel(R.drawable.img1, "Tuấn Anh"), ItemModel(R.drawable.img1, "Tuấn Anh"), ) val listView: ListView = view.findViewById(R.id.list_view) val adapter = ItemAdapter(requireContext(), contacts) listView.adapter = adapter listView.setOnItemClickListener { parent, view, position, id -> val selectedContact = contacts[position] val nameAcc = selectedContact.nameAcc // val params: Bundle = Bundle() // val navController = view.findNavController() // navController.navigate(R.id.action_listFragment_to_infDetailFragment, params) // // params.putString("SELECTED_ITEM", name) val detailFragment = InfDetailFragment.newInstance(nameAcc) requireActivity().supportFragmentManager .beginTransaction() .replace(R.id.fragment_container, detailFragment) .addToBackStack(null) .commit() } } // override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { // inflater.inflate(R.menu.option_menu, menu) // super.onCreateOptionsMenu(menu, inflater) // } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.add_option -> { Log.d("ListFragment", "Add option selected") val addItemFragment = AddFragment() requireActivity().supportFragmentManager .beginTransaction() .replace(R.id.fragment_container, addItemFragment) .addToBackStack(null) .commit() return true } else -> return super.onOptionsItemSelected(item) } } }
W9-Contact-App-Fragment-Kotlin/app/src/main/java/com/example/phonebook2/ListFragment.kt
305731300
package com.example.phonebook2 import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.FrameLayout import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.option_menu, menu) return true } }
W9-Contact-App-Fragment-Kotlin/app/src/main/java/com/example/phonebook2/MainActivity.kt
3068051258
package com.example.phonebook2 data class ItemModel( val profileImg : Int, val nameAcc: String) { }
W9-Contact-App-Fragment-Kotlin/app/src/main/java/com/example/phonebook2/ItemModel.kt
2456939684
package com.example.phonebook2 import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup class AddFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_add, container, false) } }
W9-Contact-App-Fragment-Kotlin/app/src/main/java/com/example/phonebook2/AddFragment.kt
2435060963
package com.example.phonebook2 import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.TextView class InfDetailFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { setHasOptionsMenu(true) return inflater.inflate(R.layout.fragment_inf_detail, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) } companion object { fun newInstance(name: String): InfDetailFragment { val fragment = InfDetailFragment() return fragment } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.add_option -> { val addItemFragment = AddFragment() requireActivity().supportFragmentManager .beginTransaction() .replace(R.id.fragment_container, addItemFragment) .addToBackStack(null) .commit() return true } else -> return super.onOptionsItemSelected(item) } } }
W9-Contact-App-Fragment-Kotlin/app/src/main/java/com/example/phonebook2/InfDetailFragment.kt
4215819467
package com.example.phonebook2 import android.content.Context import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView class ItemAdapter(context: Context, contacts: List<ItemModel>) : ArrayAdapter<ItemModel>(context, R.layout.list_item, contacts) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val itemView = convertView ?: LayoutInflater.from(context) .inflate(R.layout.list_item, parent, false) val imageViewContact: ImageView = itemView.findViewById(R.id.contact_img) val textViewContactName: TextView = itemView.findViewById(R.id.contact_name) val contact = getItem(position) imageViewContact.setImageResource(contact?.profileImg ?: R.drawable.img) textViewContactName.text = contact?.nameAcc return itemView } }
W9-Contact-App-Fragment-Kotlin/app/src/main/java/com/example/phonebook2/ItemAdapter.kt
2441563409
import java.math.BigInteger import java.security.MessageDigest import kotlin.io.path.Path import kotlin.io.path.readLines /** * Reads lines from the given input txt file. */ fun readInput(name: String) = Path("src/$name.txt").readLines() /** * Converts string to md5 hash. */ fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())) .toString(16) .padStart(32, '0') /** * The cleaner shorthand for printing output. */ fun Any?.println() = println(this)
AdventOfCode23-kotlin/src/Utils.kt
186397594
package Day1 import println import readInput /** Returns a list of all possible tail substrings of a given string. */ private fun String.tails(): List<CharSequence> = indices.map { subSequence(it, length) } /** Mapping from "0" -> 0, "1" -> 1 etc. */ private val numericDigits: Map<String, Int> = (0..9).associateBy { it.toString() } /** Mapping from "one" -> 1, "two" -> 2 etc. */ private val writtenDigits: Map<String, Int> = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine") .withIndex().associate { (i, word) -> word to (i + 1) } private fun CharSequence.startingDigit(digits: Map<String, Int>): Int? = digits.entries.firstNotNullOfOrNull { (prefix, digit) -> digit.takeIf { startsWith(prefix) } } /** Calculates the calibration value for a line, using given digit mappings */ private fun calibrationValue(line: String, digits: Map<String, Int>): Int { val lineDigits = line.tails().mapNotNull { it.startingDigit(digits) } return lineDigits.first() * 10 + lineDigits.last() } private fun calibrationValueSum(input: List<String>, digits: Map<String, Int>) = input.sumOf { calibrationValue(it, digits) } fun main() { fun part1(input: List<String>) : Int = calibrationValueSum(input, digits = numericDigits) fun part2(input: List<String>) : Int = calibrationValueSum(input, digits = numericDigits + writtenDigits) val testInput = readInput("Day01_test") val testOutput = part1(testInput) println(testOutput) check(testOutput == 142) val testInput2 = readInput("Day02_test") val testOutput2 = part2(testInput2) println(testOutput2) check(testOutput2 == 281) // check(part2(testInput) == 45000) val input = readInput("Day01") part1(input).println() part2(input).println() }
AdventOfCode23-kotlin/src/Day1/Day01.kt
3499604887
package com.korobeynikova.pr11_zagadks 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.korobeynikova.pr11_zagadks", appContext.packageName) } }
pr11_zagadks/app/src/androidTest/java/com/korobeynikova/pr11_zagadks/ExampleInstrumentedTest.kt
78506545
package com.korobeynikova.pr11_zagadks 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) } }
pr11_zagadks/app/src/test/java/com/korobeynikova/pr11_zagadks/ExampleUnitTest.kt
2556664554
package com.korobeynikova.pr11_zagadks import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class StatsActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_stats) val totalRiddles = intent.getIntExtra("totalRiddles", 0) val correctAnswers = intent.getIntExtra("correctAnswers", 0) val incorrectAnswers = intent.getIntExtra("incorrectAnswers", 0) val textTotalRiddles = findViewById<TextView>(R.id.text_total_riddles) val textCorrectAnswers = findViewById<TextView>(R.id.text_correct_answers) val textIncorrectAnswers = findViewById<TextView>(R.id.text_incorrect_answers) textTotalRiddles.text = "Полученные загадки: $totalRiddles" textCorrectAnswers.text = "Правильные ответы: $correctAnswers" textIncorrectAnswers.text = "Неправильные ответы: $incorrectAnswers" val btnNewSession = findViewById<Button>(R.id.btn_new_session) btnNewSession.setOnClickListener { startNewSession() } } private fun startNewSession() { val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() } }
pr11_zagadks/app/src/main/java/com/korobeynikova/pr11_zagadks/StatsActivity.kt
1717693502
package com.korobeynikova.pr11_zagadks import android.annotation.SuppressLint import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.RadioButton import android.widget.RadioGroup import android.widget.TextView import android.widget.Toast class MainActivity : AppCompatActivity() { private lateinit var textRiddle: TextView private lateinit var radioGroup: RadioGroup private lateinit var btnCheck: Button private lateinit var btnStats: Button private lateinit var btnRiddle: Button private lateinit var btnGoEnd: Button private lateinit var textRiddleCount: TextView private val answers = listOf( Triple( "Висит груша, нельзя скушать.", listOf("Груша", "Шар", "Лампочка", "Яблоко"), 2 ), Triple( "Что можно сломать, но нельзя увидеть?", listOf("Сердце", "Шар", "Воздух", "Доверие"), 0 ), Triple( "Что можно увидеть с закрытыми глазами?", listOf("Звезды", "Сны", "Цветы", "Тени"), 1 ), Triple("Кто его делает, тот не пользуется, кто пользуется, тот его не делает. Что это?", listOf("Ключ", "Гроб", "Ложка", "Ведро"), 1), Triple( "Что можно увидеть вместе с его создателем?", listOf("Душа", "Тень", "Свет", "Отражение"), 1 ), Triple( "Что идет, не шагает, что идет, не едет?", listOf("Дождь", "Свет", "Время", "Путь"), 2 ), Triple( "День спит, ночь глядит, утром умирает, другой сменяет. Что это?", listOf("Месяц", "Свечи", "Вампир", "Ветер"), 1 ), Triple("Хоть без глаз, могу бегущих догонять, но только никому меня нельзя обнять. Что это?", listOf("Туча", "Тень", "Деньги", "Звезда"), 1), Triple( "Без языка, а сказывается. Что это?", listOf("Боль", "Жест", "Лай", "Старость"), 0 ), Triple( "Не море, не земля, корабли не плавают, и ходить нельзя. Что за место такое?", listOf("Небеса", "Лава", "Болото", "Пустыня"), 2 ), Triple( "Первый говорит — побежим, другой говорит — полежим, третий говорит — покачаемся. Кто первый?", listOf("Время", "Грунтовая дорога", "Конь", "Вода"), 3 ), Triple( "Деревянные ноги, хоть всё лето стой. Что это за зверь такой?", listOf("Забор", "Ткацкий станок", "Табуретка", "Протезы"), 1 ), Triple( "В лесу выросло, из лесу вынесли, на руках плачет, а по полу скачут. Что это?", listOf("Лапти", "Балалайка", "Деревянные доски", "Лук и стрелы"), 1 ), Triple( "Четыре четырки, две растопырки, седьмой вертун, два стёклушка в нём. Что это?", listOf("Бык", "Часы", "Автомобиль", "Бинокль"), 0 ), Triple( "Утка в море, хвост на заборе. Что за чудо-юдо?", listOf("Ковш", "Морковь", "Буй", "Якорь"), 0 ) ) private var currentRiddles: List<Triple<String, List<String>, Int>> = emptyList() private var currentRiddleIndex = 0 private var correctAnswersCount = 0 private var incorrectAnswersCount = 0 @SuppressLint("MissingInflatedId") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) textRiddle = findViewById(R.id.text_riddle) radioGroup = findViewById(R.id.radio_group) btnCheck = findViewById(R.id.btn_check) btnStats = findViewById(R.id.btn_stats) textRiddleCount = findViewById(R.id.text_riddle_count) btnRiddle = findViewById(R.id.btn_riddle) btnGoEnd = findViewById(R.id.btn_goEnd) btnCheck.visibility = View.GONE btnCheck.setOnClickListener { checkAnswer() } btnStats.setOnClickListener { showStats() } btnRiddle.setOnClickListener { showNextRiddle() } btnGoEnd.setOnClickListener { showEndRiddle() } generateRiddles() showNextRiddle() } private fun checkAnswer() { val checkedRadioButtonId = radioGroup.checkedRadioButtonId if (checkedRadioButtonId != -1) { val checkedRadioButton = findViewById<RadioButton>(checkedRadioButtonId) val selectedAnswer = checkedRadioButton.text.toString() val (_, answersList, correctAnswerIndex) = currentRiddles[currentRiddleIndex - 1] val correctAnswer = answersList[correctAnswerIndex] if (selectedAnswer == correctAnswer) { Toast.makeText(this, "Правильно!", Toast.LENGTH_SHORT).show() // Увеличиваем счетчик правильных ответов correctAnswersCount++ } else { Toast.makeText(this, "Неправильно!", Toast.LENGTH_SHORT).show() // Увеличиваем счетчик неправильных ответов incorrectAnswersCount++ } showNextRiddle() } else { Toast.makeText(this, "Выберите ответ", Toast.LENGTH_SHORT).show() } } private fun showStats() { val totalRiddles = currentRiddles.size val correctAnswers = correctAnswersCount val incorrectAnswers = incorrectAnswersCount val intent = Intent(this, StatsActivity::class.java) intent.putExtra("totalRiddles", totalRiddles) intent.putExtra("correctAnswers", correctAnswers) intent.putExtra("incorrectAnswers", incorrectAnswers) startActivity(intent) } private fun showEndRiddle(){ if (currentRiddleIndex > 1) { val (riddle, answersList, correctAnswerIndex) = currentRiddles[currentRiddleIndex] textRiddle.text = riddle radioGroup.removeAllViews() answersList.forEach { answer -> val radioButton = RadioButton(this) radioButton.text = answer radioGroup.addView(radioButton) } currentRiddleIndex-- textRiddleCount.text = "Загадка $currentRiddleIndex из ${currentRiddles.size}" btnCheck.visibility = View.VISIBLE } else { Toast.makeText(this, "Это первая загадка", Toast.LENGTH_SHORT).show() } } private fun showNextRiddle() { if (currentRiddleIndex < currentRiddles.size) { val (riddle, answersList, correctAnswerIndex) = currentRiddles[currentRiddleIndex] textRiddle.text = riddle radioGroup.removeAllViews() answersList.shuffled().forEach { answer -> val radioButton = RadioButton(this) radioButton.text = answer radioGroup.addView(radioButton) } currentRiddleIndex++ textRiddleCount.text = "Загадка $currentRiddleIndex из ${currentRiddles.size}" btnCheck.visibility = View.VISIBLE } else { btnCheck.visibility = View.GONE btnStats.visibility = View.VISIBLE btnRiddle.visibility = View.GONE Toast.makeText(this, "Все загадки отгаданы", Toast.LENGTH_SHORT).show() } } private fun generateRiddles() { currentRiddles = getRandomRiddles() } private fun getRandomRiddles(): List<Triple<String, List<String>, Int>> { val shuffledRiddles = answers.shuffled() return shuffledRiddles.take(10) } }
pr11_zagadks/app/src/main/java/com/korobeynikova/pr11_zagadks/MainActivity.kt
1472676798
package uz.javokhir_apps.languagetranslator 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("uz.javokhir_apps.languagetranslator", appContext.packageName) } }
Language_Translator/app/src/androidTest/java/uz/javokhir_apps/languagetranslator/ExampleInstrumentedTest.kt
2462350599
package uz.javokhir_apps.languagetranslator 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) } }
Language_Translator/app/src/test/java/uz/javokhir_apps/languagetranslator/ExampleUnitTest.kt
3102605450
package uz.javokhir_apps.languagetranslator import android.app.ProgressDialog import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Message import android.util.Log import android.view.Menu import android.widget.EditText import android.widget.PopupMenu import android.widget.TextView import android.widget.Toast import com.google.android.material.button.MaterialButton import com.google.mlkit.common.model.DownloadConditions import com.google.mlkit.nl.translate.TranslateLanguage import com.google.mlkit.nl.translate.Translation import com.google.mlkit.nl.translate.Translator import com.google.mlkit.nl.translate.TranslatorOptions import java.util.Locale class MainActivity : AppCompatActivity() { private lateinit var sourceLanguageEt:EditText private lateinit var targetLanguageTv:TextView private lateinit var sourceLanguageChooseBtn:MaterialButton private lateinit var targetLanguageChooseBtn:MaterialButton private lateinit var translateBtn:MaterialButton companion object{ private const val TAG="MAIN_TAG" } private var languageArrayList:ArrayList<ModelLanguage>?=null private var sourceLanguageCode="en" private var sourceLanguageTitle="English" private var targetLanguageCode="uz" private var targetLanguageTitle="Uzbek" private lateinit var translatorOptions: TranslatorOptions private lateinit var translator: Translator private lateinit var progressDialog: ProgressDialog override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) sourceLanguageEt=findViewById(R.id.sourceLanguageEt) targetLanguageTv=findViewById(R.id.targetLanguageTv) sourceLanguageChooseBtn=findViewById(R.id.sourceLanguageChooseBtn) targetLanguageChooseBtn=findViewById(R.id.targetLanguageChooseBtn) translateBtn=findViewById(R.id.translateBtn) progressDialog= ProgressDialog(this) progressDialog.setTitle("Please wait") progressDialog.setCanceledOnTouchOutside(false) loadAvailableLanguages() sourceLanguageChooseBtn.setOnClickListener { sourceLanguageChoose() } targetLanguageChooseBtn.setOnClickListener { targetLanguageChoose() } translateBtn.setOnClickListener { validateData() } } private var sourceLanguageText="" private fun validateData() { sourceLanguageText=sourceLanguageEt.text.toString().trim() Log.d(TAG,"validateData:sourceLanguageText:$sourceLanguageText") if (sourceLanguageText.isEmpty()){ showToast("Enter text to translate....") } else{ startTranslation() } } private fun startTranslation() { progressDialog.setMessage("Processing language model...") progressDialog.show() translatorOptions=TranslatorOptions.Builder() .setSourceLanguage(sourceLanguageCode) .setTargetLanguage(targetLanguageCode) .build() translator=Translation.getClient(translatorOptions) val downloadConditions=DownloadConditions.Builder() .requireWifi() .build() translator.downloadModelIfNeeded(downloadConditions) .addOnSuccessListener { Log.d(TAG,"startTranslation:model ready,start translation...") progressDialog.setMessage("Translating...") translator.translate(sourceLanguageText) .addOnSuccessListener {translatedText -> Log.d(TAG,"startTranslation:translatedText") progressDialog.dismiss() targetLanguageTv.text=translatedText } .addOnFailureListener {e-> progressDialog.dismiss() Log.e(TAG,"startTranslation:", e) showToast("Failed to translate due to ${e.message}") } } .addOnFailureListener {e-> progressDialog.dismiss() Log.e(TAG,"startTranslation:" ,e) showToast("Failed due to ${e.message}") } } private fun loadAvailableLanguages(){ languageArrayList=ArrayList() val languageCodeList=TranslateLanguage.getAllLanguages() for (languageCode in languageCodeList){ val languageTitle=Locale(languageCode).displayLanguage Log.d(TAG,"loadAvailableLanguages:languageCode: $languageCode") Log.d(TAG,"loadAvailableLanguages:languageTitle:$languageTitle") val modelLanguage=ModelLanguage(languageCode,languageTitle) languageArrayList!!.add(modelLanguage) } } private fun sourceLanguageChoose(){ val popupMenu=PopupMenu(this,sourceLanguageChooseBtn) for (i in languageArrayList!!.indices){ popupMenu.menu.add(Menu.NONE,i,i, languageArrayList!![i].languageTitle) } popupMenu.show() popupMenu.setOnMenuItemClickListener { menuItem-> val position=menuItem.itemId sourceLanguageCode=languageArrayList!![position].languageCode sourceLanguageTitle=languageArrayList!![position].languageTitle sourceLanguageChooseBtn.text=sourceLanguageTitle sourceLanguageEt.hint="Enter $sourceLanguageTitle" Log.d(TAG,"sourceLanguageChoose:sourceLanguageCode:$sourceLanguageCode") Log.d(TAG,"sourceLanguageChoose:sourceLanguageTitle:$sourceLanguageTitle") false } } private fun targetLanguageChoose(){ val popupMenu=PopupMenu(this,targetLanguageChooseBtn) for (i in languageArrayList!!.indices){ popupMenu.menu.add(Menu.NONE, i , i, languageArrayList!![i].languageTitle) } popupMenu.show() popupMenu.setOnMenuItemClickListener {menuItem-> val position=menuItem.itemId targetLanguageCode=languageArrayList!![position].languageCode targetLanguageTitle=languageArrayList!![position].languageTitle targetLanguageChooseBtn.text=targetLanguageTitle Log.d(TAG,"targetLanguageChoose:targetLanguageCode:$targetLanguageCode") Log.d(TAG,"targetLanguageChoose:targetLanguageTitle:$targetLanguageTitle") false } } private fun showToast(message:String){ Toast.makeText(this,message,Toast.LENGTH_LONG).show() } }
Language_Translator/app/src/main/java/uz/javokhir_apps/languagetranslator/MainActivity.kt
2826016343
package uz.javokhir_apps.languagetranslator class ModelLanguage (var languageCode:String, var languageTitle:String){ }
Language_Translator/app/src/main/java/uz/javokhir_apps/languagetranslator/ModelLanguage.kt
3110490533
package com.br.createapplicationsystem.respository import com.br.createapplicationsystem.entity.Address import com.br.createapplicationsystem.entity.Credit import com.br.createapplicationsystem.entity.Customer import com.br.createapplicationsystem.repository.CreditRepository import org.assertj.core.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager import org.springframework.test.context.ActiveProfiles import java.math.BigDecimal import java.time.LocalDate import java.time.Month import java.util.* @ActiveProfiles("test") @DataJpaTest @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) class CreditRepositoryTest { @Autowired lateinit var creditRepository: CreditRepository @Autowired lateinit var testEntityManager: TestEntityManager private lateinit var customer: Customer private lateinit var credit1: Credit private lateinit var credit2: Credit @BeforeEach fun setup () { customer = testEntityManager.persist(buildCustomer()) credit1 = testEntityManager.persist(buildCredit(customer = customer)) credit2 = testEntityManager.persist(buildCredit(customer = customer)) } @Test fun `should find credit by credit code`() { //given val creditCode1 = UUID.fromString("aa547c0f-9a6a-451f-8c89-afddce916a29") val creditCode2 = UUID.fromString("49f740be-46a7-449b-84e7-ff5b7986d7ef") credit1.creditCode = creditCode1 credit2.creditCode = creditCode2 //when val fakeCredit1: Credit = creditRepository.findByCreditCode(creditCode1)!! val fakeCredit2: Credit = creditRepository.findByCreditCode(creditCode2)!! //then Assertions.assertThat(fakeCredit1).isNotNull Assertions.assertThat(fakeCredit2).isNotNull Assertions.assertThat(fakeCredit1).isSameAs(credit1) Assertions.assertThat(fakeCredit2).isSameAs(credit2) } @Test fun `should find all credits by customer id`() { //given val customerId: Long = 1L //when val creditList: List<Credit> = creditRepository.findAllByCustomer(customerId) //then Assertions.assertThat(creditList).isNotEmpty Assertions.assertThat(creditList.size).isEqualTo(2) Assertions.assertThat(creditList).contains(credit1, credit2) } private fun buildCredit( creditValue: BigDecimal = BigDecimal.valueOf(500.0), dayFirstInstallment: LocalDate = LocalDate.of(2023, Month.APRIL, 22), numberOfInstallments: Int = 5, customer: Customer ): Credit = Credit( creditValue = creditValue, dayFirstInstallment = dayFirstInstallment, numberOfInstallments = numberOfInstallments, customer = customer ) private fun buildCustomer( firstName: String = "Cami", lastName: String = "Cavalcante", cpf: String = "28475934625", email: String = "[email protected]", password: String = "12345", zipCode: String = "12345", street: String = "Rua da Cami", income: BigDecimal = BigDecimal.valueOf(1000.0), ) = Customer( firstName = firstName, lastName = lastName, cpf = cpf, email = email, password = password, address = Address( zipcode = zipCode, street = street, ), income = income, ) }
sistema_credito-master/src/test/kotlin/com/br/createapplicationsystem/respository/CreditRepositoryTest.kt
2317575458
package com.br.createapplicationsystem import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class CreateApplicationSystemApplicationTests { @Test fun contextLoads() { } }
sistema_credito-master/src/test/kotlin/com/br/createapplicationsystem/CreateApplicationSystemApplicationTests.kt
574890400
package com.br.createapplicationsystem.controller import com.br.createapplicationsystem.dto.CustomerDto import com.br.createapplicationsystem.dto.CustomerUpdateDto import com.br.createapplicationsystem.entity.Customer import com.br.createapplicationsystem.repository.CustomerRepository import com.fasterxml.jackson.databind.ObjectMapper import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.http.MediaType import org.springframework.test.context.ActiveProfiles import org.springframework.test.context.ContextConfiguration import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders import org.springframework.test.web.servlet.result.MockMvcResultHandlers import org.springframework.test.web.servlet.result.MockMvcResultMatchers import java.math.BigDecimal import java.util.* @SpringBootTest @ActiveProfiles("test") @AutoConfigureMockMvc @ContextConfiguration class CustomerControllerTeste { @Autowired private lateinit var customerRepository: CustomerRepository @Autowired private lateinit var mockMvc: MockMvc @Autowired private lateinit var objectMapper: ObjectMapper companion object { const val URL: String = "/api/customers" } @BeforeEach fun setup() = customerRepository.deleteAll() @AfterEach fun tearDown() = customerRepository.deleteAll() @Test fun `should create a customer and return 201 status`() { //given val customerDto: CustomerDto = builderCustomerDto() val valueAsString: String = objectMapper.writeValueAsString(customerDto) //when //then mockMvc.perform( MockMvcRequestBuilders.post(URL) .contentType(MediaType.APPLICATION_JSON) .content(valueAsString) ) .andExpect(MockMvcResultMatchers.status().isCreated) .andExpect(MockMvcResultMatchers.jsonPath("$.firstName").value("Cami")) .andExpect(MockMvcResultMatchers.jsonPath("$.lastName").value("Cavalcante")) .andExpect(MockMvcResultMatchers.jsonPath("$.cpf").value("28475934625")) .andExpect(MockMvcResultMatchers.jsonPath("$.email").value("[email protected]")) .andExpect(MockMvcResultMatchers.jsonPath("$.income").value("1000.0")) .andExpect(MockMvcResultMatchers.jsonPath("$.zipCode").value("000000")) .andExpect(MockMvcResultMatchers.jsonPath("$.street").value("Rua da Cami, 123")) .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)) .andDo(MockMvcResultHandlers.print()) } @Test fun `should not save a customer with same CPF and return 409 status`() { //given customerRepository.save(builderCustomerDto().toEntity()) val customerDto: CustomerDto = builderCustomerDto() val valueAsString: String = objectMapper.writeValueAsString(customerDto) //when //then mockMvc.perform( MockMvcRequestBuilders.post(URL) .contentType(MediaType.APPLICATION_JSON) .content(valueAsString) ) .andExpect(MockMvcResultMatchers.status().isConflict) .andExpect(MockMvcResultMatchers.jsonPath("$.title").value("Conflict! Consult the documentation")) .andExpect(MockMvcResultMatchers.jsonPath("$.timestamp").exists()) .andExpect(MockMvcResultMatchers.jsonPath("$.status").value(409)) .andExpect( MockMvcResultMatchers.jsonPath("$.exception") .value("class org.springframework.dao.DataIntegrityViolationException") ) .andExpect(MockMvcResultMatchers.jsonPath("$.details[*]").isNotEmpty) .andDo(MockMvcResultHandlers.print()) } @Test fun `should not save a customer with empty firstName and return 400 status`() { //given val customerDto: CustomerDto = builderCustomerDto(firstName = "") val valueAsString: String = objectMapper.writeValueAsString(customerDto) //when //then mockMvc.perform( MockMvcRequestBuilders.post(URL) .content(valueAsString) .contentType(MediaType.APPLICATION_JSON) ) .andExpect(MockMvcResultMatchers.status().isBadRequest) .andExpect(MockMvcResultMatchers.jsonPath("$.title").value("Bad Request! Consult the documentation")) .andExpect(MockMvcResultMatchers.jsonPath("$.timestamp").exists()) .andExpect(MockMvcResultMatchers.jsonPath("$.status").value(400)) .andExpect( MockMvcResultMatchers.jsonPath("$.exception") .value("class org.springframework.web.bind.MethodArgumentNotValidException") ) .andExpect(MockMvcResultMatchers.jsonPath("$.details[*]").isNotEmpty) .andDo(MockMvcResultHandlers.print()) } @Test fun `should find customer by id and return 200 status`() { //given val customer: Customer = customerRepository.save(builderCustomerDto().toEntity()) //when //then mockMvc.perform( MockMvcRequestBuilders.get("$URL/${customer.id}") .accept(MediaType.APPLICATION_JSON) ) .andExpect(MockMvcResultMatchers.status().isOk) .andExpect(MockMvcResultMatchers.jsonPath("$.firstName").value("Cami")) .andExpect(MockMvcResultMatchers.jsonPath("$.lastName").value("Cavalcante")) .andExpect(MockMvcResultMatchers.jsonPath("$.cpf").value("28475934625")) .andExpect(MockMvcResultMatchers.jsonPath("$.email").value("[email protected]")) .andExpect(MockMvcResultMatchers.jsonPath("$.income").value("1000.0")) .andExpect(MockMvcResultMatchers.jsonPath("$.zipCode").value("000000")) .andExpect(MockMvcResultMatchers.jsonPath("$.street").value("Rua da Cami, 123")) //.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)) .andDo(MockMvcResultHandlers.print()) } @Test fun `should not find customer with invalid id and return 400 status`() { //given val invalidId: Long = 2L //when //then mockMvc.perform( MockMvcRequestBuilders.get("$URL/$invalidId") .accept(MediaType.APPLICATION_JSON) ) .andExpect(MockMvcResultMatchers.status().isBadRequest) .andExpect(MockMvcResultMatchers.jsonPath("$.title").value("Bad Request! Consult the documentation")) .andExpect(MockMvcResultMatchers.jsonPath("$.timestamp").exists()) .andExpect(MockMvcResultMatchers.jsonPath("$.status").value(400)) .andExpect( MockMvcResultMatchers.jsonPath("$.exception") .value("class me.dio.credit.application.system.exception.BusinessException") ) .andExpect(MockMvcResultMatchers.jsonPath("$.details[*]").isNotEmpty) .andDo(MockMvcResultHandlers.print()) } @Test fun `should delete customer by id and return 204 status`() { //given val customer: Customer = customerRepository.save(builderCustomerDto().toEntity()) //when //then mockMvc.perform( MockMvcRequestBuilders.delete("$URL/${customer.id}") .accept(MediaType.APPLICATION_JSON) ) .andExpect(MockMvcResultMatchers.status().isNoContent) .andDo(MockMvcResultHandlers.print()) } @Test fun `should not delete customer by id and return 400 status`() { //given val invalidId: Long = Random().nextLong() //when //then mockMvc.perform( MockMvcRequestBuilders.delete("$URL/${invalidId}") .accept(MediaType.APPLICATION_JSON) ) .andExpect(MockMvcResultMatchers.status().isBadRequest) .andExpect(MockMvcResultMatchers.jsonPath("$.title").value("Bad Request! Consult the documentation")) .andExpect(MockMvcResultMatchers.jsonPath("$.timestamp").exists()) .andExpect(MockMvcResultMatchers.jsonPath("$.status").value(400)) .andExpect( MockMvcResultMatchers.jsonPath("$.exception") .value("class me.dio.credit.application.system.exception.BusinessException") ) .andExpect(MockMvcResultMatchers.jsonPath("$.details[*]").isNotEmpty) .andDo(MockMvcResultHandlers.print()) } @Test fun `should update a customer and return 200 status`() { //given val customer: Customer = customerRepository.save(builderCustomerDto().toEntity()) val customerUpdateDto: CustomerUpdateDto = builderCustomerUpdateDto() val valueAsString: String = objectMapper.writeValueAsString(customerUpdateDto) //when //then mockMvc.perform( MockMvcRequestBuilders.patch("$URL?customerId=${customer.id}") .contentType(MediaType.APPLICATION_JSON) .content(valueAsString) ) .andExpect(MockMvcResultMatchers.status().isOk) .andExpect(MockMvcResultMatchers.jsonPath("$.firstName").value("CamiUpdate")) .andExpect(MockMvcResultMatchers.jsonPath("$.lastName").value("CavalcanteUpdate")) .andExpect(MockMvcResultMatchers.jsonPath("$.cpf").value("28475934625")) .andExpect(MockMvcResultMatchers.jsonPath("$.email").value("[email protected]")) .andExpect(MockMvcResultMatchers.jsonPath("$.income").value("5000.0")) .andExpect(MockMvcResultMatchers.jsonPath("$.zipCode").value("45656")) .andExpect(MockMvcResultMatchers.jsonPath("$.street").value("Rua Updated")) //.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)) .andDo(MockMvcResultHandlers.print()) } @Test fun `should not update a customer with invalid id and return 400 status`() { //given val invalidId: Long = Random().nextLong() val customerUpdateDto: CustomerUpdateDto = builderCustomerUpdateDto() val valueAsString: String = objectMapper.writeValueAsString(customerUpdateDto) //when //then mockMvc.perform( MockMvcRequestBuilders.patch("$URL?customerId=$invalidId") .contentType(MediaType.APPLICATION_JSON) .content(valueAsString) ) .andExpect(MockMvcResultMatchers.status().isBadRequest) .andExpect(MockMvcResultMatchers.jsonPath("$.title").value("Bad Request! Consult the documentation")) .andExpect(MockMvcResultMatchers.jsonPath("$.timestamp").exists()) .andExpect(MockMvcResultMatchers.jsonPath("$.status").value(400)) .andExpect( MockMvcResultMatchers.jsonPath("$.exception") .value("class me.dio.credit.application.system.exception.BusinessException") ) .andExpect(MockMvcResultMatchers.jsonPath("$.details[*]").isNotEmpty) .andDo(MockMvcResultHandlers.print()) } private fun builderCustomerDto( firstName: String = "Cami", lastName: String = "Cavalcante", cpf: String = "28475934625", email: String = "[email protected]", income: BigDecimal = BigDecimal.valueOf(1000.0), password: String = "1234", zipCode: String = "000000", street: String = "Rua da Cami, 123", ) = CustomerDto( firstName = firstName, lastName = lastName, cpf = cpf, email = email, income = income, password = password, zipcode = zipCode, street = street ) private fun builderCustomerUpdateDto( firstName: String = "CamiUpdate", lastName: String = "CavalcanteUpdate", income: BigDecimal = BigDecimal.valueOf(5000.0), zipCode: String = "45656", street: String = "Rua Updated" ): CustomerUpdateDto = CustomerUpdateDto( firstName = firstName, lastName = lastName, income = income, zipcode = zipCode, street = street ) }
sistema_credito-master/src/test/kotlin/com/br/createapplicationsystem/controller/CustomerControllerTeste.kt
843049266
package com.br.createapplicationsystem.service import com.br.createapplicationsystem.entity.Address import com.br.createapplicationsystem.entity.Customer import com.br.createapplicationsystem.exception.BusinesseException import com.br.createapplicationsystem.repository.CustomerRepository import com.br.createapplicationsystem.service.impl.CustomerService import io.mockk.every import io.mockk.impl.annotations.InjectMockKs import io.mockk.impl.annotations.MockK import io.mockk.junit5.MockKExtension import io.mockk.just import io.mockk.runs import io.mockk.verify import org.assertj.core.api.Assertions import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import java.math.BigDecimal import java.util.* @ExtendWith(MockKExtension::class) class CustomerServiceTest { @MockK lateinit var customerRepository: CustomerRepository @InjectMockKs lateinit var customerService: CustomerService @Test fun `should create customer`(){ //given val fakeCustomer: Customer = buildCustomer() every { customerRepository.save(any()) } returns fakeCustomer //when val actual: Customer = customerService.save(fakeCustomer) //then Assertions.assertThat(actual).isNotNull Assertions.assertThat(actual).isSameAs(fakeCustomer) verify(exactly = 1) { customerRepository.save(fakeCustomer) } } @Test fun `should find customer by id`() { //given val fakeId: Long = Random().nextLong() val fakeCustomer: Customer = buildCustomer(id = fakeId) every { customerRepository.findById(fakeId) } returns Optional.of(fakeCustomer) //when val actual: Customer = customerService.findById(fakeId) //then Assertions.assertThat(actual).isNotNull Assertions.assertThat(actual).isExactlyInstanceOf(Customer::class.java) Assertions.assertThat(actual).isSameAs(fakeCustomer) verify(exactly = 1) { customerRepository.findById(fakeId) } } @Test fun `should not find customer by invalid id and throw BusinessException`() { //given val fakeId: Long = Random().nextLong() every { customerRepository.findById(fakeId) } returns Optional.empty() //when //then Assertions.assertThatExceptionOfType(BusinesseException::class.java) .isThrownBy { customerService.findById(fakeId) } .withMessage("Id $fakeId not found") verify(exactly = 1) { customerRepository.findById(fakeId) } } @Test fun `should delete customer by id`() { //given val fakeId: Long = Random().nextLong() val fakeCustomer: Customer = buildCustomer(id = fakeId) every { customerRepository.findById(fakeId) } returns Optional.of(fakeCustomer) every { customerRepository.delete(fakeCustomer) } just runs //when customerService.delete(fakeId) //then verify(exactly = 1) { customerRepository.findById(fakeId) } verify(exactly = 1) { customerRepository.delete(fakeCustomer) } } private fun buildCustomer( firstName: String = "pablo", lastName: String = "Vini", cpf: String = "28475934625", email: String = "[email protected]", password: String = "123", zipCode: String = "123", street: String = "Rua da Victor", income: BigDecimal = BigDecimal.valueOf(1000.0), id: Long = 1L ) = Customer( firstName = firstName, lastName = lastName, cpf = cpf, email = email, password = password, address = Address( zipcode = zipCode, street = street, ), income = income, id = id ) }
sistema_credito-master/src/test/kotlin/com/br/createapplicationsystem/service/CustomerServiceTest.kt
1493134926
package com.br.createapplicationsystem.dto import com.br.createapplicationsystem.entity.Address import com.br.createapplicationsystem.entity.Customer import jakarta.validation.constraints.Email import jakarta.validation.constraints.NotEmpty import jakarta.validation.constraints.NotNull import org.hibernate.validator.constraints.br.CPF import java.math.BigDecimal data class CustomerDto ( @field:NotEmpty(message = "Precisa digitar um nome") val firstName: String, @field:NotEmpty(message = "Precisa digitar o ultimo nome") val lastName: String, @field:NotEmpty(message = "CPF vazio") @CPF(message = "Este CPF é invalido")val cpf: String, @field:NotNull(message = "Invalido dados") val income: BigDecimal, @field:NotEmpty(message = "Precisa digitar um email") @field:Email(message = "Email invalido") val email: String, @field:NotEmpty(message = "Precisa digitar uma senha") val password: String, @field:NotEmpty(message = "Precisa digitar um cep") val zipcode: String, @field:NotEmpty(message = "Precisa digitar uma rua ") val street: String ){ fun toEntity():Customer = Customer( firstName = this.firstName, lastName = this.lastName, cpf = this.cpf, income = this.income, email = this.email, password = this.password, address = Address( zipcode = this.zipcode, street = this.street ) ) }
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/dto/CustomerDto.kt
2163018395
package com.br.createapplicationsystem.dto import com.br.createapplicationsystem.entity.Credit import com.br.createapplicationsystem.entity.Customer import jakarta.validation.constraints.Future import jakarta.validation.constraints.NotNull import java.math.BigDecimal import java.time.LocalDate data class CreditoDto( @field:NotNull val creditValue: BigDecimal, @field:Future val dayFirstOfInstallment: LocalDate, val numberOfIntallments: Int, @field:NotNull val customerId: Long ) { fun toEntity(): Credit = Credit( creditValue = this.creditValue, dayFirstInstallment = this.dayFirstOfInstallment, numberOfInstallments = this.numberOfIntallments, customer = Customer(id = this.customerId) ) }
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/dto/CreditoDto.kt
2962424132
package com.br.createapplicationsystem.dto import com.br.createapplicationsystem.entity.Credit import com.br.createapplicationsystem.enummeration.Status import java.math.BigDecimal import java.time.LocalDate import java.util.* data class CreditView( val creditCode: UUID, val creditValue: BigDecimal, val numberOfIntallments: Int, val status: Status, val emailCustomer: String?, val incomeCustomer: BigDecimal? ) { constructor(credit: Credit): this( creditCode = credit.creditCode, creditValue = credit.creditValue, numberOfIntallments = credit.numberOfInstallments, status = credit.status, emailCustomer = credit.customer?.email, incomeCustomer = credit.customer?.income ) }
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/dto/CreditView.kt
1372324001
package com.br.createapplicationsystem.dto import com.br.createapplicationsystem.entity.Customer import jakarta.validation.constraints.NotEmpty import jakarta.validation.constraints.NotNull import java.math.BigDecimal data class CustomerUpdateDto( @field:NotEmpty(message = "Precisa digitar um nome") val firstName: String, @field:NotEmpty(message = "Precisa digitar um nome") val lastName: String, @field:NotNull(message = "Invalido dados") val income: BigDecimal, @field:NotEmpty(message = "Precisa digitar um nome") val zipcode: String, @field:NotEmpty(message = "Precisa digitar um nome") val street: String ) { fun toEntity(customer: Customer): Customer{ customer.firstName = this.firstName customer.lastName = this.lastName customer.income = this.income customer.address.street = this.street customer.address.zipcode = this.zipcode return customer } }
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/dto/CustomerUpdateDto.kt
2420293045
package com.br.createapplicationsystem.dto import com.br.createapplicationsystem.entity.Credit import java.math.BigDecimal import java.util.* data class CreditViewList( val creditCode: UUID, val creditValue: BigDecimal, val numberOfIntallments: Int, ) { constructor(credit: Credit) : this( creditCode = credit.creditCode, creditValue = credit.creditValue, numberOfIntallments = credit.numberOfInstallments ) }
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/dto/CreditViewList.kt
1708053321
package com.br.createapplicationsystem.dto import com.br.createapplicationsystem.entity.Customer import java.math.BigDecimal data class CustomerView( val firstName: String, val lastName: String, val cpf: String, val income: BigDecimal, val email: String, val zipcode: String, val street: String, val id: Long? ) { constructor(customer: Customer):this ( firstName = customer.firstName, lastName = customer.lastName, cpf = customer.cpf, income = customer.income, email = customer.email, zipcode = customer.address.zipcode, street = customer.address.street, id = customer.id ) }
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/dto/CustomerView.kt
2398774744
package com.br.createapplicationsystem.configuration import org.springdoc.core.models.GroupedOpenApi import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class Swagger3Config { @Bean fun publicApi(): GroupedOpenApi? { return GroupedOpenApi.builder() .group("springcreditapplicationsystem-public") .pathsToMatch("/customers/**", "/credit/**") .build() } }
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/configuration/Swagger3Config.kt
2087106740
package com.br.createapplicationsystem.repository import com.br.createapplicationsystem.entity.Credit import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.jpa.repository.Query import org.springframework.stereotype.Repository import java.util.* @Repository interface CreditRepository: JpaRepository<Credit, Long>{ fun findByCreditCode(creditCode: UUID): Credit? @Query(value = "SELECT * FROM CREDITO WHERE CUSTOMER_ID = ?1", nativeQuery = true) fun findAllByCustomer(customerId: Long): List<Credit> }
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/repository/CreditRepository.kt
3806485029
package com.br.createapplicationsystem.repository import com.br.createapplicationsystem.entity.Customer import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository @Repository interface CustomerRepository: JpaRepository<Customer, Long>
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/repository/CustomerRepository.kt
991144753
package com.br.createapplicationsystem.entity import com.br.createapplicationsystem.enummeration.Status import jakarta.persistence.* import java.math.BigDecimal import java.time.LocalDate import java.util.* @Entity @Table(name = "Credito") data class Credit ( @Column(nullable = false, unique = true) var creditCode: UUID = UUID.randomUUID(), @Column(nullable = false) val creditValue: BigDecimal = BigDecimal.ZERO, @Column(nullable = false) val dayFirstInstallment: LocalDate, @Column(nullable = false) val numberOfInstallments: Int = 0, @Enumerated(value = EnumType.STRING) val status: Status = Status.IN_PROGRESS, @ManyToOne var customer: Customer? = null, @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long? = null )
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/entity/Credit.kt
159052166
package com.br.createapplicationsystem.entity import jakarta.persistence.* import java.math.BigDecimal import java.net.Inet4Address @Entity @Table(name = "Cliente") data class Customer ( @Column(nullable = false) var firstName: String = "", @Column(nullable = false) var lastName: String = "", @Column(nullable = false, unique = true) var cpf: String = "", @Column(nullable = false, unique = true) var email: String = "", @Column(nullable = false) var income: BigDecimal = BigDecimal.ZERO, @Column(nullable = false) var password: String = "", @Column(nullable = false) @Embedded var address: Address = Address(), @Column(nullable = false) @OneToMany(fetch = FetchType.LAZY, cascade = arrayOf(CascadeType.REMOVE, CascadeType.PERSIST), mappedBy = "customer" ) var credits: List<Credit> = mutableListOf(), @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long? = null )
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/entity/Customer.kt
3460596146
package com.br.createapplicationsystem.entity import jakarta.persistence.Column import jakarta.persistence.Embeddable @Embeddable data class Address ( @Column(nullable = false) var zipcode: String = "", @Column(nullable = false) var street: String = "" )
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/entity/Address.kt
585196083
package com.br.createapplicationsystem import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class CreateApplicationSystemApplication fun main(args: Array<String>) { runApplication<CreateApplicationSystemApplication>(*args) }
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/CreateApplicationSystemApplication.kt
4138238702
package com.br.createapplicationsystem.controller import com.br.createapplicationsystem.dto.CustomerDto import com.br.createapplicationsystem.dto.CustomerUpdateDto import com.br.createapplicationsystem.dto.CustomerView import com.br.createapplicationsystem.entity.Customer import com.br.createapplicationsystem.service.impl.CustomerService import jakarta.validation.Valid import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PatchMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("/customers") class CustomerController( private val customerService: CustomerService ) { @PostMapping fun saveCustomer(@RequestBody @Valid customerDto: CustomerDto): ResponseEntity<String>{ val savedCustomer = this.customerService.save(customerDto.toEntity()) return ResponseEntity. status(HttpStatus.CREATED).body("Customer ${savedCustomer.email} saved!") } @GetMapping("/{id}") fun findById(@PathVariable id: Long): ResponseEntity<CustomerView> { val customer: Customer = this.customerService.findById(id) return ResponseEntity.status(HttpStatus.OK).body(CustomerView(customer)) } @DeleteMapping("/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) fun deleteCustomer(@PathVariable id: Long) = this.customerService.delete(id) @PatchMapping fun updateCustomer( @RequestParam(value = "customerId") id: Long, @Valid @RequestBody customerUpdateDto: CustomerUpdateDto): ResponseEntity<CustomerView>{ val customer: Customer = this.customerService.findById(id) val customerToUpdate: Customer = customerUpdateDto.toEntity(customer) val customerUpdate: Customer = this.customerService.save(customerToUpdate) return ResponseEntity.status(HttpStatus.OK).body(CustomerView(customerUpdate)) } }
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/controller/CustomerController.kt
2769515674
package com.br.createapplicationsystem.controller import com.br.createapplicationsystem.dto.CreditView import com.br.createapplicationsystem.dto.CreditViewList import com.br.createapplicationsystem.dto.CreditoDto import com.br.createapplicationsystem.entity.Credit import com.br.createapplicationsystem.service.impl.CreditService import jakarta.validation.Valid import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import java.util.* import java.util.stream.Collectors @RestController @RequestMapping("/credit") class CreditController( private val creditService: CreditService ){ @PostMapping fun savedCredit(@RequestBody @Valid creditDto: CreditoDto): ResponseEntity<String>{ val credit: Credit = this.creditService.save(creditDto.toEntity()) return ResponseEntity.status(HttpStatus.CREATED).body("Credit ${credit.creditCode} - Customer ${credit.customer?.firstName} saved!") } @GetMapping fun findAllByCustomerId(@RequestParam(value = "customerId") customerId: Long) : ResponseEntity<List<CreditViewList>>{ val creditViewList: List<CreditViewList> = this.creditService.findAllByCustomer(customerId).stream() .map { credit: Credit -> CreditViewList(credit) }.collect(Collectors.toList()) return ResponseEntity.status(HttpStatus.OK).body(creditViewList) } @GetMapping("/{creditCode}") fun findByCreditCode(@RequestParam(value = "customerId") customerId: Long, @PathVariable creditCode: UUID ) : ResponseEntity<CreditView> { val credit: Credit = this.creditService.findByCreditCode(customerId, creditCode) return ResponseEntity.status(HttpStatus.OK).body(CreditView(credit)) } }
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/controller/CreditController.kt
3930028517
package com.br.createapplicationsystem.enummeration enum class Status { IN_PROGRESS, APPROVED, REJECT }
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/enummeration/Status.kt
422748293
package com.br.createapplicationsystem.service.impl import com.br.createapplicationsystem.entity.Customer import com.br.createapplicationsystem.exception.BusinesseException import com.br.createapplicationsystem.repository.CustomerRepository import com.br.createapplicationsystem.service.ICustomerService import org.springframework.stereotype.Service @Service class CustomerService( private val customerRepository: CustomerRepository ): ICustomerService { override fun save(customer: Customer): Customer = this.customerRepository.save(customer) override fun findById(id: Long): Customer = this.customerRepository.findById(id).orElseThrow{ throw BusinesseException("Id $id not found") } override fun delete(id: Long) { val customer: Customer = this.findById(id) this.customerRepository.delete(customer) } }
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/service/impl/CustomerService.kt
1496467753
package com.br.createapplicationsystem.service.impl import com.br.createapplicationsystem.entity.Credit import com.br.createapplicationsystem.exception.BusinesseException import com.br.createapplicationsystem.repository.CreditRepository import com.br.createapplicationsystem.service.ICreditService import org.springframework.stereotype.Service import java.lang.IllegalArgumentException import java.util.* @Service class CreditService( private val creditRepository: CreditRepository, private val customerService: CustomerService ):ICreditService { override fun save(credit: Credit): Credit { credit.apply { customer = customerService.findById(credit.customer?.id!!) } return this.creditRepository.save(credit) } override fun findAllByCustomer(customerId: Long): List<Credit> = this.creditRepository.findAllByCustomer(customerId) override fun findByCreditCode(customerId: Long, creditCode: UUID): Credit { val credit: Credit = (this.creditRepository.findByCreditCode(creditCode) ?: throw BusinesseException("Creditcode $creditCode not found")) return if (credit.customer?.id == customerId) credit else throw IllegalArgumentException("Contact admin") } }
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/service/impl/CreditService.kt
3902823206
package com.br.createapplicationsystem.service import com.br.createapplicationsystem.entity.Customer interface ICustomerService { fun save(customer: Customer): Customer fun findById(id: Long): Customer fun delete(id: Long) }
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/service/ICustomerService.kt
1272344636
package com.br.createapplicationsystem.service import com.br.createapplicationsystem.entity.Credit import java.util.* interface ICreditService { fun save(credit: Credit): Credit fun findAllByCustomer(customerId: Long): List<Credit> fun findByCreditCode(customerId: Long, creditCode: UUID): Credit }
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/service/ICreditService.kt
3428239859
package com.br.createapplicationsystem.exception data class BusinesseException(override val message: String?): RuntimeException(message) { }
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/exception/BusinesseException.kt
2671541369
package com.br.createapplicationsystem.exception import org.springframework.dao.DataAccessException import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.validation.FieldError import org.springframework.validation.ObjectError import org.springframework.web.bind.MethodArgumentNotValidException import org.springframework.web.bind.annotation.ExceptionHandler import org.springframework.web.bind.annotation.RestControllerAdvice import java.time.LocalDateTime @RestControllerAdvice class RestExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException::class) fun handlerValidException(ex: MethodArgumentNotValidException): ResponseEntity<ExceptionDetails>{ val erros: MutableMap<String, String?> = HashMap() ex.bindingResult.allErrors.stream().forEach { erro: ObjectError -> val fieldName: String = (erro as FieldError).field val messageError: String? = erro.defaultMessage erros[fieldName] = messageError } return ResponseEntity( ExceptionDetails( title = "Bad Request! Consult the documentation", timestamp = LocalDateTime.now(), status = HttpStatus.BAD_REQUEST.value(), exception = ex.objectName.toString(), details = erros ), HttpStatus.BAD_REQUEST ) } @ExceptionHandler(DataAccessException::class) fun handlerValidException(ex: DataAccessException): ResponseEntity<ExceptionDetails>{ return ResponseEntity.status(HttpStatus.CONFLICT) .body( ExceptionDetails( title = "Bad Request! Consult the documentation", timestamp = LocalDateTime.now(), status = HttpStatus.CONFLICT.value(), exception = ex.javaClass.toString(), details = mutableMapOf(ex.cause.toString() to ex.message) )) } @ExceptionHandler(BusinesseException::class) fun handlerValidException(ex: BusinesseException): ResponseEntity<ExceptionDetails>{ return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body( ExceptionDetails( title = "Bad Request! Consult the documentation", timestamp = LocalDateTime.now(), status = HttpStatus.BAD_REQUEST.value(), exception = ex.javaClass.toString(), details = mutableMapOf(ex.cause.toString() to ex.message) )) } @ExceptionHandler(IllegalArgumentException::class) fun handlerValidException(ex: IllegalArgumentException): ResponseEntity<ExceptionDetails>{ return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body( ExceptionDetails( title = "Bad Request! Consult the documentation", timestamp = LocalDateTime.now(), status = HttpStatus.BAD_REQUEST.value(), exception = ex.javaClass.toString(), details = mutableMapOf(ex.cause.toString() to ex.message) )) } }
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/exception/RestExceptionHandler.kt
4216698272
package com.br.createapplicationsystem.exception import java.lang.Exception import java.time.LocalDateTime data class ExceptionDetails( val title: String, val timestamp: LocalDateTime, val status: Int, val exception: String, val details: MutableMap<String, String?> ) { }
sistema_credito-master/src/main/kotlin/com/br/createapplicationsystem/exception/ExceptionDetails.kt
105282242
package com.example.aplicatie_calcul_mobil 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.aplicatie_calcul_mobil", appContext.packageName) } }
Proiect_Calcul_Mobil/app/src/androidTest/java/com/example/aplicatie_calcul_mobil/ExampleInstrumentedTest.kt
2676285664
package com.example.aplicatie_calcul_mobil 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) } }
Proiect_Calcul_Mobil/app/src/test/java/com/example/aplicatie_calcul_mobil/ExampleUnitTest.kt
2003578420