content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.tourismapp
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)
}
} | Cultoura-BitBandits-Vihaan007/app/src/test/java/com/example/tourismapp/ExampleUnitTest.kt | 2675217019 |
package com.example.tourismapp.viewmodel
import android.util.Log
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.tourismapp.RetrofitClient
import kotlinx.coroutines.launch
import com.example.tourismapp.data.*
class LocationViewModel: ViewModel() {
private val _location= mutableStateOf<LocationData?>(null)
val location : State<LocationData?> = _location
private val _address = mutableStateOf(listOf<GeocodingResult>())
val address: State<List<GeocodingResult>> = _address
fun updateLocation(newLocation: LocationData){
_location.value = newLocation
}
fun fetchAddress(latlng: String){
try{
viewModelScope.launch {
val result = RetrofitClient.create().getAddressFromCoordinates(
latlng,
"AIzaSyCnfwyKH4V8CE5XR38GGg_uZysFyHIXeZU"
)
_address.value = result.results
}
}catch(e:Exception) {
Log.d("res1", "${e.cause} ${e.message}")
}
}
} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/viewmodel/LocationViewModel.kt | 3729305101 |
package com.example.tourismapp.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import androidx.lifecycle.ViewModel
import com.example.tourismapp.Injection
import com.example.tourismapp.data.User
import com.example.tourismapp.data.Result.*
import com.example.tourismapp.data.UserRepository
import com.google.firebase.auth.FirebaseAuth
class HomeViewModel : ViewModel() {
private val userRepository: UserRepository
private val _user = MutableLiveData<User>()
val user : LiveData<User> get() = _user
val selected = MutableLiveData<String>()
val state = MutableLiveData<String>()
init{
userRepository = UserRepository(
FirebaseAuth.getInstance(),
Injection.instance()
)
loadCurrentUser()
selected.value = "Home"
}
private fun loadCurrentUser() {
viewModelScope.launch {
when (val result = userRepository.getCurrentUser()) {
is Success -> _user.value = result.data
is Error -> {
}
}
}
}
fun Navigate(value:String){
selected.value = value
}
fun setState(value:String){
state.value = value
}
} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/viewmodel/HomeViewModel.kt | 2057146418 |
package com.example.tourismapp.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.firebase.auth.FirebaseAuth
import com.example.tourismapp.Injection
import com.example.tourismapp.data.*
import kotlinx.coroutines.launch
class AuthViewModel : ViewModel() {
private val userRepository: UserRepository
init {
userRepository = UserRepository(
FirebaseAuth.getInstance(),
Injection.instance()
)
}
private val _authResult = MutableLiveData<Result<Boolean>?>()
val authResult: LiveData<Result<Boolean>?> get() = _authResult
fun signUp(email: String, password: String, firstName: String, lastName: String) {
viewModelScope.launch {
_authResult.value = userRepository.signUp(email, password, firstName, lastName)
}
}
fun reset(){
_authResult.value = null
}
fun login(email: String, password: String) {
viewModelScope.launch {
_authResult.value = userRepository.login(email, password)
}
}
} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/viewmodel/AuthViewModel.kt | 960828885 |
package com.example.tourismapp.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) | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/ui/theme/Color.kt | 4217989353 |
package com.example.tourismapp.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 TourismAppTheme(
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
)
} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/ui/theme/Theme.kt | 1103210150 |
package com.example.tourismapp.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
)
*/
) | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/ui/theme/Type.kt | 3417981519 |
package com.example.tourismapp
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import com.example.tourismapp.ui.theme.TourismAppTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
TourismAppTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
NavigationGraph()
}
}
}
}
}
| Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/MainActivity.kt | 2866429887 |
package com.example.tourismapp
import com.example.tourismapp.utils.GeocodingApiService
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitClient {
private const val BASE_URL = "https://maps.googleapis.com/"
fun create(): GeocodingApiService {
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
return retrofit.create(GeocodingApiService::class.java)
}
} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/RetrofitClient.kt | 133574485 |
package com.example.tourismapp
sealed class Screens(val route:String){
data object LoginScreen : Screens("login-screen")
data object SignUpScreen : Screens("signup-screen")
data object HomePage:Screens("homepage")
data object LocationScreen: Screens("location screen")
data object Loading: Screens("Loading")
} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/Screens.kt | 3688891111 |
package com.example.tourismapp
import android.content.Context
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.NavHostController
import androidx.navigation.compose.composable
import androidx.navigation.compose.dialog
import androidx.navigation.compose.rememberNavController
import com.example.tourismapp.screens.HomePage
import com.example.tourismapp.screens.LoadingScreen
import com.example.tourismapp.screens.LocationSelectionScreen
import com.example.tourismapp.screens.LoginScreen
import com.example.tourismapp.screens.SignUpScreen
import com.example.tourismapp.utils.LocationUtils
import com.example.tourismapp.viewmodel.AuthViewModel
import com.example.tourismapp.viewmodel.HomeViewModel
import com.example.tourismapp.viewmodel.LocationViewModel
@Composable
fun NavigationGraph(
authViewModel: AuthViewModel = viewModel(),
navController: NavHostController = rememberNavController(),
homeViewModel: HomeViewModel= viewModel(),
locationViewModel: LocationViewModel= viewModel(),
context: Context = LocalContext.current
) {
val locationUtils = LocationUtils(context)
NavHost(
navController = navController,
startDestination = Screens.SignUpScreen.route
) {
composable(Screens.SignUpScreen.route) {
SignUpScreen(
onNavigateToLogin = { navController.navigate(Screens.LoginScreen.route) }
)
}
composable(Screens.LoginScreen.route) {
LoginScreen(
authViewModel,
onNavigateToSignUp = {navController.navigate(Screens.SignUpScreen.route) }
){
navController.navigate(Screens.Loading.route){
this.launchSingleTop
}
}
}
composable(Screens.HomePage.route){
HomePage(homeViewModel,locationUtils,locationViewModel,navController,context)
}
dialog(Screens.LocationScreen.route){
locationViewModel.location.value?.let{it1 ->
LocationSelectionScreen(location = it1, onLocationSelected = {locationdata->
locationViewModel.fetchAddress("${locationdata.latitude},${locationdata.longitude}")
navController.popBackStack()
}, goBack = {navController.popBackStack()})
}
}
dialog(Screens.Loading.route){
LoadingScreen(authViewModel = authViewModel, navController = navController)
}
}
}
| Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/Navigation.kt | 1838689533 |
package com.example.tourismapp.utils
import com.example.tourismapp.data.GeocodingResponse
import retrofit2.http.GET
import retrofit2.http.Query
interface GeocodingApiService {
@GET("maps/api/geocode/json")
suspend fun getAddressFromCoordinates(
@Query("latlng") latlng: String,
@Query("key") apiKey: String
): GeocodingResponse
} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/utils/GeocodingApiService.kt | 3441274051 |
package com.example.tourismapp.utils
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.location.Address
import android.location.Geocoder
import android.os.Looper
import androidx.core.content.ContextCompat
import com.example.tourismapp.data.LocationData
import com.example.tourismapp.viewmodel.LocationViewModel
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationResult
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.Priority
import com.google.android.gms.maps.model.LatLng
import java.util.Locale
class LocationUtils(val context: Context) {
private val _fusedLocationClient: FusedLocationProviderClient
= LocationServices.getFusedLocationProviderClient(context)
@SuppressLint("MissingPermission")
fun requestLocationUpdates(viewModel: LocationViewModel){
val locationCallback = object : LocationCallback(){
override fun onLocationResult(locationResult: LocationResult) {
super.onLocationResult(locationResult)
locationResult.lastLocation?.let {
val location = LocationData(latitude = it.latitude, longitude = it.longitude)
viewModel.updateLocation(location)
}
}
}
val locationRequest = LocationRequest.Builder(
Priority.PRIORITY_HIGH_ACCURACY, 1000).build()
_fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper())
}
fun hasLocationPermission(context: Context):Boolean{
return ContextCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&&
ContextCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
}
fun reverseGeocodeLocation(location: LocationData) : String{
val geocoder = Geocoder(context, Locale.getDefault())
val coordinate = LatLng(location.latitude, location.longitude)
val addresses:MutableList<Address>? =
geocoder.getFromLocation(coordinate.latitude, coordinate.longitude, 1)
return if(addresses?.isNotEmpty() == true){
addresses[0].getAddressLine(0)
}else{
"Address not found"
}
}
} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/utils/LocationUtils.kt | 1214137766 |
package com.example.tourismapp.screens
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.example.tourismapp.data.User
@Composable
fun ProfilePage(paddingValues: PaddingValues, user: User?){
LazyColumn(
modifier = Modifier.padding(paddingValues)
) {
}
} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/screens/ProfilePage.kt | 37658609 |
package com.example.tourismapp.screens
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.Arrangement
import androidx.compose.foundation.layout.Column
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.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.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 androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.VisualTransformation
import coil.compose.rememberAsyncImagePainter
import com.example.tourismapp.Address
import com.example.tourismapp.R
import com.example.tourismapp.viewmodel.AuthViewModel
@Composable
fun LoginScreen(
authViewModel: AuthViewModel,
onNavigateToSignUp: () -> Unit,
onSignInSuccess:()->Unit
) {
var email by remember { mutableStateOf("") }
var password by remember {mutableStateOf("")
}
var isVisible by remember{ mutableStateOf(false)}
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
.background(color = Color.White),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
){
Text(text = stringResource(R.string.app_name), fontWeight = FontWeight.Bold, color= Color.Black, fontSize = 45.sp)
Image(painter = rememberAsyncImagePainter(Address.path) , contentDescription = null,modifier = Modifier
.size(200.dp)
.clip(
CircleShape
)
.border(4.dp, Color.Yellow, CircleShape))
Text(text = "Festival of India", fontWeight = FontWeight.Light, color= Color.Gray)
OutlinedTextField(
value = email,
onValueChange = { email = it },
label = { Text("Email") },
shape = RoundedCornerShape(50),
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
colors = OutlinedTextFieldDefaults.colors(
cursorColor = colorResource(id = R.color.black),
// using predefined Color
focusedTextColor = Color.Black,
unfocusedTextColor= Color.Black,
// using our own colors in Res.Values.Color
unfocusedContainerColor = colorResource(id = R.color.text_field),
focusedContainerColor = colorResource(id = R.color.text_field),
focusedBorderColor = colorResource(id = R.color.black),
unfocusedBorderColor = colorResource(id = R.color.black),
focusedLabelColor = colorResource(id = R.color.black),
unfocusedLabelColor = colorResource(id = R.color.black),
)
)
OutlinedTextField(
value = password,
onValueChange = { password = it },
label = { Text("Password") },
shape = RoundedCornerShape(50),
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
visualTransformation = if(isVisible) VisualTransformation.None else PasswordVisualTransformation(),
colors = OutlinedTextFieldDefaults.colors(
cursorColor = colorResource(id = R.color.black),
// using predefined Color
focusedTextColor = Color.Black,
unfocusedTextColor= Color.Black,
// using our own colors in Res.Values.Color
unfocusedContainerColor = colorResource(id = R.color.text_field),
focusedContainerColor = colorResource(id = R.color.text_field),
focusedBorderColor = colorResource(id = R.color.black),
unfocusedBorderColor = colorResource(id = R.color.black),
focusedLabelColor = colorResource(id = R.color.black),
unfocusedLabelColor = colorResource(id = R.color.black),
),
trailingIcon = { IconButton(onClick = { isVisible = (!isVisible) }) {
Icon(imageVector = if(isVisible) Icons.Filled.Visibility else Icons.Filled.VisibilityOff , contentDescription = null)
}}
)
Button(
onClick = {
authViewModel.login(email, password)
onSignInSuccess()
},
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
colors = ButtonDefaults.buttonColors(Color.Green)
) {
Text("Login")
}
Text("Forgot Password?", modifier = Modifier.clickable { }, textDecoration = TextDecoration.Underline)
Spacer(modifier = Modifier.height(16.dp))
Text("Don't have an account? Sign up.",
modifier = Modifier.clickable { onNavigateToSignUp() }
)
}
}
//@Preview(showBackground = true)
//@Composable
//fun Preview(){
// LoginScreen(onNavigateToSignUp = { }) {
//
// }
//} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/screens/Login.kt | 3435469896 |
package com.example.tourismapp.screens
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.material.Icon
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.TopAppBar
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.unit.dp
import com.example.tourismapp.R
@Composable
fun TopAppBar(){
val navigationIcon : (@Composable () -> Unit)? =
{
IconButton(onClick = { }) {
Icon(
imageVector = Icons.Default.Menu,
tint = Color.White,
contentDescription = null
)
}
}
TopAppBar(
title = {
Text(text = "Welcome",
color = colorResource(id = R.color.white),
modifier = Modifier
.padding(start = 4.dp)
.heightIn(max = 24.dp))
},
elevation = 3.dp,
backgroundColor = colorResource(id = R.color.text_field),
navigationIcon = navigationIcon
)
} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/screens/TopBar.kt | 3151415341 |
package com.example.tourismapp.screens
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
fun SearchPage(paddingValues: PaddingValues){
LazyColumn(
modifier = Modifier.padding(paddingValues)
) {
}
} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/screens/SearchPage.kt | 1978026219 |
package com.example.tourismapp.screens
import android.content.Context
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
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.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Scaffold
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.LocationOn
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import com.example.tourismapp.R
import androidx.compose.material.rememberScaffoldState
import androidx.compose.ui.Alignment
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.rememberAsyncImagePainter
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Menu
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.core.app.ActivityCompat
import androidx.navigation.NavController
import com.example.tourismapp.MainActivity
import com.example.tourismapp.Screens
import com.example.tourismapp.data.*
import com.example.tourismapp.utils.LocationUtils
import com.example.tourismapp.viewmodel.HomeViewModel
import com.example.tourismapp.viewmodel.LocationViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
@Composable
fun HomePage(
homeViewModel: HomeViewModel,
locationUtils: LocationUtils,
viewModel: LocationViewModel,
navController: NavController,
context: Context
){
BackHandler(enabled = true) {
}
val scope: CoroutineScope = rememberCoroutineScope()
val selected by homeViewModel.selected.observeAsState()
val state by homeViewModel.state.observeAsState()
val scaffoldState = rememberScaffoldState()
Scaffold(
topBar = { val navigationIcon : (@Composable () -> Unit) =
{
androidx.compose.material3.IconButton(onClick = {
scope.launch {
scaffoldState.drawerState.open()
}
}) {
Icon(
imageVector = Icons.Default.Menu,
tint = Color.White,
contentDescription = null
)
}
}
androidx.compose.material.TopAppBar(
title = {
Text(
text = "${selected}",
color = colorResource(id = R.color.white),
modifier = Modifier
.padding(start = 4.dp)
.heightIn(max = 24.dp)
)
},
elevation = 3.dp,
backgroundColor = colorResource(id = R.color.text_field),
navigationIcon = navigationIcon
)
},
// drawerContent = {
// LazyColumn(Modifier.padding(16.dp)){
// items(screensInDrawer){
// item ->
// DrawerItem(selected = currentRoute == item.dRoute, item = item) {
// scope.launch {
// scaffoldState.drawerState.close()
// }
//
// controller.navigate(item.dRoute)
// title.value = item.dTitle
//
// }
// }
// }
// },
bottomBar = {
androidx.compose.material3.BottomAppBar(
containerColor = colorResource(id = R.color.text_field),
) {
Row(modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Absolute.SpaceBetween) {
IconButton(
onClick = {
homeViewModel.Navigate("Home")
}, modifier = if (selected == "Home") Modifier
.size(50.dp)
.background(color = Color.White)
.clip(
CircleShape
)
.border(1.dp, Color.White) else Modifier
) {
Icon(
imageVector = Icons.Default.Home,
contentDescription = "Home",
tint = if (selected == "Home") colorResource(id = R.color.text_field) else Color.White
)
}
IconButton(onClick = {
homeViewModel.Navigate("Search")
}, modifier = if (selected == "Search") Modifier
.size(50.dp)
.background(color = Color.White)
.clip(
CircleShape
)
.border(1.dp, Color.White) else Modifier) {
Icon(
imageVector = Icons.Default.Search,
contentDescription = "Search",
tint = if (selected == "Search") colorResource(id = R.color.text_field) else Color.White
)
}
FloatingActionButton(onClick = {
homeViewModel.Navigate( "Itinerary")
}, ) {
Icon(imageVector = Icons.Default.Add , contentDescription = null, tint = Color.White)
}
IconButton(onClick = {
homeViewModel.Navigate("Location")
}, modifier = if (selected == "Location") Modifier
.size(50.dp)
.background(color = Color.White)
.clip(
CircleShape
)
.border(1.dp, Color.White) else Modifier) {
Icon(
imageVector = Icons.Default.LocationOn,
contentDescription = "Location",
tint = if (selected == "Location") colorResource(id = R.color.text_field) else Color.White
)
}
IconButton(onClick = {
homeViewModel.Navigate("Profile")
}, modifier = if (selected == "Profile") Modifier
.size(50.dp)
.background(color = Color.White)
.clip(
CircleShape
)
.border(1.dp, Color.White) else Modifier) {
Icon(
imageVector = Icons.Default.Person,
contentDescription = "Profile",
tint = if (selected == "Profile") colorResource(id = R.color.text_field) else Color.White
)
}
}
}} ,
scaffoldState = scaffoldState
)
{
val requestPermissionLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestMultiplePermissions() ,
onResult = { permissions ->
if(permissions[android.Manifest.permission.ACCESS_COARSE_LOCATION] == true
&& permissions[android.Manifest.permission.ACCESS_FINE_LOCATION] == true){
// I HAVE ACCESS to location
locationUtils.requestLocationUpdates(viewModel = viewModel)
}else{
val rationaleRequired = ActivityCompat.shouldShowRequestPermissionRationale(
context as MainActivity,
android.Manifest.permission.ACCESS_FINE_LOCATION
) || ActivityCompat.shouldShowRequestPermissionRationale(
context,
android.Manifest.permission.ACCESS_COARSE_LOCATION
)
if(rationaleRequired){
Toast.makeText(context,
"Location Permission is required for this feature to work", Toast.LENGTH_LONG)
.show()
}else{
Toast.makeText(context,
"Location Permission is required. Please enable it in the Android Settings",
Toast.LENGTH_LONG)
.show()
}
}
})
when(selected){
"Home"-> HomeView(it,homeViewModel)
"Search"-> SearchPage(it)
"Location"-> LocationPage(it, state)
"Profile" ->ProfilePage(it,homeViewModel.user.value)
"Itinerary" -> {
if(locationUtils.hasLocationPermission(context)){
locationUtils.requestLocationUpdates(viewModel)
navController.navigate(Screens.LocationScreen.route){
this.launchSingleTop
}
}else{
requestPermissionLauncher.launch(arrayOf(
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION
))
}
}
}
}
}
@Composable
fun StateRowItem(state:States, homeViewModel: HomeViewModel){
Column(
modifier= Modifier
.size(150.dp)
.clickable {homeViewModel.Navigate("Location")
homeViewModel.setState(state.name)
},
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(painter = rememberAsyncImagePainter(state.image) , contentDescription = null,modifier = Modifier
.size(100.dp)
.clip(
CircleShape
)
.border(2.dp, state.borderColor, CircleShape))
Text(text = state.name, color = Color.Black)
}
}
@Composable
fun ListItems(heading:String){
Column{
Text(text = heading, color = Color.Black,fontWeight = FontWeight.Bold, fontStyle = FontStyle.Normal, fontFamily = FontFamily.SansSerif, fontSize = 25.sp)
// This list has to be updated with real data
val images = mutableListOf<Images>()
images.add(Images())
images.add(Images())
images.add(Images())
images.add(Images())
images.add(Images())
LazyRow( modifier = Modifier
.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
){
items(images){
image->
ImagesWidget(image = image)
}
}
}
}
@Composable
fun ImagesWidget(image: Images){
Image(painter = rememberAsyncImagePainter(image.image) , contentDescription = null,modifier = Modifier
.padding(15.dp)
.size(150.dp)
.clip(RoundedCornerShape(50.dp))
.clickable { /*Add functionality later*/ }
)
} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/screens/HomePage.kt | 46668201 |
package com.example.tourismapp.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
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.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.ui.res.stringResource
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.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 androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.tourismapp.R
import com.example.tourismapp.viewmodel.AuthViewModel
@Composable
fun SignUpScreen(
authViewModel: AuthViewModel= viewModel(),
onNavigateToLogin: () -> Unit
){
var email by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") }
var firstName by remember { mutableStateOf("") }
var lastName by remember { mutableStateOf("") }
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
.background(color = Color.White),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
){
Text(text = "Welcome to ${stringResource(R.string.app_name)}", fontWeight = FontWeight.Bold, color= Color.Black)
Text("Make your journey memorable", color = colorResource(id = R.color.text_field), fontWeight = FontWeight.Bold)
Spacer(modifier = Modifier.height(25.dp))
OutlinedTextField(
value = email,
onValueChange = { email = it },
label = { Text("Email") },
shape = RoundedCornerShape(50),
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
colors = OutlinedTextFieldDefaults.colors(
cursorColor = colorResource(id = R.color.black),
// using predefined Color
focusedTextColor = Color.Black,
unfocusedTextColor= Color.Black,
// using our own colors in Res.Values.Color
unfocusedContainerColor = colorResource(id = R.color.text_field),
focusedContainerColor = colorResource(id = R.color.text_field),
focusedBorderColor = colorResource(id = R.color.black),
unfocusedBorderColor = colorResource(id = R.color.black),
focusedLabelColor = colorResource(id = R.color.black),
unfocusedLabelColor = colorResource(id = R.color.black),
)
)
OutlinedTextField(
value = password,
onValueChange = { password = it },
label = { Text("Password") },
shape = RoundedCornerShape(50),
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
visualTransformation = PasswordVisualTransformation(),
colors = OutlinedTextFieldDefaults.colors(
cursorColor = colorResource(id = R.color.black),
// using predefined Color
focusedTextColor = Color.Black,
unfocusedTextColor= Color.Black,
// using our own colors in Res.Values.Color
unfocusedContainerColor = colorResource(id = R.color.text_field),
focusedContainerColor = colorResource(id = R.color.text_field),
focusedBorderColor = colorResource(id = R.color.black),
unfocusedBorderColor = colorResource(id = R.color.black),
focusedLabelColor = colorResource(id = R.color.black),
unfocusedLabelColor = colorResource(id = R.color.black),
)
)
OutlinedTextField(
value = firstName,
onValueChange = { firstName = it },
label = { Text("First Name") },
shape = RoundedCornerShape(50),
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
colors = OutlinedTextFieldDefaults.colors(
cursorColor = colorResource(id = R.color.black),
// using predefined Color
focusedTextColor = Color.Black,
unfocusedTextColor= Color.Black,
// using our own colors in Res.Values.Color
unfocusedContainerColor = colorResource(id = R.color.text_field),
focusedContainerColor = colorResource(id = R.color.text_field),
focusedBorderColor = colorResource(id = R.color.black),
unfocusedBorderColor = colorResource(id = R.color.black),
focusedLabelColor = colorResource(id = R.color.black),
unfocusedLabelColor = colorResource(id = R.color.black),
)
)
OutlinedTextField(
value = lastName,
onValueChange = { lastName = it },
label = { Text("Last Name") },
shape = RoundedCornerShape(50),
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
colors = OutlinedTextFieldDefaults.colors(
cursorColor = colorResource(id = R.color.black),
// using predefined Color
focusedTextColor = Color.Black,
unfocusedTextColor= Color.Black,
// using our own colors in Res.Values.Color
unfocusedContainerColor = colorResource(id = R.color.text_field),
focusedContainerColor = colorResource(id = R.color.text_field),
focusedBorderColor = colorResource(id = R.color.black),
unfocusedBorderColor = colorResource(id = R.color.black),
focusedLabelColor = colorResource(id = R.color.black),
unfocusedLabelColor = colorResource(id = R.color.black),
)
)
Button(
onClick = {
authViewModel.signUp(email, password, firstName, lastName)
email = ""
password = ""
firstName = ""
lastName = ""
onNavigateToLogin()
},
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
, colors = ButtonDefaults.buttonColors(Color.Green)
) {
Text("Register", color = Color.White, fontWeight = FontWeight.Bold)
}
Spacer(modifier = Modifier.height(16.dp))
Text("Already have an account? Sign in.",
modifier = Modifier.clickable { onNavigateToLogin() }
)
}
} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/screens/SignUp.kt | 3791878946 |
package com.example.tourismapp.screens
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
fun LocationPage(paddingValues: PaddingValues, state: String?){
if(state == null){
// Discover Page
}
else{
//Design According To State (Will use Switch case for selecting page of a state)
Text("$state")
}
LazyColumn(
modifier = Modifier.padding(paddingValues)
) {
}
} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/screens/LocationPage.kt | 2908917980 |
package com.example.tourismapp.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
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.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Icon
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.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 androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.tourismapp.Address
import com.example.tourismapp.R
import com.example.tourismapp.data.States
import com.example.tourismapp.viewmodel.HomeViewModel
@Composable
fun HomeView(paddingValues: PaddingValues, homeViewModel: HomeViewModel){
var location by remember { mutableStateOf("") }
Column(
modifier = Modifier
.fillMaxSize().padding(paddingValues)
.verticalScroll(rememberScrollState(), true),
) {
Spacer(modifier = Modifier.height(25.dp))
Box(modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
OutlinedTextField(
value = location,
singleLine = true,
onValueChange = { location = it },
placeholder = { Text(text = "Location", color = Color.Black, fontSize = 1.sp) },
modifier = Modifier.height(30.dp).width(300.dp),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
colors = OutlinedTextFieldDefaults.colors(
cursorColor = colorResource(id = R.color.black),
// using predefined Color
focusedTextColor = Color.Black,
unfocusedTextColor = Color.Black,
// using our own colors in Res.Values.Color
focusedBorderColor = colorResource(id = R.color.black),
unfocusedBorderColor = colorResource(id = R.color.black),
focusedLabelColor = colorResource(id = R.color.black),
unfocusedLabelColor = colorResource(id = R.color.black),
),
leadingIcon = {
Icon(
imageVector = Icons.Default.Search,
contentDescription = "Search"
)
},
shape= RoundedCornerShape(50)
)
}
Spacer(modifier = Modifier.height(25.dp))
LazyRow( modifier = Modifier
.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
// This list has to be updated with real data
val states = mutableListOf<States>()
states.add(States("Maharashtra", Address.path))
states.add(States("Gujarat", Address.path, Color.Red))
states.add(States("Uttar Pradesh", Address.path, Color.Cyan))
states.add(States("Haryana", Address.path, Color.Magenta))
states.add(States("Delhi", Address.path, Color.Gray))
states.add(States("Uttarakhand", Address.path, Color.Green))
items(states){
state->
StateRowItem(state = state, homeViewModel = homeViewModel)
}
}
ListItems(heading = "Trips")
ListItems(heading = "Foods")
ListItems(heading = "Festivals")
}
} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/screens/HomeView.kt | 2027685558 |
package com.example.tourismapp.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
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.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.example.tourismapp.data.LocationData
import com.google.android.gms.maps.model.CameraPosition
import com.google.android.gms.maps.model.LatLng
import com.google.maps.android.compose.GoogleMap
import com.google.maps.android.compose.Marker
import com.google.maps.android.compose.MarkerState
import com.google.maps.android.compose.rememberCameraPositionState
@Composable
fun LocationSelectionScreen(
location: LocationData,
onLocationSelected: (LocationData) -> Unit,
goBack: ()->Unit){
val userLocation = remember{
mutableStateOf(LatLng(location.latitude, location.longitude))
}
val cameraPositionState = rememberCameraPositionState{
position = CameraPosition.fromLatLngZoom(userLocation.value, 10f)
}
Column(modifier= Modifier.fillMaxSize()) {
GoogleMap(
modifier = Modifier.weight(1f).padding(top=16.dp),
cameraPositionState = cameraPositionState,
onMapClick = {
userLocation.value = it
}
){
Marker(state = MarkerState(position = userLocation.value))
}
var newLocation: LocationData
Row(modifier= Modifier.fillMaxWidth(),horizontalArrangement = Arrangement.SpaceBetween) {
Button(onClick = {
newLocation =
LocationData(userLocation.value.latitude, userLocation.value.longitude)
onLocationSelected(newLocation)
}) {
Text("Set Location")
}
Button(onClick = {
goBack()
}) {
Text("Skip")
}
}
}
}
| Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/screens/LocationSelectionScreen.kt | 384235465 |
package com.example.tourismapp.screens
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.tourismapp.data.Images
@Composable
fun DiscoverPage(state:String = "", paddingValues: PaddingValues){
Column(modifier = Modifier.verticalScroll(rememberScrollState(),true).padding(paddingValues)) {
Text(text = if(state=="")"Discover" else state, fontSize = 25.sp, fontWeight = FontWeight.ExtraBold, fontStyle = FontStyle.Normal, fontFamily = FontFamily.Monospace, textAlign = TextAlign.Start, color = Color.Black)
Spacer(modifier = Modifier.height(40.dp))
val list = mutableListOf<Images>()
list.add(Images("https://firebasestorage.googleapis.com/v0/b/tourism-3aef0.appspot.com/o/images%2FUntitled%20Design.png?alt=media&token=14e818d4-71c3-4622-8ca6-256e9b524dda"))
list.add(Images("https://firebasestorage.googleapis.com/v0/b/tourism-3aef0.appspot.com/o/images%2FUntitled%20Design.jpg?alt=media&token=55386474-338f-490b-8a52-e5e24846d946"))
list.add(Images("https://firebasestorage.googleapis.com/v0/b/tourism-3aef0.appspot.com/o/images%2FUntitled%20Design%20(1).jpg?alt=media&token=597b7cec-ace5-4dcf-b487-3d4fd4f52f89"))
ListItems(heading = if(state=="")"Plan a Hangout" else "Current Events")
ListItems(heading = if(state=="")"Long Weekend Trip" else "Upcoming Events")
ListItems(heading = if(state=="")"Vacation Ideas" else "Underrated Locations" )
}
} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/screens/DiscoverPage.kt | 2341013078 |
package com.example.tourismapp.screens
import android.widget.Toast
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.height
import androidx.compose.foundation.layout.width
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
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.navigation.NavController
import com.example.tourismapp.Screens
import com.example.tourismapp.viewmodel.AuthViewModel
import com.example.tourismapp.data.Result.*
@Composable
fun LoadingScreen(authViewModel: AuthViewModel,navController: NavController) {
val context = LocalContext.current
val result by authViewModel.authResult.observeAsState()
Box(modifier = Modifier.background(color = Color.Black).height(200.dp).width(200.dp), contentAlignment = Alignment.Center) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
CircularProgressIndicator()
Text("Please Wait")
}
}
LaunchedEffect(result) {
if (result == null) {
// Show loading screen
} else {
// Proceed with your logic
when(result){
is Success -> {
navController.navigate(Screens.HomePage.route)
}
is Error -> {
navController.navigateUp()
authViewModel.reset()
Toast.makeText(context,"Incorrect Id or Password",Toast.LENGTH_LONG).show()
}
else -> {}
}
}
}
} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/screens/LoadingScreen.kt | 4281794705 |
package com.example.tourismapp
object Address {
val path:String = "https://firebasestorage.googleapis.com/v0/b/practice-d6fc0.appspot.com/o/taj%20mahal.jpg?alt=media&token=84ac21f9-052d-4ca1-ad30-d873959f03db"
} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/Address.kt | 2820362928 |
package com.example.tourismapp
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.storage.FirebaseStorage
object Injection {
private val instance: FirebaseFirestore by lazy {
FirebaseFirestore.getInstance()
}
private val storage: FirebaseStorage by lazy{
FirebaseStorage.getInstance()
}
fun instance(): FirebaseFirestore {
return instance
}
fun storageInstance(): FirebaseStorage{
return storage
}
} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/Injection.kt | 4085754589 |
package com.example.tourismapp.data
import com.example.tourismapp.Address
data class Images (
val image: String = Address.path
) | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/data/Images.kt | 2951770994 |
package com.example.tourismapp.data
data class LocationData(
val latitude: Double,
val longitude: Double
)
data class GeocodingResponse(
val results: List<GeocodingResult>,
val status: String
)
data class GeocodingResult(
val formatted_address: String
) | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/data/LocationData.kt | 2137100652 |
package com.example.tourismapp.data
sealed class Result<out T> {
data class Success<out T>(val data: T) : Result<T>()
data class Error(val exception: Exception) : Result<Nothing>()
} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/data/Result.kt | 713799194 |
package com.example.tourismapp.data
import androidx.compose.ui.graphics.Color
import com.example.tourismapp.Address
data class States(
val name:String= "Delhi",
val image: String = Address.path,
val borderColor: Color = Color.Yellow
)
| Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/data/States.kt | 3605761826 |
package com.example.tourismapp.data
import android.util.Log
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.coroutines.tasks.await
class UserRepository(private val auth: FirebaseAuth,
private val firestore: FirebaseFirestore
) {
suspend fun signUp(email: String, password: String, firstName: String, lastName: String): Result<Boolean> =
try {
auth.createUserWithEmailAndPassword(email, password).await()
val user = User(firstName, lastName, email)
saveUserToFirestore(user)
Result.Success(true)
} catch (e: Exception) {
Result.Error(e)
}
suspend fun login(email: String, password: String): Result<Boolean> =
try {
auth.signInWithEmailAndPassword(email, password).await()
Result.Success(true)
} catch (e: Exception) {
Result.Error(e)
}
private suspend fun saveUserToFirestore(user: User) {
firestore.collection("users").document(user.email).set(user).await()
}
suspend fun getCurrentUser(): Result<User> = try {
val uid = auth.currentUser?.email
if (uid != null) {
val userDocument = firestore.collection("users").document(uid).get().await()
val user = userDocument.toObject(User::class.java)
if (user != null) {
Log.d("user2","$uid")
Result.Success(user)
} else {
Result.Error(Exception("User data not found"))
}
} else {
Result.Error(Exception("User not authenticated"))
}
} catch (e: Exception) {
Result.Error(e)
}
} | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/data/UserRepository.kt | 666550318 |
package com.example.tourismapp.data
data class User(
val firstName: String = "",
val lastName: String = "",
val email: String = ""
) | Cultoura-BitBandits-Vihaan007/app/src/main/java/com/example/tourismapp/data/User.kt | 1558023194 |
package com.example.alarmmagager
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.alarmmagager", appContext.packageName)
}
} | AlarmMagagerApp/app/src/androidTest/java/com/example/alarmmagager/ExampleInstrumentedTest.kt | 2053510470 |
package com.example.alarmmagager
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)
}
} | AlarmMagagerApp/app/src/test/java/com/example/alarmmagager/ExampleUnitTest.kt | 569741783 |
package com.example.alarmmagager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | AlarmMagagerApp/app/src/main/java/com/example/alarmmagager/MainActivity.kt | 1953581395 |
package com.example.jetpack_compose_retrofit
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.jetpack_compose_retrofit", appContext.packageName)
}
} | jetpack-compose-retrofit/app/src/androidTest/java/com/example/jetpack_compose_retrofit/ExampleInstrumentedTest.kt | 4203415217 |
package com.example.jetpack_compose_retrofit
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)
}
} | jetpack-compose-retrofit/app/src/test/java/com/example/jetpack_compose_retrofit/ExampleUnitTest.kt | 2922429996 |
package com.example.jetpack_compose_retrofit.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) | jetpack-compose-retrofit/app/src/main/java/com/example/jetpack_compose_retrofit/ui/theme/Color.kt | 845896394 |
package com.example.jetpack_compose_retrofit.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 JetpackcomposeretrofitTheme(
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
)
} | jetpack-compose-retrofit/app/src/main/java/com/example/jetpack_compose_retrofit/ui/theme/Theme.kt | 3628921844 |
package com.example.jetpack_compose_retrofit.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
)
*/
) | jetpack-compose-retrofit/app/src/main/java/com/example/jetpack_compose_retrofit/ui/theme/Type.kt | 3317097234 |
package com.example.jetpack_compose_retrofit
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.jetpack_compose_retrofit.ui.theme.JetpackcomposeretrofitTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
JetpackcomposeretrofitTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Greeting("Android")
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
JetpackcomposeretrofitTheme {
Greeting("Android")
}
} | jetpack-compose-retrofit/app/src/main/java/com/example/jetpack_compose_retrofit/MainActivity.kt | 3630311480 |
package com.jimbonlemu.mycustomview
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.jimbonlemu.mycustomview", appContext.packageName)
}
} | MyCustomView_Custom_Component_Android_Native/app/src/androidTest/java/com/jimbonlemu/mycustomview/ExampleInstrumentedTest.kt | 2143671507 |
package com.jimbonlemu.mycustomview
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)
}
} | MyCustomView_Custom_Component_Android_Native/app/src/test/java/com/jimbonlemu/mycustomview/ExampleUnitTest.kt | 2983076141 |
package com.jimbonlemu.mycustomview
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.jimbonlemu.mycustomview.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
ActivityMainBinding.inflate(layoutInflater).apply {
setContentView(root)
}
}
} | MyCustomView_Custom_Component_Android_Native/app/src/main/java/com/jimbonlemu/mycustomview/MainActivity.kt | 2840832965 |
package com.example.homework07
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.homework07", appContext.packageName)
}
} | HW7-android-GB/app/src/androidTest/java/com/example/homework07/ExampleInstrumentedTest.kt | 17890519 |
package com.example.homework07
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)
}
} | HW7-android-GB/app/src/test/java/com/example/homework07/ExampleUnitTest.kt | 3025971553 |
package com.example.homework07
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.homework07.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)
}
} | HW7-android-GB/app/src/main/java/com/example/homework07/MainActivity.kt | 3896345235 |
package com.example.homework07
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.example.homework07.databinding.FragmentQuizBinding
class QuizFragment : Fragment() {
private var _binding: FragmentQuizBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentQuizBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.buttonSendAnswers.setOnClickListener {
val number = getAnswersByUser()
val action = QuizFragmentDirections.actionQuizFragmentToResultFragment(number)
findNavController().navigate(action)
}
}
private fun getAnswersByUser() : Int {
var currentAnswers = 0
if (binding.radiogroupAnswers01.checkedRadioButtonId == binding.radiobuttonAnswer0103.id)
currentAnswers++
if (binding.radiogroupAnswers02.checkedRadioButtonId == binding.radiobuttonAnswer0204.id)
currentAnswers++
if (binding.radiogroupAnswers03.checkedRadioButtonId == binding.radiobuttonAnswer0302.id)
currentAnswers++
if (binding.radiogroupAnswers04.checkedRadioButtonId == binding.radiobuttonAnswer0401.id)
currentAnswers++
return currentAnswers
}
override fun onDestroy() {
super.onDestroy()
_binding = null
}
}
| HW7-android-GB/app/src/main/java/com/example/homework07/QuizFragment.kt | 1025365141 |
package com.example.homework07
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.example.homework07.databinding.FragmentHelloBinding
class HelloFragment : Fragment() {
private lateinit var binding: FragmentHelloBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
binding = FragmentHelloBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.buttonStart.setOnClickListener {
findNavController().navigate(R.id.action_helloFragment_to_quizFragment)
}
}
} | HW7-android-GB/app/src/main/java/com/example/homework07/HelloFragment.kt | 3268757573 |
package com.example.homework07
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.example.homework07.databinding.FragmentResultBinding
class ResultFragment : Fragment() {
private val args: ResultFragmentArgs by navArgs()
private var _binding: FragmentResultBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentResultBinding.inflate(inflater)
return binding.root
}
@SuppressLint("SetTextI18n")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.result.text = args.number.toString() + " / 4"
binding.buttonReturnQuiz.setOnClickListener {
findNavController().navigate(R.id.action_resultFragment_to_quizFragment)
}
}
override fun onDestroy() {
super.onDestroy()
_binding = null
}
} | HW7-android-GB/app/src/main/java/com/example/homework07/ResultFragment.kt | 319815648 |
package api
import org.junit.jupiter.api.Test
internal class VedtakRouteTest {
@Test
fun `dummy test`() {
assert(true)
}
}
| aap-api-intern/app/test/api/VedtakTest.kt | 581020241 |
package api
import org.junit.jupiter.api.Test
internal class VedtakRouteTest {
@Test
fun `dummy test`() {
assert(true)
}
}
| aap-api-intern/app/bin/test/api/VedtakTest.kt | 581020241 |
package api
import api.afp.afp
import api.arena.ArenaoppslagRestClient
import api.auth.MASKINPORTEN_AFP_OFFENTLIG
import api.auth.MASKINPORTEN_AFP_PRIVAT
import api.auth.maskinporten
import api.sporingslogg.SporingsloggKafkaClient
import api.util.*
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import io.ktor.http.*
import io.ktor.serialization.jackson.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.engine.*
import io.ktor.server.metrics.micrometer.*
import io.ktor.server.netty.*
import io.ktor.server.plugins.callloging.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.plugins.cors.routing.*
import io.ktor.server.plugins.statuspages.*
import io.ktor.server.plugins.swagger.*
import io.ktor.server.routing.*
import io.micrometer.prometheus.PrometheusConfig
import io.micrometer.prometheus.PrometheusMeterRegistry
import org.slf4j.LoggerFactory
private val logger = LoggerFactory.getLogger("App")
fun main() {
Thread.currentThread().setUncaughtExceptionHandler { _, e -> logger.error("Uhåndtert feil", e) }
embeddedServer(Netty, port = 8080, module = Application::api).start(wait = true)
}
fun Application.api() {
val config = Config()
val prometheus = PrometheusMeterRegistry(PrometheusConfig.DEFAULT)
val sporingsloggKafkaClient = SporingsloggKafkaClient(config.kafka, config.sporingslogg)
val arenaRestClient = ArenaoppslagRestClient(config.arenaoppslag, config.azure)
install(CallLogging) {
logging()
}
install(MicrometerMetrics) {
registry = prometheus
}
install(StatusPages) {
feilhåndtering(logger)
}
install(ContentNegotiation) {
jackson {
registerModule(JavaTimeModule())
disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
}
}
install(Authentication) {
maskinporten(MASKINPORTEN_AFP_PRIVAT, config.oauth.maskinporten.scope.afpprivat, config)
maskinporten(MASKINPORTEN_AFP_OFFENTLIG, config.oauth.maskinporten.scope.afpoffentlig, config)
}
install(CORS) {
anyHost()
allowHeader(HttpHeaders.ContentType)
}
routing {
actuator(prometheus)
swaggerUI(path = "swagger", swaggerFile = "openapi.yaml")
afp(config, arenaRestClient, sporingsloggKafkaClient, prometheus)
}
}
| aap-api-intern/app/bin/main/api/App.kt | 2051125193 |
package api.util
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.micrometer.prometheus.PrometheusMeterRegistry
fun Routing.actuator(prometheus: PrometheusMeterRegistry) {
route("/actuator") {
get("/metrics") {
call.respondText(prometheus.scrape())
}
get("/live") {
call.respond(HttpStatusCode.OK, "api")
}
get("/ready") {
call.respond(HttpStatusCode.OK, "api")
}
}
} | aap-api-intern/app/bin/main/api/util/Actuator.kt | 3270929962 |
package api.util
import io.ktor.server.plugins.callloging.*
import io.ktor.server.request.*
import org.slf4j.event.Level
fun CallLoggingConfig.logging() {
level = Level.INFO
format { call ->
val status = call.response.status()
val httpMethod = call.request.httpMethod.value
val userAgent = call.request.headers["User-Agent"]
val callId = call.request.header("x-callid") ?: call.request.header("nav-callId") ?: "ukjent"
"Status: $status, HTTP method: $httpMethod, User agent: $userAgent, callId: $callId"
}
filter { call -> call.request.path().startsWith("/actuator").not() }
} | aap-api-intern/app/bin/main/api/util/CallLogging.kt | 3898700822 |
package api.util
import api.auth.SamtykkeIkkeGittException
import io.ktor.http.*
import io.ktor.server.plugins.statuspages.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import org.slf4j.Logger
fun StatusPagesConfig.feilhåndtering(logger: Logger) {
exception<SamtykkeIkkeGittException> { call, cause ->
logger.warn("Samtykke ikke gitt", cause)
call.respondText(text = "Samtykke ikke gitt", status = HttpStatusCode.Forbidden)
}
exception<ContentTransformationException> { call, cause ->
logger.warn("Feil i mottatte data", cause)
call.respondText(text = "Feil i mottatte data", status = HttpStatusCode.BadRequest)
}
exception<IllegalArgumentException> { call, cause ->
logger.warn("Feil i mottatte data", cause)
call.respondText(text = "Feil i mottatte data", status = HttpStatusCode.BadRequest)
}
exception<Throwable> { call, cause ->
logger.error("Uhåndtert feil", cause)
call.respondText(text = "Feil i tjeneste: ${cause.message}", status = HttpStatusCode.InternalServerError)
}
}
| aap-api-intern/app/bin/main/api/util/ErrorHandling.kt | 764603046 |
package api.util
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import org.apache.kafka.clients.CommonClientConfigs
import org.apache.kafka.clients.producer.KafkaProducer
import org.apache.kafka.clients.producer.ProducerConfig
import org.apache.kafka.common.config.SslConfigs
import org.apache.kafka.common.serialization.Serdes
import org.apache.kafka.common.serialization.Serializer
import java.util.*
class KafkaFactory private constructor() {
companion object {
fun<T:Any> createProducer(clientId: String, config: KafkaConfig): KafkaProducer<String, T> {
fun properties(): Properties = Properties().apply {
this[CommonClientConfigs.CLIENT_ID_CONFIG] = clientId
this[CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG] = config.brokers
this[ProducerConfig.ACKS_CONFIG] = "all"
this[ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION] = "5"
this[CommonClientConfigs.SECURITY_PROTOCOL_CONFIG] = "SSL"
this[SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG] = "JKS"
this[SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG] = config.truststorePath
this[SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG] = config.credstorePsw
this[SslConfigs.SSL_KEYSTORE_TYPE_CONFIG] = "PKCS12"
this[SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG] = config.keystorePath
this[SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG] = config.credstorePsw
this[SslConfigs.SSL_KEY_PASSWORD_CONFIG] = config.credstorePsw
this[SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG] = ""
}
return KafkaProducer(properties(), Serdes.StringSerde().serializer(), JacksonSerializer<T>())
}
}
}
class JacksonSerializer<T:Any>:Serializer<T>{
companion object {
internal val jackson: ObjectMapper = jacksonObjectMapper().apply {
registerModule(JavaTimeModule())
disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
}
}
override fun configure(configs: MutableMap<String, *>?, isKey: Boolean) {}
override fun serialize(topic: String?, data: T): ByteArray = jackson.writeValueAsBytes(data)
override fun close() {}
} | aap-api-intern/app/bin/main/api/util/KafkaFactory.kt | 1178675856 |
package api.util
import no.nav.aap.ktor.client.auth.azure.AzureConfig
import java.net.URI
import java.net.URL
private fun getEnvVar(envar: String) = System.getenv(envar) ?: error("missing envvar $envar")
data class Config(
val oauth: OauthConfig = OauthConfig(),
val arenaoppslag: ArenaoppslagConfig = ArenaoppslagConfig(),
val azure: AzureConfig = AzureConfig(
tokenEndpoint = getEnvVar("AZURE_OPENID_CONFIG_TOKEN_ENDPOINT"),
clientId = getEnvVar("AZURE_APP_CLIENT_ID"),
clientSecret = getEnvVar("AZURE_APP_CLIENT_SECRET")
),
val kafka: KafkaConfig= KafkaConfig(),
val sporingslogg: SporingsloggConfig= SporingsloggConfig()
)
data class KafkaConfig(
val brokers: String = getEnvVar("KAFKA_BROKERS"),
val truststorePath: String = getEnvVar("KAFKA_TRUSTSTORE_PATH"),
val keystorePath: String = getEnvVar("KAFKA_KEYSTORE_PATH"),
val credstorePsw: String= getEnvVar("KAFKA_CREDSTORE_PASSWORD"),
)
data class OauthConfig(
val maskinporten: MaskinportenConfig= MaskinportenConfig(),
val samtykke: SamtykkeConfig= SamtykkeConfig()
)
data class SporingsloggConfig(
val enabled: Boolean = getEnvVar("SPORINGSLOGG_ENABLED").toBoolean(),
val topic: String= getEnvVar("SPORINGSLOGG_TOPIC")
)
data class MaskinportenConfig(
val jwksUri: URL= URI(getEnvVar("MASKINPORTEN_JWKS_URI")).toURL(),
val issuer: IssuerConfig=IssuerConfig(),
val scope: ScopeConfig= ScopeConfig()
) {
data class IssuerConfig(
val name: String= getEnvVar("MASKINPORTEN_ISSUER"),
val discoveryUrl: String= getEnvVar("MASKINPORTEN_WELL_KNOWN_URL"),
val audience: String = getEnvVar("AAP_AUDIENCE"),
val optionalClaims: String = "sub,nbf",
)
data class ScopeConfig(
val afpprivat: String= "nav:aap:afpprivat.read",
val afpoffentlig: String = "nav:aap:afpoffentlig.read"
)
}
data class ArenaoppslagConfig(
val proxyBaseUrl:String = getEnvVar("ARENAOPPSLAG_PROXY_BASE_URL"),
val scope: String= getEnvVar("ARENAOPPSLAG_SCOPE")
)
data class SamtykkeConfig(
val wellknownUrl: String= getEnvVar("ALTINN_WELLKNOWN"),
val audience: String= getEnvVar("ALTINN_AUDIENCE")
)
| aap-api-intern/app/bin/main/api/util/Config.kt | 2659092568 |
package api.util
import io.micrometer.core.instrument.Counter
import io.micrometer.core.instrument.Tag
import io.micrometer.prometheus.PrometheusMeterRegistry
fun PrometheusMeterRegistry.httpCallCounter(consumer: String, path: String): Counter = this.counter(
"http_call",
listOf(Tag.of("consumer", consumer), Tag.of("path", path))
)
fun PrometheusMeterRegistry.httpFailedCallCounter(consumer: String, path: String): Counter = this.counter(
"http_call_failed",
listOf(Tag.of("consumer", consumer), Tag.of("path", path))
)
fun PrometheusMeterRegistry.sporingsloggFailCounter(consumer: String): Counter = this.counter(
"sporingslogg_failed",
listOf(Tag.of("consumer", consumer))
) | aap-api-intern/app/bin/main/api/util/Metrics.kt | 287909709 |
package api.auth
import api.util.Config
import com.auth0.jwk.JwkProvider
import com.auth0.jwk.JwkProviderBuilder
import io.ktor.server.application.*
import io.ktor.http.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.response.*
import org.slf4j.LoggerFactory
import java.util.concurrent.TimeUnit
private val logger = LoggerFactory.getLogger("MaskinportenAuth")
const val MASKINPORTEN_AFP_PRIVAT = "fellesordning"
const val MASKINPORTEN_AFP_OFFENTLIG = "afp-offentlig"
internal fun ApplicationCall.hentConsumerId(): String {
val principal = requireNotNull(this.principal<JWTPrincipal>())
val consumer = requireNotNull(principal.payload.getClaim("consumer"))
return consumer.asMap()["ID"].toString().split(":").last()
}
fun AuthenticationConfig.maskinporten(name: String, scope: String, config: Config) {
val maskinportenJwkProvider: JwkProvider = JwkProviderBuilder(config.oauth.maskinporten.jwksUri)
.cached(10, 24, TimeUnit.HOURS)
.rateLimited(10, 1, TimeUnit.MINUTES)
.build()
jwt(name) {
verifier(maskinportenJwkProvider, config.oauth.maskinporten.issuer.name)
challenge { _, _ -> call.respond(HttpStatusCode.Unauthorized, "Ikke tilgang til maskinporten") }
validate { cred ->
if (cred.getClaim("scope", String::class) != scope) {
logger.warn("Wrong scope in claim")
return@validate null
}
JWTPrincipal(cred.payload)
}
}
}
| aap-api-intern/app/bin/main/api/auth/MaskinportenAuth.kt | 2286014642 |
package api.auth
import api.util.Config
import com.auth0.jwk.UrlJwkProvider
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.auth0.jwt.interfaces.DecodedJWT
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import org.slf4j.LoggerFactory
import java.security.interfaces.RSAPublicKey
import java.time.LocalDate
private val logger = LoggerFactory.getLogger("SamtykkeAuth")
data class SamtykkeData(
val samtykkeperiode: Samtykkeperiode,
val personIdent: String,
val consumerId: String,
val samtykketoken: String,
val tidspunkt: LocalDate = LocalDate.now(),
)
data class Samtykkeperiode(val fraOgMed:LocalDate, val tilOgMed:LocalDate)
class SamtykkeIkkeGittException: Exception {
constructor(msg: String): super(msg)
constructor(msg: String, cause: Throwable): super(msg, cause)
}
fun verifiserOgPakkUtSamtykkeToken(token: String, call:ApplicationCall, config: Config): SamtykkeData {
val samtykkeJwks = SamtykkeJwks(config.oauth.samtykke.wellknownUrl)
val jwkProvider = UrlJwkProvider(samtykkeJwks.jwksUri)
val consumerId = hentConsumerId(call)
val personIdent = hentPersonIdent(call)
val jwt = JWT.decode(token)
val jwk = jwkProvider.get(jwt.keyId)
val publicKey = jwk.publicKey as? RSAPublicKey ?: throw Exception("Invalid key type")
val algorithm = when (jwk.algorithm) {
"RS256" -> Algorithm.RSA256(publicKey, null)
"RSA-OAEP-256" -> Algorithm.RSA256(publicKey, null)
else -> throw Exception("Unsupported algorithm")
}
val verifier = JWT.require(algorithm) // signature
.withIssuer(samtykkeJwks.issuer)
.withAudience(config.oauth.samtykke.audience)
.withClaim("CoveredBy", consumerId)
.withClaim("OfferedBy", personIdent)
.build()
return try {
verifier.verify(token)
SamtykkeData(samtykketoken = token, consumerId = consumerId, personIdent = personIdent, samtykkeperiode = parseDates(jwt))
} catch (e: Exception) {
logger.info("Token not verified: $e")
throw SamtykkeIkkeGittException("Klarte ikke godkjenne samtykketoken", e)
}
}
private fun hentPersonIdent(call: ApplicationCall): String =
call.request.headers["NAV-PersonIdent"]?: throw SamtykkeIkkeGittException("NAV-PersonIdent ikke satt")
private fun hentConsumerId(call:ApplicationCall): String {
val principal = requireNotNull(call.principal<JWTPrincipal>())
val consumer = requireNotNull(principal.payload.getClaim("consumer"))
return consumer.asMap()["ID"].toString().split(":").last()
}
private fun parseDates(jwt:DecodedJWT):Samtykkeperiode{
val services = jwt.getClaim("Services").asArray(String::class.java)
return Samtykkeperiode(
LocalDate.parse(services[1].split("=").last()),
LocalDate.parse(services[2].split("=").last())
)
}
| aap-api-intern/app/bin/main/api/auth/SamtykkeAuth.kt | 2891728620 |
package api.auth
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.serialization.jackson.*
import kotlinx.coroutines.runBlocking
import java.net.URI
import java.net.URL
class SamtykkeJwks (
private val wellknownUrl: String
) {
val issuer: String
val jwksUri: URL
init {
val samtykke = runBlocking {
defaultHttpClient.get(wellknownUrl) {
accept(ContentType.Application.Json)
}.body<SamtykkeResponse>()
}
issuer = samtykke.issuer
jwksUri = URI(samtykke.jwksUri).toURL()
}
private data class SamtykkeResponse(
val issuer: String,
@JsonProperty("jwks_uri")
val jwksUri: String
)
private companion object {
private val defaultHttpClient = HttpClient(CIO) {
install(ContentNegotiation) {
jackson {
registerModule(JavaTimeModule())
disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
}
}
}
}
} | aap-api-intern/app/bin/main/api/auth/SamtykkeJwks.kt | 461134613 |
package api.dsop
import api.arena.ArenaoppslagRestClient
import api.auth.verifiserOgPakkUtSamtykkeToken
import api.sporingslogg.Spor
import api.util.Config
import api.sporingslogg.SporingsloggKafkaClient
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import org.slf4j.LoggerFactory
import java.time.LocalDateTime
import java.util.*
private val logger = LoggerFactory.getLogger("App")
private val secureLog = LoggerFactory.getLogger("secureLog")
fun Routing.dsop(
config: Config,
arenaoppslagRestClient: ArenaoppslagRestClient,
sporingsloggKafkaClient: SporingsloggKafkaClient
) {
post("/dsop/meldeplikt") {//TODO: gjør om til get()
val callId = requireNotNull(call.request.header("x-callid")) { "x-callid ikke satt" }
val samtykke = verifiserOgPakkUtSamtykkeToken(requireNotNull(call.request.header("NAV-samtykke-token")), call, config)
val dsopRequest = call.receive<DsopRequest>()
logger.info("Samtykke OK: ${samtykke.samtykkeperiode}")
try {
arenaoppslagRestClient.hentMeldepliktDsop(UUID.fromString(callId),dsopRequest)
sporingsloggKafkaClient.send(
Spor(samtykke.personIdent,samtykke.consumerId,"aap", "behandlingsgrunnlag",
LocalDateTime.now(),"leverteData",samtykke.samtykketoken,"dataForespoersel", "leverandoer")
)
call.respond("OK")
} catch (e:Exception){
secureLog.error("Klarte ikke produsere til kafka sporingslogg og kan derfor ikke returnere data", e)
call.respond(
HttpStatusCode.ServiceUnavailable,
"Feilet sporing av oppslag, kan derfor ikke returnere data. Feilen er på vår side, prøv igjen senere."
)
}
}
post("/dsop/vedtak") {//TODO: gjør om til get()
val callId = requireNotNull(call.request.header("x-callid")) { "x-callid ikke satt" }
val samtykke = verifiserOgPakkUtSamtykkeToken(requireNotNull(call.request.header("NAV-samtykke-token")), call, config)
val dsopRequest = call.receive<DsopRequest>() //TODO: hent ut personId fra token
logger.info("Samtykke OK: ${samtykke.samtykkeperiode}")
try {
arenaoppslagRestClient.hentMeldepliktDsop(UUID.fromString(callId),dsopRequest)
sporingsloggKafkaClient.send(
Spor(samtykke.personIdent,samtykke.consumerId,"aap", "behandlingsgrunnlag",
LocalDateTime.now(),"leverteData",samtykke.samtykketoken,"dataForespoersel", "leverandoer")
)
call.respond("OK")
} catch (e:Exception){
secureLog.error("Klarte ikke produsere til kafka sporingslogg og kan derfor ikke returnere data", e)
call.respond(
HttpStatusCode.ServiceUnavailable,
"Feilet sporing av oppslag, kan derfor ikke returnere data. Feilen er på vår side, prøv igjen senere."
)
}
}
} | aap-api-intern/app/bin/main/api/dsop/Routes.kt | 1220702097 |
package api.dsop
import java.time.LocalDate
data class DsopRequest(
val personId: String,
val periode: Periode,
val samtykkePeriode: Periode
)
data class Periode(
val fraDato: LocalDate,
val tilDato: LocalDate
) {
fun erDatoIPeriode(dato: LocalDate) = dato in fraDato..tilDato
} | aap-api-intern/app/bin/main/api/dsop/DsopRequest.kt | 3277204761 |
package api.afp
import api.arena.ArenaoppslagRestClient
import api.auth.MASKINPORTEN_AFP_OFFENTLIG
import api.auth.MASKINPORTEN_AFP_PRIVAT
import api.sporingslogg.SporingsloggKafkaClient
import api.util.Config
import api.auth.hentConsumerId
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.routing.*
import io.micrometer.prometheus.PrometheusMeterRegistry
fun Route.afp(
config: Config,
arenaoppslagRestClient: ArenaoppslagRestClient,
sporingsloggClient: SporingsloggKafkaClient,
prometheus: PrometheusMeterRegistry
) {
route("/afp") {
authenticate(MASKINPORTEN_AFP_PRIVAT) {
post("/fellesordningen") {
Afp.doWorkFellesOrdningen(call, config, arenaoppslagRestClient, sporingsloggClient, prometheus)
}
}
authenticate(MASKINPORTEN_AFP_OFFENTLIG) {
post("/offentlig") {
Afp.doWorkOffentlig(
call,
config,
arenaoppslagRestClient,
sporingsloggClient,
prometheus,
orgnr = call.hentConsumerId()
)
}
}
}
authenticate(MASKINPORTEN_AFP_PRIVAT) {
post("/fellesordning-for-afp") {
Afp.doWorkFellesOrdningen(call, config, arenaoppslagRestClient, sporingsloggClient, prometheus)
}
}
}
| aap-api-intern/app/bin/main/api/afp/Routes.kt | 1187282137 |
package api.afp
import java.time.LocalDate
data class VedtakResponse(val perioder: List<VedtakPeriode>)
data class VedtakPeriode(val fraOgMedDato:LocalDate, val tilOgMedDato:LocalDate?) | aap-api-intern/app/bin/main/api/afp/VedtakResponse.kt | 419041254 |
package api.afp
import api.arena.ArenaoppslagRestClient
import api.sporingslogg.Spor
import api.sporingslogg.SporingsloggKafkaClient
import api.util.Config
import api.util.httpCallCounter
import api.util.httpFailedCallCounter
import api.util.sporingsloggFailCounter
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.micrometer.prometheus.PrometheusMeterRegistry
import org.slf4j.LoggerFactory
import java.lang.Exception
import java.util.*
private val secureLog = LoggerFactory.getLogger("secureLog")
private val logger = LoggerFactory.getLogger("App")
private const val AFP_FELLERORDNINGEN_ORGNR = "987414502"
private val consumerTags = mapOf(
AFP_FELLERORDNINGEN_ORGNR to "fellesordningen"
)
object Afp {
private fun getConsumerTag(orgnr: String) = consumerTags[orgnr] ?: orgnr
suspend fun doWorkOffentlig(
call: ApplicationCall,
config: Config,
arenaoppslagRestClient: ArenaoppslagRestClient,
sporingsloggClient: SporingsloggKafkaClient,
prometheus: PrometheusMeterRegistry,
orgnr: String
) {
doWork(
call, config, arenaoppslagRestClient, sporingsloggClient, prometheus, orgnr
)
}
suspend fun doWorkFellesOrdningen(
call: ApplicationCall,
config: Config,
arenaoppslagRestClient: ArenaoppslagRestClient,
sporingsloggClient: SporingsloggKafkaClient,
prometheus: PrometheusMeterRegistry
) {
doWork(
call, config, arenaoppslagRestClient, sporingsloggClient, prometheus, AFP_FELLERORDNINGEN_ORGNR
)
}
private suspend fun doWork(
call: ApplicationCall,
config: Config,
arenaoppslagRestClient: ArenaoppslagRestClient,
sporingsloggClient: SporingsloggKafkaClient,
prometheus: PrometheusMeterRegistry,
orgnr: String
) {
val consumerTag = getConsumerTag(orgnr)
prometheus.httpCallCounter(consumerTag, call.request.path()).increment()
val body = call.receive<VedtakRequest>()
val callId = requireNotNull(call.request.header("x-callid")) { "x-callid ikke satt" }
runCatching {
arenaoppslagRestClient.hentVedtakFellesordning(UUID.fromString(callId), body)
}.onFailure { ex ->
prometheus.httpFailedCallCounter(consumerTag, call.request.path()).increment()
secureLog.error("Klarte ikke hente vedtak fra Arena", ex)
throw ex
}.onSuccess { res ->
if (config.sporingslogg.enabled) {
try {
sporingsloggClient.send(Spor.opprett(body.personidentifikator, res, orgnr))
call.respond(res)
} catch (e: Exception) {
prometheus.sporingsloggFailCounter(consumerTag).increment()
secureLog.error("Klarte ikke produsere til kafka sporingslogg og kan derfor ikke returnere data", e)
call.respond(
HttpStatusCode.ServiceUnavailable,
"Feilet sporing av oppslag, kan derfor ikke returnere data. Feilen er på vår side, prøv igjen senere."
)
}
} else {
logger.warn("Sporingslogg er skrudd av, returnerer data uten å sende til kafka")
call.respond(res)
}
}
}
}
| aap-api-intern/app/bin/main/api/afp/Worker.kt | 4202840386 |
package api.afp
import java.time.LocalDate
data class VedtakRequest(
val personidentifikator: String,
val fraOgMedDato: LocalDate,
val tilOgMedDato: LocalDate
) | aap-api-intern/app/bin/main/api/afp/VedtakRequest.kt | 4140237209 |
package api.sporingslogg
import api.util.KafkaConfig
import api.util.KafkaFactory
import api.util.SporingsloggConfig
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import org.apache.kafka.clients.producer.ProducerRecord
import org.apache.kafka.clients.producer.RecordMetadata
import java.time.LocalDateTime
import java.util.*
class SporingsloggKafkaClient(kafkaConf: KafkaConfig, private val sporingConf: SporingsloggConfig) {
private val producer = KafkaFactory.createProducer<Spor>("aap-api-producer-${sporingConf.topic}", kafkaConf)
fun send(spor: Spor): RecordMetadata = producer.send(record(spor)).get()
private fun <V> record(value: V) = ProducerRecord<String, V>(sporingConf.topic, value)
}
//https://confluence.adeo.no/display/KES/Sporingslogg
data class Spor(
val person: String,
val mottaker: String,
val tema: String,
val behandlingsGrunnlag: String,
val uthentingsTidspunkt: LocalDateTime,
val leverteData: String,
val samtykkeToken: String? = null,
val dataForespoersel: String? = null,
val leverandoer: String? = null
) {
companion object {
fun opprett(
personIdent: String,
utlevertData: Any,
konsumentOrgNr: String
) = Spor(
person = personIdent,
mottaker = konsumentOrgNr,
tema = "AAP",
behandlingsGrunnlag = "GDPR Art. 6(1)e. AFP-tilskottsloven §17 første ledd, §29 andre ledd, første punktum. GDPR Art. 9(2)b",
uthentingsTidspunkt = LocalDateTime.now(),
leverteData = Base64.getEncoder()
.encodeToString(objectMapper.writeValueAsString(utlevertData).encodeToByteArray())
)
private val objectMapper = jacksonObjectMapper()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.registerModule(JavaTimeModule())
}
} | aap-api-intern/app/bin/main/api/sporingslogg/SporingsloggKafkaClient.kt | 653815571 |
package api.arena
import api.dsop.DsopRequest
import api.util.ArenaoppslagConfig
import api.afp.VedtakRequest
import api.afp.VedtakResponse
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.plugins.logging.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.serialization.jackson.*
import io.prometheus.client.Summary
import kotlinx.coroutines.runBlocking
import no.nav.aap.ktor.client.auth.azure.AzureAdTokenProvider
import no.nav.aap.ktor.client.auth.azure.AzureConfig
import org.slf4j.LoggerFactory
import java.util.*
private const val ARENAOPPSLAG_CLIENT_SECONDS_METRICNAME = "arenaoppslag_client_seconds"
private val sikkerLogg = LoggerFactory.getLogger("secureLog")
private val clientLatencyStats: Summary = Summary.build()
.name(ARENAOPPSLAG_CLIENT_SECONDS_METRICNAME)
.quantile(0.5, 0.05) // Add 50th percentile (= median) with 5% tolerated error
.quantile(0.9, 0.01) // Add 90th percentile with 1% tolerated error
.quantile(0.99, 0.001) // Add 99th percentile with 0.1% tolerated error
.help("Latency arenaoppslag, in seconds")
.register()
private val objectMapper = jacksonObjectMapper()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.registerModule(JavaTimeModule())
class ArenaoppslagRestClient(
private val arenaoppslagConfig: ArenaoppslagConfig,
azureConfig: AzureConfig
) {
private val tokenProvider = AzureAdTokenProvider(azureConfig)
fun hentVedtakFellesordning(callId: UUID, vedtakRequest: VedtakRequest): VedtakResponse =
clientLatencyStats.startTimer().use {
runBlocking {
httpClient.post("${arenaoppslagConfig.proxyBaseUrl}/fellesordningen/vedtak"){
accept(ContentType.Application.Json)
header("Nav-Call-Id", callId)
bearerAuth(tokenProvider.getClientCredentialToken(arenaoppslagConfig.scope))
contentType(ContentType.Application.Json)
setBody(vedtakRequest)
}
.bodyAsText()
.also { svar -> sikkerLogg.info("Svar fra arenaoppslag:\n$svar") }
.let(objectMapper::readValue)
}
}
fun hentVedtakDsop(callId: UUID, dsopRequest: DsopRequest): VedtakResponse =
clientLatencyStats.startTimer().use {
runBlocking {
httpClient.post("${arenaoppslagConfig.proxyBaseUrl}/dsop/vedtak"){
accept(ContentType.Application.Json)
header("Nav-Call-Id", callId)
bearerAuth(tokenProvider.getClientCredentialToken(arenaoppslagConfig.scope))
contentType(ContentType.Application.Json)
setBody(dsopRequest)
}
.bodyAsText()
.also { svar -> sikkerLogg.info("Svar fra arenaoppslag:\n$svar") }
.let(objectMapper::readValue)
}
}
fun hentMeldepliktDsop(callId: UUID, dsopRequest: DsopRequest): VedtakResponse =
clientLatencyStats.startTimer().use {
runBlocking {
httpClient.post("${arenaoppslagConfig.proxyBaseUrl}/dsop/meldeplikt"){
accept(ContentType.Application.Json)
header("Nav-Call-Id", callId)
bearerAuth(tokenProvider.getClientCredentialToken(arenaoppslagConfig.scope))
contentType(ContentType.Application.Json)
setBody(dsopRequest)
}
.bodyAsText()
.also { svar -> sikkerLogg.info("Svar fra arenaoppslag:\n$svar") }
.let(objectMapper::readValue)
}
}
private val httpClient = HttpClient(CIO) {
install(HttpTimeout)
install(HttpRequestRetry)
install(Logging) {
level = LogLevel.BODY
logger = object : Logger {
private var logBody = false
override fun log(message: String) {
when {
message == "BODY START" -> logBody = true
message == "BODY END" -> logBody = false
logBody -> sikkerLogg.debug("respons fra Arenaoppslag: $message")
}
}
}
}
install(ContentNegotiation) {
jackson {
disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
registerModule(JavaTimeModule())
}
}
}
}
| aap-api-intern/app/bin/main/api/arena/ArenaoppslagRestClient.kt | 1063714102 |
package api
import api.arena.ArenaoppslagRestClient
import api.util.*
import com.auth0.jwk.JwkProviderBuilder
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import io.ktor.http.*
import io.ktor.serialization.jackson.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.engine.*
import io.ktor.server.metrics.micrometer.*
import io.ktor.server.netty.*
import io.ktor.server.plugins.callloging.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.plugins.cors.routing.*
import io.ktor.server.plugins.swagger.*
import io.ktor.server.request.*
import io.ktor.server.routing.*
import io.micrometer.prometheus.PrometheusConfig
import io.micrometer.prometheus.PrometheusMeterRegistry
import org.slf4j.LoggerFactory
import org.slf4j.event.Level
import java.util.concurrent.TimeUnit
private val logger = LoggerFactory.getLogger("App")
fun main() {
Thread.currentThread().setUncaughtExceptionHandler { _, e -> logger.error("Uhåndtert feil", e) }
embeddedServer(Netty, port = 8080, module = Application::api).start(wait = true)
}
fun Application.api() {
val config = Config()
val prometheus = PrometheusMeterRegistry(PrometheusConfig.DEFAULT)
val arenaRestClient = ArenaoppslagRestClient(config.arenaoppslag, config.azure)
install(CallLogging) {
level = Level.INFO
format { call ->
val status = call.response.status()
val httpMethod = call.request.httpMethod.value
val userAgent = call.request.headers["User-Agent"]
val callId = call.request.header("x-callid") ?: call.request.header("nav-callId") ?: "ukjent"
"Status: $status, HTTP method: $httpMethod, User agent: $userAgent, callId: $callId"
}
filter { call -> call.request.path().startsWith("/actuator").not() }
}
install(MicrometerMetrics) {
registry = prometheus
}
install(ContentNegotiation) {
jackson {
registerModule(JavaTimeModule())
disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
}
}
val jwkProvider = JwkProviderBuilder(config.azure.jwksUri)
.cached(10, 24, TimeUnit.HOURS)
.rateLimited(10, 1, TimeUnit.MINUTES)
.build()
authentication {
jwt {
realm = "intern api"
verifier(jwkProvider, config.azure.issuer)
validate { credential ->
if (credential.payload.audience.contains(config.azure.clientId)) JWTPrincipal(credential.payload) else null
}
}
}
install(CORS) {
anyHost()
allowHeader(HttpHeaders.ContentType)
}
routing {
actuator(prometheus)
swaggerUI(path = "swagger", swaggerFile = "openapi.yaml")
}
}
| aap-api-intern/app/main/api/App.kt | 597961567 |
package api.util
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.micrometer.prometheus.PrometheusMeterRegistry
fun Routing.actuator(prometheus: PrometheusMeterRegistry) {
route("/actuator") {
get("/metrics") {
call.respondText(prometheus.scrape())
}
get("/live") {
call.respond(HttpStatusCode.OK, "api")
}
get("/ready") {
call.respond(HttpStatusCode.OK, "api")
}
}
} | aap-api-intern/app/main/api/util/Actuator.kt | 3270929962 |
package api.util
import no.nav.aap.ktor.client.auth.azure.AzureConfig
private fun getEnvVar(envar: String) = System.getenv(envar) ?: error("missing envvar $envar")
data class Config(
val arenaoppslag: ArenaoppslagConfig = ArenaoppslagConfig(),
val azure: AzureConfig = AzureConfig(
tokenEndpoint = getEnvVar("AZURE_OPENID_CONFIG_TOKEN_ENDPOINT"),
clientId = getEnvVar("AZURE_APP_CLIENT_ID"),
clientSecret = getEnvVar("AZURE_APP_CLIENT_SECRET"),
jwksUri = getEnvVar("AZURE_OPENID_CONFIG_JWKS_URI"),
issuer = getEnvVar("AZURE_OPENID_CONFIG_ISSUER")
),
)
data class ArenaoppslagConfig(
val proxyBaseUrl:String = getEnvVar("ARENAOPPSLAG_PROXY_BASE_URL"),
val scope: String= getEnvVar("ARENAOPPSLAG_SCOPE")
)
| aap-api-intern/app/main/api/util/Config.kt | 1664822209 |
package api.arena
import api.util.ArenaoppslagConfig
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.plugins.logging.*
import io.ktor.serialization.jackson.*
import io.prometheus.client.Summary
import no.nav.aap.ktor.client.auth.azure.AzureAdTokenProvider
import no.nav.aap.ktor.client.auth.azure.AzureConfig
import org.slf4j.LoggerFactory
private const val ARENAOPPSLAG_CLIENT_SECONDS_METRICNAME = "arenaoppslag_client_seconds"
private val sikkerLogg = LoggerFactory.getLogger("secureLog")
private val clientLatencyStats: Summary = Summary.build()
.name(ARENAOPPSLAG_CLIENT_SECONDS_METRICNAME)
.quantile(0.5, 0.05) // Add 50th percentile (= median) with 5% tolerated error
.quantile(0.9, 0.01) // Add 90th percentile with 1% tolerated error
.quantile(0.99, 0.001) // Add 99th percentile with 0.1% tolerated error
.help("Latency arenaoppslag, in seconds")
.register()
private val objectMapper = jacksonObjectMapper()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.registerModule(JavaTimeModule())
class ArenaoppslagRestClient(
private val arenaoppslagConfig: ArenaoppslagConfig,
azureConfig: AzureConfig
) {
private val tokenProvider = AzureAdTokenProvider(azureConfig)
private val httpClient = HttpClient(CIO) {
install(HttpTimeout)
install(HttpRequestRetry)
install(Logging) {
level = LogLevel.BODY
logger = object : Logger {
private var logBody = false
override fun log(message: String) {
when {
message == "BODY START" -> logBody = true
message == "BODY END" -> logBody = false
logBody -> sikkerLogg.debug("respons fra Arenaoppslag: $message")
}
}
}
}
install(ContentNegotiation) {
jackson {
disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
registerModule(JavaTimeModule())
}
}
}
}
| aap-api-intern/app/main/api/arena/ArenaoppslagRestClient.kt | 468643793 |
package com.example.quizapp
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.quizapp", appContext.packageName)
}
} | QuizAppMPMC/app/src/androidTest/java/com/example/quizapp/ExampleInstrumentedTest.kt | 1745855708 |
package com.example.quizapp
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)
}
} | QuizAppMPMC/app/src/test/java/com/example/quizapp/ExampleUnitTest.kt | 1706911147 |
package com.example.quizapp.ui
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.example.quizapp.R
import com.example.quizapp.model.Question
import com.example.quizapp.utils.Constants
class QuestionsActivity : AppCompatActivity(), View.OnClickListener {
private lateinit var progressBar: ProgressBar
private lateinit var textViewProgress: TextView
private lateinit var textViewQuestion: TextView
private lateinit var textViewOptionOne: TextView
private lateinit var textViewOptionTwo: TextView
private lateinit var textViewOptionThree: TextView
private lateinit var textViewOptionFour: TextView
private lateinit var checkButton: Button
private var questionsCounter = 0
private lateinit var questionsList: MutableList<Question>
private var selectedAnswer = 0
private var answered = false
private lateinit var currentQuestion: Question
private lateinit var name: String
private var score = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_questions)
progressBar = findViewById(R.id.progressBar)
textViewProgress = findViewById(R.id.text_view_progress)
textViewQuestion = findViewById(R.id.question_text_view)
checkButton = findViewById(R.id.button_check)
textViewOptionOne = findViewById(R.id.text_view_option_one)
textViewOptionTwo = findViewById(R.id.text_view_option_two)
textViewOptionThree = findViewById(R.id.text_view_option_three)
textViewOptionFour = findViewById(R.id.text_view_option_four)
textViewOptionOne.setOnClickListener(this)
textViewOptionTwo.setOnClickListener(this)
textViewOptionThree.setOnClickListener(this)
textViewOptionFour.setOnClickListener(this)
checkButton.setOnClickListener(this)
questionsList = Constants.getQuestions()
Log.d("QuestionSize", "$questionsList.size")
showNextQuestion()
if (intent.hasExtra(Constants.USER_NAME)) {
name = intent.getStringExtra(Constants.USER_NAME)!!
}
}
private fun showNextQuestion() {
if (questionsCounter < questionsList.size) {
checkButton.text = "CHECK"
currentQuestion = questionsList[questionsCounter]
resetOptions()
val question = questionsList[questionsCounter]
progressBar.progress = questionsCounter
textViewProgress.text = "${questionsCounter + 1}/${progressBar.max}"
textViewQuestion.text = question.question
textViewOptionOne.text = question.optionOne
textViewOptionTwo.text = question.optionTwo
textViewOptionThree.text = question.optionThree
textViewOptionFour.text = question.optionFour
} else {
checkButton.text = "FINISH"
// start activity here
Intent(this, ResultActivity::class.java).also {
it.putExtra(Constants.USER_NAME, name)
it.putExtra(Constants.SCORE, score)
it.putExtra(Constants.TOTAL_QUESTIONS, questionsList.size)
startActivity(it)
}
}
questionsCounter++
answered = false
}
private fun resetOptions() {
val options = mutableListOf<TextView>()
options.add(textViewOptionOne)
options.add(textViewOptionTwo)
options.add(textViewOptionThree)
options.add(textViewOptionFour)
for (option in options) {
option.setTextColor(Color.parseColor("#7A8089"))
option.typeface = Typeface.DEFAULT
option.background = ContextCompat.getDrawable(
this,
R.drawable.default_option_border_bg
)
}
}
override fun onClick(view: View?) {
when(view?.id) {
R.id.text_view_option_one -> {
selectedOption(textViewOptionOne, 1)
}
R.id.text_view_option_two -> {
selectedOption(textViewOptionTwo, 2)
}
R.id.text_view_option_three -> {
selectedOption(textViewOptionThree, 3)
}
R.id.text_view_option_four -> {
selectedOption(textViewOptionFour, 4)
}
R.id.button_check -> {
if (!answered) {
checkAnswer()
} else {
showNextQuestion()
}
selectedAnswer = 0
}
}
}
private fun selectedOption(textView: TextView, selectOptionNumber: Int) {
resetOptions()
selectedAnswer = selectOptionNumber
textView.setTextColor(Color.parseColor("#363A43"))
textView.setTypeface(textView.typeface, Typeface.BOLD)
textView.background = ContextCompat.getDrawable(
this,
R.drawable.selected_option_border_bg
)
}
private fun checkAnswer() {
answered = true
if (selectedAnswer == currentQuestion.correctAnswer) {
score++
highlightAnswer(selectedAnswer)
} else {
when(selectedAnswer) {
1 -> {
textViewOptionOne.background = ContextCompat.getDrawable(this,
R.drawable.wrong_option_border_bg)
}
2 -> {
textViewOptionTwo.background = ContextCompat.getDrawable(this,
R.drawable.wrong_option_border_bg)
}
3 -> {
textViewOptionThree.background = ContextCompat.getDrawable(this,
R.drawable.wrong_option_border_bg)
}
4 -> {
textViewOptionFour.background = ContextCompat.getDrawable(this,
R.drawable.wrong_option_border_bg)
}
}
}
checkButton.text = "NEXT"
showSolution()
}
private fun showSolution() {
selectedAnswer = currentQuestion.correctAnswer
highlightAnswer(selectedAnswer)
}
private fun highlightAnswer(answer: Int) {
when (answer) {
1 -> {
textViewOptionOne.background = ContextCompat.getDrawable(this,
R.drawable.correct_option_border_bg)
}
2 -> {
textViewOptionTwo.background = ContextCompat.getDrawable(this,
R.drawable.correct_option_border_bg)
}
3 -> {
textViewOptionThree.background = ContextCompat.getDrawable(this,
R.drawable.correct_option_border_bg)
}
4 -> {
textViewOptionFour.background = ContextCompat.getDrawable(this,
R.drawable.correct_option_border_bg)
}
}
}
} | QuizAppMPMC/app/src/main/java/com/example/quizapp/ui/QuestionsActivity.kt | 2479204593 |
package com.example.quizapp.ui
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import com.example.quizapp.MainActivity
import com.example.quizapp.R
import com.example.quizapp.utils.Constants
class ResultActivity : AppCompatActivity() {
private lateinit var textViewScore: TextView
private lateinit var textViewName: TextView
private lateinit var finishButton: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_result)
textViewScore = findViewById(R.id.textview_score)
textViewName = findViewById(R.id.textview_name)
finishButton = findViewById(R.id.btn_finish)
val totalQuestions = intent.getIntExtra(Constants.TOTAL_QUESTIONS, 0)
val score = intent.getIntExtra(Constants.SCORE, 0)
val name = intent.getStringExtra(Constants.USER_NAME)
textViewScore.text = "Your score is $score out of $totalQuestions"
textViewName.text = name
finishButton.setOnClickListener {
Intent(this, MainActivity::class.java).also {
startActivity(it)
}
}
}
} | QuizAppMPMC/app/src/main/java/com/example/quizapp/ui/ResultActivity.kt | 3765411793 |
package com.example.quizapp
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.example.quizapp.ui.QuestionsActivity
import com.example.quizapp.utils.Constants
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val startButton: Button = findViewById(R.id.button_start)
val editTextName: EditText = findViewById(R.id.name)
val editTextRegno: EditText = findViewById(R.id.regno)
startButton.setOnClickListener {
if (!editTextName.text.isEmpty() && !editTextRegno.text.isEmpty()) {
Intent(this@MainActivity, QuestionsActivity::class.java).also {
it.putExtra(Constants.USER_NAME, editTextName.text.toString())
startActivity(it)
finish()
}
} else {
Toast.makeText(this@MainActivity, "Please enter your details", Toast.LENGTH_LONG).show()
}
}
}
} | QuizAppMPMC/app/src/main/java/com/example/quizapp/MainActivity.kt | 4092430899 |
package com.example.quizapp.utils
import com.example.quizapp.model.Question
object Constants {
const val USER_NAME = "user_name"
const val TOTAL_QUESTIONS = "total_questions"
const val SCORE = "correct_answers"
fun getQuestions(): MutableList<Question> {
val questions = mutableListOf<Question>()
val quest1 = Question(
1, "What is the maximum addressable memory in the 8086 microprocessor?",
"64 KB",
"1 MB",
"16 MB",
"4 GB",
3
)
questions.add(quest1)
val quest2 = Question(
2, "Which addressing mode is not supported by the 8086 microprocessor?",
"Register addressing mode",
"Immediate addressing mode",
"Base register addressing mode",
"Indirect addressing mode",
1
)
questions.add(quest2)
val quest3 = Question(
3, "What is the data bus size of the 8086 microprocessor?",
"8 bits",
"16 bits",
"32 bits",
"64 bits",
2
)
questions.add(quest3)
val quest4 = Question(
4, "How many general-purpose I/O ports does the 8051 microcontroller have?",
"1",
"2",
"3",
"4",
4
)
questions.add(quest4)
val quest5 = Question(
5, "Which register is used as a program counter in the 8051 microcontroller?",
"R0",
"R1",
"DPTR",
"PC",
4
)
questions.add(quest5)
val quest6 = Question(
6, "What is the clock frequency range of the 8051 microcontroller?",
"1 MHz - 10 MHz",
"4 MHz - 16 MHz",
"8 MHz - 24 MHz",
"12 MHz - 30 MHz",
3
)
questions.add(quest6)
val quest7 = Question(
7, "Which ARM processor architecture is most commonly used in mobile devices?",
"ARMv5",
"ARMv7",
"ARMv8",
"ARMv9",
2
)
questions.add(quest7)
val quest8 = Question(
8, "What is the primary advantage of the ARM architecture over traditional CISC architectures?",
"Lower power consumption",
"Higher clock speeds",
"Larger instruction set",
"More complex instructions",
1
)
questions.add(quest8)
val quest9 = Question(
9, "Which company is responsible for the development of the ARM architecture?",
"Intel",
"AMD",
"ARM Holdings",
"Qualcomm",
3
)
questions.add(quest9)
val quest10 = Question(
10, "What does the term \"RISC\" stand for in the context of ARM processors?",
"Random Instruction Set Computing",
"Reduced Instruction Set Computing",
"Rapid Instruction Set Computing",
"Real Instruction Set Computing",
2
)
questions.add(quest10)
return questions
}
} | QuizAppMPMC/app/src/main/java/com/example/quizapp/utils/Constants.kt | 1097778054 |
package com.example.quizapp.model
data class Question(
val id: Int,
val question: String,
val optionOne: String,
val optionTwo: String,
val optionThree: String,
val optionFour: String,
val correctAnswer: Int
) | QuizAppMPMC/app/src/main/java/com/example/quizapp/model/Question.kt | 3979293411 |
package com.example
import com.example.plugins.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.testing.*
import kotlin.test.*
internal class ApplicationTest {
@Test
fun testRoot() = testApplication {
application {
configureRouting()
}
client.get("/").apply {
assertEquals(HttpStatusCode.OK, status)
assertEquals("Hello World!", bodyAsText())
}
}
}
| tech-talk/src/test/kotlin/com/example/ApplicationTest.kt | 1236986327 |
package com.example
import com.example.plugins.*
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
fun main() {
embeddedServer(Netty, port = 8080, host = "0.0.0.0", module = Application::module)
.start(wait = true)
}
fun Application.module() {
configureSerialization()
configureDatabases()
configureTemplating()
configureHTTP()
configureSecurity()
configureRouting()
}
| tech-talk/src/main/kotlin/com/example/Application.kt | 878938912 |
package com.example.plugins
import io.ktor.server.application.*
import io.ktor.server.plugins.openapi.*
import io.ktor.server.plugins.swagger.*
import io.ktor.server.routing.*
fun Application.configureHTTP() {
routing {
swaggerUI(path = "openapi")
}
routing {
openAPI(path = "openapi")
}
}
| tech-talk/src/main/kotlin/com/example/plugins/HTTP.kt | 627132518 |
package com.example.plugins
import io.ktor.server.application.*
import io.ktor.server.plugins.autohead.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
fun Application.configureRouting() {
install(AutoHeadResponse)
routing {
get("/") {
call.respondText("Hello World!")
}
}
}
| tech-talk/src/main/kotlin/com/example/plugins/Routing.kt | 3199867660 |
package com.example.plugins
import com.fasterxml.jackson.databind.*
import io.ktor.serialization.jackson.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
fun Application.configureSerialization() {
install(ContentNegotiation) {
json()
jackson {
enable(SerializationFeature.INDENT_OUTPUT)
}
}
routing {
get("/json/kotlinx-serialization") {
call.respond(mapOf("hello" to "world"))
}
get("/json/jackson") {
call.respond(mapOf("hello" to "world"))
}
}
}
| tech-talk/src/main/kotlin/com/example/plugins/Serialization.kt | 288320516 |
package com.example.plugins
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.thymeleaf.Thymeleaf
import io.ktor.server.thymeleaf.ThymeleafContent
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver
fun Application.configureTemplating() {
install(Thymeleaf) {
setTemplateResolver(ClassLoaderTemplateResolver().apply {
prefix = "templates/thymeleaf/"
suffix = ".html"
characterEncoding = "utf-8"
})
}
routing {
get("/html-thymeleaf") {
call.respond(ThymeleafContent("index", mapOf("user" to ThymeleafUser(1, "user1"))))
}
}
}
data class ThymeleafUser(val id: Int, val name: String)
| tech-talk/src/main/kotlin/com/example/plugins/Templating.kt | 4017901344 |
package com.example.plugins
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import org.jetbrains.exposed.sql.*
fun Application.configureDatabases() {
val database = Database.connect(
url = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1",
user = "root",
driver = "org.h2.Driver",
password = ""
)
val userService = UserService(database)
routing {
// Create user
post("/users") {
val user = call.receive<ExposedUser>()
val id = userService.create(user)
call.respond(HttpStatusCode.Created, id)
}
// Read user
get("/users/{id}") {
val id = call.parameters["id"]?.toInt() ?: throw IllegalArgumentException("Invalid ID")
val user = userService.read(id)
if (user != null) {
call.respond(HttpStatusCode.OK, user)
} else {
call.respond(HttpStatusCode.NotFound)
}
}
// Update user
put("/users/{id}") {
val id = call.parameters["id"]?.toInt() ?: throw IllegalArgumentException("Invalid ID")
val user = call.receive<ExposedUser>()
userService.update(id, user)
call.respond(HttpStatusCode.OK)
}
// Delete user
delete("/users/{id}") {
val id = call.parameters["id"]?.toInt() ?: throw IllegalArgumentException("Invalid ID")
userService.delete(id)
call.respond(HttpStatusCode.OK)
}
}
}
| tech-talk/src/main/kotlin/com/example/plugins/Databases.kt | 1568703506 |
package com.example.plugins
import org.jetbrains.exposed.sql.transactions.transaction
import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import kotlinx.serialization.Serializable
import kotlinx.coroutines.Dispatchers
import org.jetbrains.exposed.sql.*
@Serializable
data class ExposedUser(val name: String, val age: Int)
class UserService(private val database: Database) {
object Users : Table() {
val id = integer("id").autoIncrement()
val name = varchar("name", length = 50)
val age = integer("age")
override val primaryKey = PrimaryKey(id)
}
init {
transaction(database) {
SchemaUtils.create(Users)
}
}
private suspend fun <T> dbQuery(block: suspend () -> T): T =
newSuspendedTransaction(Dispatchers.IO) { block() }
suspend fun create(user: ExposedUser): Int = dbQuery {
Users.insert {
it[name] = user.name
it[age] = user.age
}[Users.id]
}
suspend fun read(id: Int): ExposedUser? {
return dbQuery {
Users.select { Users.id eq id }
.map { ExposedUser(it[Users.name], it[Users.age]) }
.singleOrNull()
}
}
suspend fun update(id: Int, user: ExposedUser) {
dbQuery {
Users.update({ Users.id eq id }) {
it[name] = user.name
it[age] = user.age
}
}
}
suspend fun delete(id: Int) {
dbQuery {
Users.deleteWhere { Users.id.eq(id) }
}
}
}
| tech-talk/src/main/kotlin/com/example/plugins/UsersSchema.kt | 1453099076 |
package com.example.plugins
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
fun Application.configureSecurity() {
// Please read the jwt property from the config file if you are using EngineMain
val jwtAudience = "jwt-audience"
val jwtDomain = "https://jwt-provider-domain/"
val jwtRealm = "ktor sample app"
val jwtSecret = "secret"
authentication {
jwt {
realm = jwtRealm
verifier(
JWT
.require(Algorithm.HMAC256(jwtSecret))
.withAudience(jwtAudience)
.withIssuer(jwtDomain)
.build()
)
validate { credential ->
if (credential.payload.audience.contains(jwtAudience)) JWTPrincipal(credential.payload) else null
}
}
}
}
| tech-talk/src/main/kotlin/com/example/plugins/Security.kt | 2113201246 |
package com.example.gadgetsfuture
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.gadgetsfuture", appContext.packageName)
}
} | GadgetsFuture/app/src/androidTest/java/com/example/gadgetsfuture/ExampleInstrumentedTest.kt | 114732776 |
package com.example.gadgetsfuture
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)
}
} | GadgetsFuture/app/src/test/java/com/example/gadgetsfuture/ExampleUnitTest.kt | 1705615401 |
package com.example.gadgetsfuture
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.transition.Fade
import android.view.animation.AnimationUtils
import android.widget.ImageView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
startActivity(Intent(this, InicioSesion::class.java))
[email protected](
R.anim.animate_fade_enter,
R.anim.animate_fade_exit
)
}
} | GadgetsFuture/app/src/main/java/com/example/gadgetsfuture/MainActivity.kt | 2865069701 |
package com.example.gadgetsfuture
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.android.material.bottomnavigation.BottomNavigationView
class FrmPrincipal : AppCompatActivity() {
private lateinit var bottomNavigationView: BottomNavigationView
private lateinit var cart: Cart_fragment
private lateinit var home: Home_fragment
private lateinit var store: store_fragment
private lateinit var user: UserFragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_frm_principal)
bottomNavigationView = findViewById(R.id.bottom_navigation)
// Instancias
cart = Cart_fragment()
home = Home_fragment()
store = store_fragment()
user = UserFragment()
supportFragmentManager.beginTransaction().replace(R.id.container, home).commit()
// Badge que muestra la cantidad de los productos
val badge = bottomNavigationView.getOrCreateBadge(R.id.cart)
badge.isVisible = true
badge.number = 5
bottomNavigationView.setOnItemSelectedListener { menuItem ->
when (menuItem.itemId) {
R.id.home -> {
supportFragmentManager.beginTransaction().replace(R.id.container, home).commit()
true
}
R.id.cart -> {
supportFragmentManager.beginTransaction().replace(R.id.container, cart).commit()
true
}
R.id.store -> {
supportFragmentManager.beginTransaction().replace(R.id.container, store).commit()
true
}
R.id.user -> {
supportFragmentManager.beginTransaction().replace(R.id.container, user).commit()
true
}
// Agrega más casos para otras opciones del menú si es necesario
else -> false
}
}
}
} | GadgetsFuture/app/src/main/java/com/example/gadgetsfuture/FrmPrincipal.kt | 1966768936 |
package com.example.gadgetsfuture;
import android.content.Context
import android.net.ConnectivityManager
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.volley.Request
import com.android.volley.toolbox.JsonArrayRequest
import com.android.volley.toolbox.Volley
import com.denzcoskun.imageslider.ImageSlider
import com.denzcoskun.imageslider.constants.ScaleTypes
import com.denzcoskun.imageslider.models.SlideModel
import com.example.gadgetsfuture.adapter.adapterHome
import com.example.gadgetsfuture.config.config
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.json.JSONArray
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [Home_fragment.newInstance] factory method to
* create an instance of this fragment.
*/
class Home_fragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
//Se define la variable que contiene el RecyclerView
lateinit var recycler: RecyclerView
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
var view= inflater.inflate(R.layout.fragment_home, container, false)
var imageSlider: ImageSlider = view.findViewById(R.id.imageSlider)
var slideModels : ArrayList<SlideModel> = ArrayList<SlideModel>()
slideModels.add(SlideModel(R.drawable.banner_gadgets_future,ScaleTypes.FIT))
slideModels.add(SlideModel(R.drawable.banner_gadgets_future2,ScaleTypes.FIT))
slideModels.add(SlideModel(R.drawable.banner_gadgets_future3,ScaleTypes.FIT))
imageSlider.setImageList(slideModels,ScaleTypes.FIT)
// MUESTRA LA VISTA HOME CON LOS PRODUCTOS
recycler=view.findViewById(R.id.RVHome)
llamarPeticion()
return view
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment home.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
Home_fragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
fun llamarPeticion(){
GlobalScope.launch(Dispatchers.Main) {
try {
peticionListaProductosH()
}catch (error: Exception){
Toast.makeText(activity, "Error en el servidor, por favor conectate a internet", Toast.LENGTH_LONG).show()
}
}
}
private suspend fun peticionListaProductosH() {
val url = config.urlBase + "api/list_product/v1/"
val queue = Volley.newRequestQueue(activity)
val request = JsonArrayRequest(
Request.Method.GET,
url,
null,
{ response ->
cargarLista(response)
},
{ error ->
Toast.makeText(activity,"Error de conexión, intentalo más tarde", Toast.LENGTH_LONG).show()
}
)
queue.add(request)
}
private fun cargarLista(listaProductos: JSONArray) {
recycler.layoutManager = LinearLayoutManager(activity)
val adapter = adapterHome(activity, listaProductos)
adapter.onclick = {
val bundle = Bundle()
bundle.putInt("id_productoH", it.getInt("id"))
val transaction = requireFragmentManager().beginTransaction()
val fragmento = detalle_producto()
fragmento.arguments = bundle
transaction.replace(R.id.container, fragmento).commit()
transaction.addToBackStack(null)
}
recycler.adapter = adapter
}
} | GadgetsFuture/app/src/main/java/com/example/gadgetsfuture/Home_fragment.kt | 4020804963 |
package com.example.principal
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.gadgetsfuture.R
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [pedidos2Fragment.newInstance] factory method to
* create an instance of this fragment.
*/
class pedidos2Fragment<T> : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_pedidos2, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment pedidos2Fragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
pedidos2Fragment<Any>().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | GadgetsFuture/app/src/main/java/com/example/gadgetsfuture/pedidos2Fragment.kt | 1230522875 |
package com.example.gadgetsfuture.config
import android.content.SharedPreferences
class config {
//crear una variable static
companion object{
lateinit var SharedPreferences: SharedPreferences
//una variable para el token
var token:String = ""
//crer una variable para almacenar la url base
//puerto SENA:
const val urlBase="http://192.168.137.1:8000/"
//puerto local:
//const val urlBase="http://192.168.1.5:8000/"
const val urlTienda="${urlBase}tienda/api/v1/"
const val urlCuenta="${urlBase}cuenta/api/"
}
} | GadgetsFuture/app/src/main/java/com/example/gadgetsfuture/config/config.kt | 614199062 |
package com.example.gadgetsfuture
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatDelegate
import androidx.navigation.ActivityNavigator
import com.android.volley.Request
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.JsonRequest
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.example.gadgetsfuture.config.config
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject
class InicioSesion : AppCompatActivity() {
lateinit var correoEditText: EditText
lateinit var passwordEditText: EditText
lateinit var loginButton: Button
lateinit var passwordError: TextView
lateinit var context:Context
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
ActivityNavigator.applyPopAnimationsToPendingTransition(this)
setContentView(R.layout.activity_inicio_sesion)
context=applicationContext
MostrarContrasena()
correoEditText = findViewById(R.id.txtCorreo)
passwordEditText = findViewById(R.id.txtContra)
loginButton = findViewById(R.id.btnIniciarS)
passwordError = findViewById(R.id.passwordError)
// Verificar si las credenciales están guardadas
if (checkCredentials()) {
// Si las credenciales están guardadas, iniciar la actividad principal
val intent = Intent(this, FrmPrincipal::class.java)
startActivity(intent)
finish()
}
// Forzar el modo claro
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
delegate.applyDayNight()
}
fun olvideContra(view: View) {
val olvideContra = Intent(this, Recuperar_Contrasena::class.java)
startActivity(olvideContra)
[email protected](
R.anim.animate_slide_left_enter,
R.anim.animate_slide_left_exit
)
}
fun registrarse(view: View) {
val regis = Intent(this, Registrarse::class.java)
startActivity(regis)
finish()
[email protected](
R.anim.animate_slide_left_enter,
R.anim.animate_slide_left_exit
)
}
fun inicioSesion(view: View) {
GlobalScope.launch {
if (login()) {
// Inicio de sesión exitoso
val intent = Intent(context, FrmPrincipal::class.java)
startActivity(intent)
finish()
} else {
passwordError.visibility = View.VISIBLE
passwordError.text = "Correo o contraseña incorrecta"
}
}
}
private suspend fun login(): Boolean {
var peticion: Boolean = false
var inicioExitoso: Boolean = false
val username = correoEditText.text.toString()
val password = passwordEditText.text.toString()
var url = config.urlCuenta + "v1/login/"
// Preparar los parametros
var parametros = JSONObject().apply {
put("correo_electronico", username)
put("password", password)
}
// Hacer la petición
// Si la api responde un json = JsonRequest
// Si responde un String = StringRequest
val request = JsonObjectRequest(
Request.Method.POST,
url,
parametros,
{ response ->
// Cuando la respuesta es positiva
Toast.makeText(context, "Inicio correcto", Toast.LENGTH_LONG).show()
inicioExitoso = true
peticion = true
// Obtener el token de la respuesta y guardarlo
val token = response.getString("token")
if (token.isNotEmpty()) {
config.token = token
}
saveCredentials(username, password, token) // Guardar las credenciales
},
{ error ->
inicioExitoso = false
peticion = true
}
)
var queue = Volley.newRequestQueue(context)
queue.add(request)
while (!peticion) {
delay(500)
}
return inicioExitoso
}
// Función para guardar las credenciales
private fun saveCredentials(username: String, password: String,token: String) {
config.SharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
val editor = config.SharedPreferences.edit()
editor.putString("username", username)
editor.putString("password", password)
editor.apply()
}
// Función para verificar si las credenciales están guardadas
private fun checkCredentials(): Boolean {
config.SharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
val username = config.SharedPreferences.getString("username", null)
val password = config.SharedPreferences.getString("password", null)
return !username.isNullOrEmpty() && !password.isNullOrEmpty()
}
private fun MostrarContrasena(){
val checkBoxMostrarContrasena: CheckBox = findViewById(R.id.checkBoxMostrarContrasena)
val password: EditText = findViewById(R.id.txtContra)
checkBoxMostrarContrasena.setOnCheckedChangeListener() {buttonView, isChecked ->
if (isChecked) {
password.inputType = android.text.InputType.TYPE_CLASS_TEXT or android.text.InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
} else {
password.inputType = android.text.InputType.TYPE_CLASS_TEXT or android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD
}
}
}
}
| GadgetsFuture/app/src/main/java/com/example/gadgetsfuture/InicioSesion.kt | 771566525 |
package com.example.gadgetsfuture.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
import com.example.gadgetsfuture.R
import com.example.gadgetsfuture.config.config
import org.json.JSONArray
import org.json.JSONObject
class adapterHome (var context: Context?, var listaProductoH:JSONArray)
:RecyclerView.Adapter<adapterHome.MyHolder>() {
inner class MyHolder(Item: View):RecyclerView.ViewHolder(Item){
var lblnombre:TextView
var lblprecio:TextView
var lblprecioDescunto:TextView
var lblporcentajeDescunto:TextView
var imgProducto: ImageView
var btnCarrito: Button
var cardProductoH: CardView
init {
lblnombre=itemView.findViewById(R.id.lblNombreH)
lblprecio=itemView.findViewById(R.id.lblPrecioH)
lblprecioDescunto=itemView.findViewById(R.id.lblDescuentoPrecioH)
lblporcentajeDescunto=itemView.findViewById(R.id.lblPorcenDescuentoH)
imgProducto=itemView.findViewById(R.id.imgProductoH)
btnCarrito=itemView.findViewById(R.id.btnCarritoH)
cardProductoH=itemView.findViewById(R.id.cardProductoH)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): adapterHome.MyHolder {
var itemView=LayoutInflater.from(context).inflate(R.layout.item_home,parent,false)
return MyHolder(itemView)
}
// Variable que almacena la funcion onclick
var onclick:((JSONObject)->Unit)?=null
override fun onBindViewHolder(holder: adapterHome.MyHolder, position: Int) {
val producto = listaProductoH.getJSONObject(position)
var nombre=producto.getString("nombre")
if (nombre.length >= 40){
nombre = nombre.substring(0, 39) + "..."
}
val precio=producto.getDouble("precio")
var url = config.urlBase
val imgProductoUrl= url+producto.getString("imagen")
//val precioDescunto=producto.getDouble()
//val porcentajeDescuento=producto.getDouble()
holder.lblnombre.text = nombre
holder.lblprecio.text = "$precio"
Glide.with(holder.itemView.context).load(imgProductoUrl).into(holder.imgProducto)
// cardProductoH nos lleva a detalle del producto
holder.cardProductoH.setOnClickListener {
onclick?.invoke(producto)
}
}
override fun getItemCount(): Int {
return listaProductoH.length()
}
}
/*package com.example.gadgetsfuture.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.gadgetsfuture.R
import com.example.gadgetsfuture.config.config
import org.json.JSONArray
import org.json.JSONObject
class adapterHome (var context: Context?, var listaProductoH:JSONArray)
:RecyclerView.Adapter<adapterHome.MyHolder>() {
inner class MyHolder(Item: View):RecyclerView.ViewHolder(Item){
lateinit var lblnombre:TextView
lateinit var lblprecio:TextView
lateinit var lblprecioDescunto:TextView
lateinit var lblporcentajeDescunto:TextView
lateinit var imgProducto: ImageView
lateinit var btnCarrito: Button
lateinit var cardProductoH: CardView
init {
lblnombre=itemView.findViewById(R.id.lblNombreH)
lblprecio=itemView.findViewById(R.id.lblPrecioH)
lblprecioDescunto=itemView.findViewById(R.id.lblDescuentoPrecioH)
lblporcentajeDescunto=itemView.findViewById(R.id.lblPorcenDescuentoH)
imgProducto=itemView.findViewById(R.id.imgProductoH)
btnCarrito=itemView.findViewById(R.id.btnCarritoH)
cardProductoH=itemView.findViewById(R.id.cardProductoH)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): adapterHome.MyHolder {
var itemView=LayoutInflater.from(context).inflate(R.layout.item_home,parent,false)
return MyHolder(itemView)
}
// Variable que almacena la funcion onclick
var onclick:((JSONObject)->Unit)?=null
override fun onBindViewHolder(holder: adapterHome.MyHolder, position: Int) {
val producto = listaProductoH.getJSONObject(position)
val nombre=producto.getString("nombre")
val precio=producto.getDouble("precio")
var url = config.urlBase
val imgProductoUrl= url+producto.getString("imagen")
//val precioDescunto=producto.getDouble()
//val porcentajeDescunto=producto.getDouble()
holder.lblnombre.text = nombre
holder.lblprecio.text = "$precio"
Glide.with(holder.itemView.context).load(imgProductoUrl).into(holder.imgProducto)
// Imagen button nos lleva a detalle del producto
holder.cardProductoH.setOnClickListener {
onclick?.invoke(producto)
}
}
override fun getItemCount(): Int {
return listaProductoH.length()
}
}*/ | GadgetsFuture/app/src/main/java/com/example/gadgetsfuture/adapter/adapterHome.kt | 1528998224 |
package com.example.gadgetsfuture
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [detalle_producto.newInstance] factory method to
* create an instance of this fragment.
*/
class detalle_producto : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_detalle_producto, container, false)
val btnBack: ImageButton = view.findViewById(R.id.btnBack)
btnBack.setOnClickListener {
// Cerrar el fragmento (puedes cambiar esto según lo que necesites hacer)
requireActivity().supportFragmentManager.popBackStack()
}
return view
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment detalle_producto.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
detalle_producto().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | GadgetsFuture/app/src/main/java/com/example/gadgetsfuture/detalle_producto.kt | 3011144232 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.