content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.example.petlover.navigation object Routes { const val DETAILS_SCREEN = "WELCOME_SCREEN" const val INPUT_USER_SCREEN = "INPUT_USER_SCREEN" const val USER_NAME = "NAME" const val PET_CHOOSEN = "PET_CHOOSEN" }
PetLover/app/src/main/java/com/example/petlover/navigation/Routes.kt
717678564
package com.example.petlover.navigation import androidx.compose.runtime.Composable import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument import com.example.petlover.presentation.ui.UserInputViewModel import com.example.petlover.presentation.ui.view.UserInputScreen import com.example.petlover.presentation.ui.view.DetailsScreen @Composable fun PetLoverNavigationGraph( userInputViewModel: UserInputViewModel = viewModel() ) { val navController = rememberNavController() NavHost(navController = navController, startDestination = Routes.DETAILS_SCREEN) { composable(Routes.INPUT_USER_SCREEN) { UserInputScreen( viewModel = userInputViewModel, showDetailsScreen = { navController.navigate(route = Routes.DETAILS_SCREEN + "/${it.first}/${it.second}") } ) } composable( route = "${Routes.DETAILS_SCREEN}/${Routes.USER_NAME}/${Routes.PET_CHOOSEN}", arguments = listOf( navArgument(name = Routes.USER_NAME) { type = NavType.StringType }, navArgument(name = Routes.PET_CHOOSEN) { type = NavType.StringType } ) ) { val userName = it.arguments?.getString(Routes.USER_NAME) val petChoosen = it.arguments?.getString(Routes.PET_CHOOSEN) DetailsScreen(userName, petChoosen) } } }
PetLover/app/src/main/java/com/example/petlover/navigation/PetLoverNavigationGraph.kt
3594046009
package com.example.petlover.presentation.ui.components import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.petlover.R @Composable fun AnimalCard( imagePath: Int, selected: Boolean, animalSelected: (animalName: String) -> Unit ) { val localFocusManager = LocalFocusManager.current Card( shape = RoundedCornerShape(8.dp), modifier = Modifier .padding(24.dp) .size(130.dp), elevation = CardDefaults.cardElevation(4.dp) ) { Box( modifier = Modifier .fillMaxSize() .border( width = 1.dp, color = if (selected) Color.Green else Color.Transparent, shape = RoundedCornerShape(8.dp) ) ) Image( modifier = Modifier .padding(16.dp) .wrapContentSize() .clickable { val animalName = if (imagePath == R.drawable.ic_launcher_foreground) "Cat" else "Dog" animalSelected(animalName) localFocusManager.clearFocus() }, painter = painterResource(id = imagePath), contentDescription = "Animal Image" ) } } @Preview(showBackground = true) @Composable fun AnimalCardPreview() { AnimalCard(R.drawable.ic_launcher_foreground, true, { "Dog" }) }
PetLover/app/src/main/java/com/example/petlover/presentation/ui/components/AnimalCard.kt
3355132957
package com.example.petlover.presentation.ui.components import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.size 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.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @Composable fun TextBox(title: String, descripton: String?) { Column { Text( text = title, fontSize = 20.sp ) Spacer(modifier = Modifier.size(8.dp)) descripton?.let { Text( text = it, fontSize = 16.sp, color = Color.DarkGray ) } } } @Preview(showBackground = true) @Composable fun TextBoxPreview() { TextBox( "Bem vindo, PetLover!", "Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum" ) }
PetLover/app/src/main/java/com/example/petlover/presentation/ui/components/TextBox.kt
3062547555
package com.example.petlover.presentation.ui.components import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.petlover.R @Composable fun TopBar(value: String){ Row( modifier = Modifier .fillMaxWidth() .padding(20.dp), verticalAlignment = Alignment.CenterVertically ) { Text( text = value, color = Color.Black, fontWeight = FontWeight.Medium, fontSize = 24.sp ) Spacer(modifier = Modifier.weight(1f)) Image( modifier = Modifier.size(80.dp), painter = painterResource(id = R.drawable.ic_launcher_foreground), contentDescription = null ) } } @Preview(showBackground = true) @Composable fun TopBarPreview(){ TopBar("Hi, there") }
PetLover/app/src/main/java/com/example/petlover/presentation/ui/components/TopBar.kt
1940280633
package com.example.petlover.presentation.ui.components import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.OutlinedTextField 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.Modifier import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.sp import com.example.petlover.R @Composable fun InputTextField( onTextChange: (name: String) -> Unit ){ val localFocusManager = LocalFocusManager.current var currentValue by remember{ mutableStateOf("") } Column( modifier = Modifier.fillMaxWidth() ) { OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = currentValue, onValueChange = { currentValue = it onTextChange(it) }, placeholder = { Text( text = stringResource(R.string.input_text_field_component_enter_your_name), fontSize = 18.sp ) }, keyboardOptions = KeyboardOptions( imeAction = ImeAction.Done ), keyboardActions = KeyboardActions { localFocusManager.clearFocus() } ) } } @Preview(showBackground = true) @Composable fun InputTextFieldPreview(){ // InputTextField() }
PetLover/app/src/main/java/com/example/petlover/presentation/ui/components/InputTextField.kt
1397499068
package com.example.petlover.presentation.ui.components 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.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @Composable fun ButtonComponent(goToDetailsScreen: () -> Unit) { Button(modifier = Modifier .padding(16.dp) .fillMaxWidth(), onClick = { /*TODO*/ } ) { Text(text = "Go to Details") } } @Preview(showBackground = true) @Composable fun ButtonComponentPreview() { ButtonComponent({}) }
PetLover/app/src/main/java/com/example/petlover/presentation/ui/components/ButtonComponent.kt
4279884887
package com.example.petlover.presentation.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)
PetLover/app/src/main/java/com/example/petlover/presentation/ui/theme/Color.kt
1692246380
package com.example.petlover.presentation.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 PetLoverTheme( 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 ) }
PetLover/app/src/main/java/com/example/petlover/presentation/ui/theme/Theme.kt
932242334
package com.example.petlover.presentation.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 ) */ )
PetLover/app/src/main/java/com/example/petlover/presentation/ui/theme/Type.kt
2703877237
package com.example.petlover.presentation.ui.view import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.petlover.presentation.ui.components.TextBox import com.example.petlover.presentation.ui.components.TopBar @Composable fun DetailsScreen(userName: String?, petChoosen: String?) { Surface(modifier = Modifier.fillMaxSize()) { Column( modifier = Modifier .fillMaxSize() .padding(18.dp) ) { TopBar(value = "Welcome $userName") TextBox(title = "Thank you for sharing your data!", descripton = null) Spacer(modifier = Modifier.size(60.dp)) } } } @Preview(showBackground = true) @Composable fun DetailsScreenPreview() { DetailsScreen(userName = "username", petChoosen = "petchoosen") }
PetLover/app/src/main/java/com/example/petlover/presentation/ui/view/DetailsView.kt
3712687176
package com.example.petlover.presentation.ui.view import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.petlover.R import com.example.petlover.presentation.ui.UserInputViewModel import com.example.petlover.presentation.ui.components.AnimalCard import com.example.petlover.presentation.ui.components.ButtonComponent import com.example.petlover.presentation.ui.components.InputTextField import com.example.petlover.presentation.ui.components.TextBox import com.example.petlover.presentation.ui.components.TopBar import com.example.petlover.presentation.ui.data.UserDataUiEvents @Composable fun UserInputScreen( viewModel: UserInputViewModel, showDetailsScreen: (valuePair: Pair<String, String>) -> Unit ) { Surface( modifier = Modifier.fillMaxSize() ) { Column( modifier = Modifier .fillMaxSize() .padding(18.dp) ) { TopBar(value = "Hi, there") TextBox( title = "Bem vindo, PetLover!", descripton = "Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum" ) Spacer(modifier = Modifier.size(60.dp)) InputTextField(onTextChange = { viewModel.onEvent( UserDataUiEvents.UserNameInputed(it) ) }) Spacer(modifier = Modifier.size(60.dp)) Text(text = "What do you want?") Row( modifier = Modifier .fillMaxWidth() .padding(vertical = 8.dp) .align(Alignment.CenterHorizontally) ) { AnimalCard( imagePath = R.drawable.ic_launcher_foreground, animalSelected = { viewModel.onEvent( UserDataUiEvents.AnimalSelected(it) ) }, selected = viewModel.uiState.value.petChoosen == "Cat" ) AnimalCard( imagePath = R.drawable.ic_launcher_background, animalSelected = { viewModel.onEvent( UserDataUiEvents.AnimalSelected(it) ) }, selected = viewModel.uiState.value.petChoosen == "Dog" ) } Spacer(modifier = Modifier.weight(1f)) if (viewModel.isValidState()) { ButtonComponent( goToDetailsScreen = { showDetailsScreen( Pair( viewModel.uiState.value.nameEntered, viewModel.uiState.value.petChoosen ) ) } ) } } } } @Preview(showBackground = true) @Composable fun UserInputScreenPreview() { UserInputScreen(UserInputViewModel(),{}) }
PetLover/app/src/main/java/com/example/petlover/presentation/ui/view/UserInputView.kt
1947048717
package com.example.petlover.presentation.ui.data sealed class UserDataUiEvents{ data class UserNameInputed(val name: String) : UserDataUiEvents() data class AnimalSelected(val animalValue: String) : UserDataUiEvents() }
PetLover/app/src/main/java/com/example/petlover/presentation/ui/data/UserDataUiEvents.kt
1571362007
package com.example.petlover.presentation.ui.data data class UserInputScreenState( var nameEntered: String = "", var petChoosen: String = "" )
PetLover/app/src/main/java/com/example/petlover/presentation/ui/data/UserInputScreenState.kt
3413594798
package com.example.petlover.presentation.ui import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import com.example.petlover.presentation.ui.data.UserDataUiEvents import com.example.petlover.presentation.ui.data.UserInputScreenState class UserInputViewModel : ViewModel() { var uiState = mutableStateOf(UserInputScreenState()) fun onEvent(event: UserDataUiEvents){ when(event){ is UserDataUiEvents.UserNameInputed -> { uiState.value = uiState.value.copy(nameEntered = event.name) } is UserDataUiEvents.AnimalSelected -> { uiState.value = uiState.value.copy(petChoosen = event.animalValue) } } } fun isValidState(): Boolean { return uiState.value.nameEntered.isNotEmpty() && uiState.value.petChoosen.isNotEmpty() } }
PetLover/app/src/main/java/com/example/petlover/presentation/ui/UserInputViewModel.kt
3348107067
package com.example.petlover.presentation.shared import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.runtime.Composable import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import com.example.petlover.presentation.ui.theme.PetLoverTheme import com.example.petlover.navigation.PetLoverNavigationGraph class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) installSplashScreen() setContent { PetLoverTheme { PetLoverApp() } } } @Composable fun PetLoverApp() { PetLoverNavigationGraph() } }
PetLover/app/src/main/java/com/example/petlover/presentation/shared/MainActivity.kt
69694235
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.codelab.basiclayouts.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Shapes import androidx.compose.ui.unit.dp val shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(12.dp) )
MovilNavito/app/src/main/java/com/codelab/basiclayouts/ui/theme/Shape.kt
4073031578
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.codelab.basiclayouts.ui.theme import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF6B5C4D) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFFF4DFCD) val md_theme_light_onPrimaryContainer = Color(0xFF241A0E) val md_theme_light_secondary = Color(0xFF635D59) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFEAE1DB) val md_theme_light_onSecondaryContainer = Color(0xFF1F1B17) val md_theme_light_tertiary = Color(0xFF5E5F58) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFE3E3DA) val md_theme_light_onTertiaryContainer = Color(0xFF1B1C17) val md_theme_light_error = Color(0xFFBA1A1A) val md_theme_light_errorContainer = Color(0xFFFFDAD6) val md_theme_light_onError = Color(0xFFFFFFFF) val md_theme_light_onErrorContainer = Color(0xFF410002) val md_theme_light_background = Color(0xFFF5F0EE) val md_theme_light_onBackground = Color(0xFF1D1B1A) val md_theme_light_surface = Color(0xFFFFFBFF) val md_theme_light_onSurface = Color(0xFF1D1B1A) val md_theme_light_surfaceVariant = Color(0xFFE7E1DE) val md_theme_light_onSurfaceVariant = Color(0xFF494644) val md_theme_light_outline = Color(0xFF7A7674) val md_theme_light_inverseOnSurface = Color(0xFFF5F0EE) val md_theme_dark_primary = Color(0xFFD7C3B1) val md_theme_dark_onPrimary = Color(0xFF3A2E22) val md_theme_dark_primaryContainer = Color(0xFF524437) val md_theme_dark_onPrimaryContainer = Color(0xFFF4DFCD) val md_theme_dark_secondary = Color(0xFFCDC5BF) val md_theme_dark_onSecondary = Color(0xFF34302C) val md_theme_dark_secondaryContainer = Color(0xFF4B4642) val md_theme_dark_onSecondaryContainer = Color(0xFFEAE1DB) val md_theme_dark_tertiary = Color(0xFFC7C7BE) val md_theme_dark_onTertiary = Color(0xFF30312B) val md_theme_dark_tertiaryContainer = Color(0xFF464741) val md_theme_dark_onTertiaryContainer = Color(0xFFE3E3DA) val md_theme_dark_error = Color(0xFFFFB4AB) val md_theme_dark_errorContainer = Color(0xFF93000A) val md_theme_dark_onError = Color(0xFF690005) val md_theme_dark_onErrorContainer = Color(0xFFFFB4AB) val md_theme_dark_background = Color(0xFF32302F) val md_theme_dark_onBackground = Color(0xFFE6E1E0) val md_theme_dark_surface = Color(0xFF1D1B1A) val md_theme_dark_onSurface = Color(0xFFE6E1E0) val md_theme_dark_surfaceVariant = Color(0xFF494644) val md_theme_dark_onSurfaceVariant = Color(0xFFE6E1E0) val md_theme_dark_outline = Color(0xFF94908D)
MovilNavito/app/src/main/java/com/codelab/basiclayouts/ui/theme/Color.kt
3199454695
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.codelab.basiclayouts.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable private val LightColors = lightColorScheme( primary = md_theme_light_primary, onPrimary = md_theme_light_onPrimary, primaryContainer = md_theme_light_primaryContainer, onPrimaryContainer = md_theme_light_onPrimaryContainer, secondary = md_theme_light_secondary, onSecondary = md_theme_light_onSecondary, secondaryContainer = md_theme_light_secondaryContainer, onSecondaryContainer = md_theme_light_onSecondaryContainer, tertiary = md_theme_light_tertiary, onTertiary = md_theme_light_onTertiary, tertiaryContainer = md_theme_light_tertiaryContainer, onTertiaryContainer = md_theme_light_onTertiaryContainer, error = md_theme_light_error, errorContainer = md_theme_light_errorContainer, onError = md_theme_light_onError, onErrorContainer = md_theme_light_onErrorContainer, background = md_theme_light_background, onBackground = md_theme_light_onBackground, surface = md_theme_light_surface, onSurface = md_theme_light_onSurface, surfaceVariant = md_theme_light_surfaceVariant, onSurfaceVariant = md_theme_light_onSurfaceVariant, outline = md_theme_light_outline ) private val DarkColors = darkColorScheme( primary = md_theme_dark_primary, onPrimary = md_theme_dark_onPrimary, primaryContainer = md_theme_dark_primaryContainer, onPrimaryContainer = md_theme_dark_onPrimaryContainer, secondary = md_theme_dark_secondary, onSecondary = md_theme_dark_onSecondary, secondaryContainer = md_theme_dark_secondaryContainer, onSecondaryContainer = md_theme_dark_onSecondaryContainer, tertiary = md_theme_dark_tertiary, onTertiary = md_theme_dark_onTertiary, tertiaryContainer = md_theme_dark_tertiaryContainer, onTertiaryContainer = md_theme_dark_onTertiaryContainer, error = md_theme_dark_error, errorContainer = md_theme_dark_errorContainer, onError = md_theme_dark_onError, onErrorContainer = md_theme_dark_onErrorContainer, background = md_theme_dark_background, onBackground = md_theme_dark_onBackground, surface = md_theme_dark_surface, onSurface = md_theme_dark_onSurface, surfaceVariant = md_theme_dark_surfaceVariant, onSurfaceVariant = md_theme_dark_onSurfaceVariant, outline = md_theme_dark_outline ) @Composable fun MySootheTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable() () -> Unit ) { val colors = if (darkTheme) { DarkColors } else { LightColors } MaterialTheme( colorScheme = colors, typography = typography, shapes = shapes, content = content ) }
MovilNavito/app/src/main/java/com/codelab/basiclayouts/ui/theme/Theme.kt
1031957268
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.codelab.basiclayouts.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.sp import com.codelab.basiclayouts.R private val fontFamilyKulim = FontFamily( listOf( Font( resId = R.font.kulim_park_regular ), Font( resId = R.font.kulim_park_light, weight = FontWeight.Light ) ) ) private val fontFamilyLato = FontFamily( listOf( Font( resId = R.font.lato_regular ), Font( resId = R.font.lato_bold, weight = FontWeight.Bold ) ) ) val typography = Typography( displayLarge = TextStyle( fontFamily = fontFamilyKulim, fontWeight = FontWeight.Light, fontSize = 57.sp, lineHeight = 64.sp, letterSpacing = (-0.25).sp ), displayMedium = TextStyle( fontFamily = fontFamilyKulim, fontSize = 45.sp, lineHeight = 52.sp ), displaySmall = TextStyle( fontFamily = fontFamilyKulim, fontSize = 36.sp, lineHeight = 44.sp ), titleMedium = TextStyle( fontFamily = fontFamilyLato, fontWeight = FontWeight(500), fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = (0.15).sp ), bodySmall = TextStyle( fontFamily = fontFamilyLato, fontSize = 12.sp, lineHeight = 16.sp, letterSpacing = (0.4).sp ), bodyMedium = TextStyle( fontFamily = fontFamilyLato, fontSize = 14.sp, lineHeight = 20.sp, letterSpacing = (0.25).sp ), bodyLarge = TextStyle( fontFamily = fontFamilyLato, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = (0.5).sp ), labelMedium = TextStyle( fontFamily = fontFamilyLato, fontWeight = FontWeight(500), fontSize = 12.sp, lineHeight = 16.sp, letterSpacing = (0.5).sp, textAlign = TextAlign.Center ), labelLarge = TextStyle( fontFamily = fontFamilyLato, fontSize = 14.sp, lineHeight = 20.sp, letterSpacing = (0.1).sp ) )
MovilNavito/app/src/main/java/com/codelab/basiclayouts/ui/theme/Type.kt
1402908547
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.codelab.basiclayouts import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.codelab.basiclayouts.ui.theme.MySootheTheme import androidx.compose.material3.TextField import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.ui.res.stringResource import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextFieldDefaults import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Search import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.ui.res.painterResource import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.Alignment import androidx.compose.foundation.layout.paddingFromBaseline import androidx.compose.foundation.layout.Row import androidx.compose.material3.Surface import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.height import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyHorizontalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.NavigationBar import androidx.compose.material3.NavigationBarItem import androidx.compose.material.icons.filled.AccountCircle import androidx.compose.material.icons.filled.Spa import androidx.compose.material3.Scaffold import androidx.compose.material3.NavigationRail import androidx.compose.material3.NavigationRailItem import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.material3.windowsizeclass.WindowSizeClass import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass class MainActivity : ComponentActivity() { @OptIn(ExperimentalMaterial3WindowSizeClassApi::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { val windowSizeClass = calculateWindowSizeClass(this) MySootheApp(windowSizeClass) } } } // Step: Search bar - Modifiers @Composable fun SearchBar( modifier: Modifier = Modifier ) { TextField( value = "", onValueChange = {}, leadingIcon = { Icon( imageVector = Icons.Default.Search, contentDescription = null ) }, colors = TextFieldDefaults.colors( unfocusedContainerColor = MaterialTheme.colorScheme.surface, focusedContainerColor = MaterialTheme.colorScheme.surface ), placeholder = { Text(stringResource(R.string.placeholder_search)) }, modifier = modifier .fillMaxWidth() .heightIn(min = 56.dp) ) } // Step: Align your body - Alignment @Composable fun AlignYourBodyElement( @DrawableRes drawable: Int, @StringRes text: Int, modifier: Modifier = Modifier ) { Column( modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally ) { Image( painter = painterResource(drawable), contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier .size(88.dp) .clip(CircleShape) ) Text( text = stringResource(text), modifier = Modifier.paddingFromBaseline(top = 24.dp, bottom = 8.dp), style = MaterialTheme.typography.bodyMedium ) } } // Step: Favorite collection card - Material Surface @Composable fun FavoriteCollectionCard( @DrawableRes drawable: Int, @StringRes text: Int, modifier: Modifier = Modifier ) { Surface( shape = MaterialTheme.shapes.medium, color = MaterialTheme.colorScheme.surfaceVariant, modifier = modifier ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.width(255.dp) ) { Image( painter = painterResource(drawable), contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.size(80.dp) ) Text( text = stringResource(text), style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(horizontal = 16.dp) ) } } } // Step: Align your body row - Arrangements @Composable fun AlignYourBodyRow( modifier: Modifier = Modifier ) { LazyRow( horizontalArrangement = Arrangement.spacedBy(8.dp), contentPadding = PaddingValues(horizontal = 16.dp), modifier = modifier ) { items(alignYourBodyData) { item -> AlignYourBodyElement(item.drawable, item.text) } } } // Step: Favorite collections grid - LazyGrid @Composable fun FavoriteCollectionsGrid( modifier: Modifier = Modifier ) { LazyHorizontalGrid( rows = GridCells.Fixed(2), contentPadding = PaddingValues(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp), modifier = modifier.height(168.dp) ) { items(favoriteCollectionsData) { item -> FavoriteCollectionCard(item.drawable, item.text, Modifier.height(80.dp)) } } } // Step: Home section - Slot APIs @Composable fun HomeSection( @StringRes title: Int, modifier: Modifier = Modifier, content: @Composable () -> Unit ) { Column(modifier) { Text( text = stringResource(title), style = MaterialTheme.typography.titleMedium, modifier = Modifier .paddingFromBaseline(top = 40.dp, bottom = 16.dp) .padding(horizontal = 16.dp) ) content() } } // Step: Home screen - Scrolling @Composable fun HomeScreen(modifier: Modifier = Modifier) { Column( modifier .verticalScroll(rememberScrollState()) ) { Spacer(Modifier.height(16.dp)) SearchBar(Modifier.padding(horizontal = 16.dp)) HomeSection(title = R.string.align_your_body) { AlignYourBodyRow() } HomeSection(title = R.string.favorite_collections) { FavoriteCollectionsGrid() } Spacer(Modifier.height(16.dp)) } } // Step: Bottom navigation - Material @Composable private fun SootheBottomNavigation(modifier: Modifier = Modifier) { NavigationBar( containerColor = MaterialTheme.colorScheme.surfaceVariant, modifier = modifier ) { NavigationBarItem( icon = { Icon( imageVector = Icons.Default.Spa, contentDescription = null ) }, label = { Text(stringResource(R.string.bottom_navigation_home)) }, selected = true, onClick = {} ) NavigationBarItem( icon = { Icon( imageVector = Icons.Default.AccountCircle, contentDescription = null ) }, label = { Text(stringResource(R.string.bottom_navigation_profile)) }, selected = false, onClick = {} ) } } // Step: MySoothe App - Scaffold @Composable fun MySootheAppPortrait() { MySootheTheme { Scaffold( bottomBar = { SootheBottomNavigation() } ) { padding -> HomeScreen(Modifier.padding(padding)) } } } // Step: Bottom navigation - Material @Composable private fun SootheNavigationRail(modifier: Modifier = Modifier) { NavigationRail( modifier = modifier.padding(start = 8.dp, end = 8.dp), containerColor = MaterialTheme.colorScheme.background, ) { Column( modifier = modifier.fillMaxHeight(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { NavigationRailItem( icon = { Icon( imageVector = Icons.Default.Spa, contentDescription = null ) }, label = { Text(stringResource(R.string.bottom_navigation_home)) }, selected = true, onClick = {} ) Spacer(modifier = Modifier.height(8.dp)) NavigationRailItem( icon = { Icon( imageVector = Icons.Default.AccountCircle, contentDescription = null ) }, label = { Text(stringResource(R.string.bottom_navigation_profile)) }, selected = false, onClick = {} ) } } } // Step: Landscape Mode @Composable fun MySootheAppLandscape() { MySootheTheme { Surface(color = MaterialTheme.colorScheme.background) { Row { SootheNavigationRail() HomeScreen() } } } } // Step: MySoothe App @Composable fun MySootheApp(windowSize: WindowSizeClass) { when (windowSize.widthSizeClass) { WindowWidthSizeClass.Compact -> { MySootheAppPortrait() } WindowWidthSizeClass.Expanded -> { MySootheAppLandscape() } } } private val alignYourBodyData = listOf( R.drawable.ab1_inversions to R.string.ab1_inversions, R.drawable.ab2_quick_yoga to R.string.ab2_quick_yoga, R.drawable.ab3_stretching to R.string.ab3_stretching, R.drawable.ab4_tabata to R.string.ab4_tabata, R.drawable.ab5_hiit to R.string.ab5_hiit, R.drawable.ab6_pre_natal_yoga to R.string.ab6_pre_natal_yoga, R.drawable.ab7_gasero to R.string.ab7_gasero ).map { DrawableStringPair(it.first, it.second) } private val favoriteCollectionsData = listOf( R.drawable.fc1_short_mantras to R.string.fc1_short_mantras, R.drawable.fc2_nature_meditations to R.string.fc2_nature_meditations, R.drawable.fc3_stress_and_anxiety to R.string.fc3_stress_and_anxiety, R.drawable.fc4_self_massage to R.string.fc4_self_massage, R.drawable.fc5_overwhelmed to R.string.fc5_overwhelmed, R.drawable.fc6_nightly_wind_down to R.string.fc6_nightly_wind_down ).map { DrawableStringPair(it.first, it.second) } private data class DrawableStringPair( @DrawableRes val drawable: Int, @StringRes val text: Int ) @Preview(showBackground = true, backgroundColor = 0xFFF5F0EE) @Composable fun SearchBarPreview() { MySootheTheme { SearchBar(Modifier.padding(8.dp)) } } @Preview(showBackground = true, backgroundColor = 0xFFF5F0EE) @Composable fun AlignYourBodyElementPreview() { MySootheTheme { AlignYourBodyElement( text = R.string.ab1_inversions, drawable = R.drawable.ab1_inversions, modifier = Modifier.padding(8.dp) ) } } @Preview(showBackground = true, backgroundColor = 0xFFF5F0EE) @Composable fun FavoriteCollectionCardPreview() { MySootheTheme { FavoriteCollectionCard( text = R.string.fc2_nature_meditations, drawable = R.drawable.fc2_nature_meditations, modifier = Modifier.padding(8.dp) ) } } @Preview(showBackground = true, backgroundColor = 0xFFF5F0EE) @Composable fun FavoriteCollectionsGridPreview() { MySootheTheme { FavoriteCollectionsGrid() } } @Preview(showBackground = true, backgroundColor = 0xFFF5F0EE) @Composable fun AlignYourBodyRowPreview() { MySootheTheme { AlignYourBodyRow() } } @Preview(showBackground = true, backgroundColor = 0xFFF5F0EE) @Composable fun HomeSectionPreview() { MySootheTheme { HomeSection(R.string.align_your_body) { AlignYourBodyRow() } } } @Preview(showBackground = true, backgroundColor = 0xFFF5F0EE, heightDp = 180) @Composable fun ScreenContentPreview() { MySootheTheme { HomeScreen() } } @Preview(showBackground = true, backgroundColor = 0xFFF5F0EE) @Composable fun BottomNavigationPreview() { MySootheTheme { SootheBottomNavigation(Modifier.padding(top = 24.dp)) } } @Preview(showBackground = true, backgroundColor = 0xFFF5F0EE) @Composable fun NavigationRailPreview() { MySootheTheme { SootheNavigationRail() } } @Preview(widthDp = 360, heightDp = 640) @Composable fun MySoothePortraitPreview() { MySootheAppPortrait() } @Preview(widthDp = 640, heightDp = 360) @Composable fun MySootheLandscapePreview() { MySootheAppLandscape() }
MovilNavito/app/src/main/java/com/codelab/basiclayouts/MainActivity.kt
2662613131
/* * Copyright $YEAR The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
MovilNavito/spotless/copyright.kt
2813624007
fun main() { while (true) { val a = readLine()!!.toInt() val b = readLine()!!.toInt() val x = readLine()!! if (x == "+") { println(a + b) } if (x == "-") { println(a - b) } if (x == "*") { println(a * b) } if (x == "/") { println(a / b) } println("Нажмите 1 чтобы выйти") val z = readLine()!! if (z == "1") { print("Пока") break } else{ continue } }}
Kotlin_Kolkulator/src/123.kt
4237529622
package me.dio.credit.application.system import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class CreditApplicationSystemApplicationTests { @Test fun contextLoads() { } }
CreditApplicationSystem/src/test/kotlin/me/dio/credit/application/system/CreditApplicationSystemApplicationTests.kt
1010847126
package me.dio.credit.application.system.repository import me.dio.credit.application.system.entity.Address import me.dio.credit.application.system.entity.Credit import me.dio.credit.application.system.entity.Customer import org.assertj.core.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager import org.springframework.test.context.ActiveProfiles import java.math.BigDecimal import java.time.LocalDate import java.time.Month import java.util.* @ActiveProfiles("test") @DataJpaTest @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) class CreditRepositoryTest { @Autowired lateinit var creditRepository: CreditRepository @Autowired lateinit var testEntityManager: TestEntityManager private lateinit var customer: Customer private lateinit var credit1: Credit private lateinit var credit2: Credit @BeforeEach fun setup() { customer = testEntityManager.merge(buildCustomer()) credit1 = testEntityManager.persist(buildCredit(customer = customer)) credit2 = testEntityManager.persist(buildCredit(customer = customer)) } @Test fun `should find credit code`() { //given val creditCode1 = UUID.fromString("aa547c0f-9a6a-451f-8c89-afddce916a29") val creditCode2 = UUID.fromString("49f740be-46a7-449b-84e7-ff5b7986d7ef") credit1.creditCode = creditCode1 credit2.creditCode = creditCode2 //when val fakeCredit1: Credit = creditRepository.findByCreditCode(creditCode1)!! val fakeCredit2: Credit = creditRepository.findByCreditCode(creditCode2)!! //then Assertions.assertThat(fakeCredit1).isNotNull Assertions.assertThat(fakeCredit2).isNotNull Assertions.assertThat(fakeCredit1).isSameAs(credit1) Assertions.assertThat(fakeCredit2).isSameAs(credit2) } @Test fun `should find all credits by customer id`() { //given val customerId: Long = 1L //when val creditList: List<Credit> = creditRepository.findAllByCustomerId(customerId) //then Assertions.assertThat(creditList).isNotEmpty Assertions.assertThat(creditList.size).isEqualTo(2) Assertions.assertThat(creditList).contains(credit1, credit2) } private fun buildCredit( creditValue: BigDecimal = BigDecimal.valueOf(500.0), dayFirstInstallment: LocalDate = LocalDate.of(2024, Month.FEBRUARY, 5), numberOfInstallments: Int = 5, customer: Customer ): Credit = Credit( creditValue = creditValue, dayFirstInstallment = dayFirstInstallment, numberOfInstallments = numberOfInstallments, customer = customer ) private fun buildCustomer( firstName: String = "Lucas", lastName: String = "Tressoldi", cpf: String = "431.194.775-59", email: String = "[email protected]", password: String = "123", zipCode: String = "13844-023", street: String = "Rua do Lucas", income: BigDecimal = BigDecimal.valueOf(1000.0), id: Long = 1L ) = Customer( firstName = firstName, lastName = lastName, cpf = cpf, email = email, password = password, address = Address( zipCode = zipCode, street = street ), income = income, id = id ) }
CreditApplicationSystem/src/test/kotlin/me/dio/credit/application/system/repository/CreditRepositoryTest.kt
696750062
package me.dio.credit.application.system.controller import com.fasterxml.jackson.databind.ObjectMapper import me.dio.credit.application.system.dto.CustomerDto import me.dio.credit.application.system.dto.CustomerUpdateDto import me.dio.credit.application.system.entity.Customer import me.dio.credit.application.system.repository.CustomerRepository import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.http.MediaType import org.springframework.test.context.ActiveProfiles import org.springframework.test.context.ContextConfiguration import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders import org.springframework.test.web.servlet.result.MockMvcResultHandlers import org.springframework.test.web.servlet.result.MockMvcResultMatchers import java.math.BigDecimal import java.util.Random @SpringBootTest @ActiveProfiles("test") @AutoConfigureMockMvc @ContextConfiguration class CustomerResourceTest { @Autowired private lateinit var customerRepository: CustomerRepository @Autowired private lateinit var mockMvc: MockMvc @Autowired private lateinit var objectMapper: ObjectMapper companion object { const val URL: String = "/api/customers" } @BeforeEach fun setup() = customerRepository.deleteAll() @AfterEach fun tearDown() = customerRepository.deleteAll() @Test fun `should create customer and return 201 status`() { //given val customerDto: CustomerDto = buildCustomerDto() val valueAsString: String = objectMapper.writeValueAsString(customerDto) //when //then mockMvc.perform( MockMvcRequestBuilders.post(URL) .contentType(MediaType.APPLICATION_JSON) .content(valueAsString) ).andExpect(MockMvcResultMatchers.status().isCreated).andDo(MockMvcResultHandlers.print()) } @Test fun `should not have a customer with same CPF and return 409 status`() { //given customerRepository.save(buildCustomerDto().toEntity()) val customerDto: CustomerDto = buildCustomerDto() val valueAsString: String = objectMapper.writeValueAsString(customerDto) //when //then mockMvc.perform( MockMvcRequestBuilders.post(URL).contentType(MediaType.APPLICATION_JSON) .content(valueAsString) ).andExpect(MockMvcResultMatchers.status().isConflict).andDo(MockMvcResultHandlers.print()) } @Test fun `should not have a customer with firstName empty and return 409 status`() { //given val customerDto: CustomerDto = buildCustomerDto(firstName = "") val valueAsString: String = objectMapper.writeValueAsString(customerDto) //when //then mockMvc.perform( MockMvcRequestBuilders.post(URL).content(valueAsString) .contentType(MediaType.APPLICATION_JSON) ).andExpect(MockMvcResultMatchers.status().isBadRequest) .andDo(MockMvcResultHandlers.print()) } @Test fun `should find customer by id and return 200 status`() { //given val customer: Customer = customerRepository.save(buildCustomerDto().toEntity()) //when //then mockMvc.perform( MockMvcRequestBuilders.get("$URL/${customer.id}") .accept(MediaType.APPLICATION_JSON) ).andExpect(MockMvcResultMatchers.status().isOk).andDo(MockMvcResultHandlers.print()) } @Test fun `should not find customer with invalid id and return 400 status`() { //given val invalidId: Long = 2L //when //then mockMvc.perform(MockMvcRequestBuilders.get("$URL/$invalidId").accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isBadRequest).andDo(MockMvcResultHandlers.print()) } @Test fun `should delete customer by id`() { //given val customer: Customer = customerRepository.save(buildCustomerDto().toEntity()) //when //then mockMvc.perform( MockMvcRequestBuilders.delete("$URL/${customer.id}") .accept(MediaType.APPLICATION_JSON) ).andExpect(MockMvcResultMatchers.status().isNoContent).andDo(MockMvcResultHandlers.print()) } @Test fun `should not delete customer by id and return 400 status`() { //given val invalidId: Long = Random().nextLong() //when //then mockMvc.perform( MockMvcRequestBuilders.delete("$URL/${invalidId}") .accept(MediaType.APPLICATION_JSON) ).andExpect(MockMvcResultMatchers.status().isBadRequest).andDo(MockMvcResultHandlers.print()) } @Test fun `should update a customer and return 200 status`() { //given val customer: Customer = customerRepository.save(buildCustomerDto().toEntity()) val customerUpdateDto: CustomerUpdateDto = buildCustomerUpdateDto() val valueAsString: String = objectMapper.writeValueAsString(customerUpdateDto) //when //then mockMvc.perform( MockMvcRequestBuilders.patch("$URL?customerId=${customer.id}").contentType(MediaType.APPLICATION_JSON) .content(valueAsString) ).andExpect(MockMvcResultMatchers.status().isOk).andDo(MockMvcResultHandlers.print()) } @Test fun `should not update a customer with invalid id and return 400 status`() { //given val invalidId: Long = Random().nextLong() val customerUpdateDto: CustomerUpdateDto = buildCustomerUpdateDto() val valueAsString: String = objectMapper.writeValueAsString(customerUpdateDto) //when //then mockMvc.perform( MockMvcRequestBuilders.patch("$URL?customerId=${invalidId}").contentType(MediaType.APPLICATION_JSON) .content(valueAsString) ).andExpect(MockMvcResultMatchers.status().isBadRequest).andDo(MockMvcResultHandlers.print()) } private fun buildCustomerDto( firstName: String = "Lucas", lastName: String = "Tressoldi", cpf: String = "431.194.775-59", email: String = "[email protected]", income: BigDecimal = BigDecimal.valueOf(1000.0), password: String = "123", zipCode: String = "13844-023", street: String = "Rua do Lucas" ) = CustomerDto( firstName = firstName, lastName = lastName, cpf = cpf, email = email, income = income, password = password, zipCode = zipCode, street = street ) private fun buildCustomerUpdateDto( firstName: String = "Lucas", lastName: String = "Tressoldi", income: BigDecimal = BigDecimal.valueOf(5000.0), zipCode: String = "13844-023", street: String = "Rua do Lucas" ): CustomerUpdateDto = CustomerUpdateDto( firstName = firstName, lastName = lastName, income = income, zipCode = zipCode, street = street ) }
CreditApplicationSystem/src/test/kotlin/me/dio/credit/application/system/controller/CustomerResourceTest.kt
3250886976
package me.dio.credit.application.system.service import io.mockk.every import io.mockk.impl.annotations.InjectMockKs import io.mockk.impl.annotations.MockK import io.mockk.junit5.MockKExtension import io.mockk.just import io.mockk.runs import io.mockk.verify import me.dio.credit.application.system.entity.Address import me.dio.credit.application.system.entity.Customer import me.dio.credit.application.system.exception.BusinessException import me.dio.credit.application.system.repository.CustomerRepository import me.dio.credit.application.system.service.impl.CustomerService import org.assertj.core.api.Assertions import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.test.context.ActiveProfiles import java.math.BigDecimal import java.util.Optional import java.util.Random @ActiveProfiles("test") @ExtendWith(MockKExtension::class) class CustomerServiceTest { @MockK lateinit var customerRepository: CustomerRepository @InjectMockKs lateinit var customerService: CustomerService @Test fun `should create customer`(){ //given val fakeCustomer: Customer = buildCustomer() every { customerRepository.save(any()) } returns fakeCustomer //when val actual: Customer = customerService.save(fakeCustomer) //then Assertions.assertThat(actual).isNotNull Assertions.assertThat(actual).isSameAs(fakeCustomer) verify(exactly = 1) { customerRepository.save(fakeCustomer) } } @Test fun `should find customer by id`() { //given val fakeId: Long = Random().nextLong() val fakeCustomer: Customer = buildCustomer(id = fakeId) every { customerRepository.findById(fakeId) } returns Optional.of(fakeCustomer) //when val actual: Customer = customerService.findById(fakeId) //then Assertions.assertThat(actual).isExactlyInstanceOf(Customer::class.java) Assertions.assertThat(actual).isNotNull Assertions.assertThat(actual).isSameAs(fakeCustomer) verify(exactly = 1) { customerRepository.findById(fakeId) } } @Test fun `should not find customer by invalid id and throw BusinessException()`() { //given val fakeId: Long = Random().nextLong() every { customerRepository.findById(fakeId) } returns Optional.empty() //when //then Assertions.assertThatExceptionOfType(BusinessException::class.java) .isThrownBy { customerService.findById(fakeId) } .withMessage("Id $fakeId not found.") verify(exactly = 1) { customerRepository.findById(fakeId) } } @Test fun `should delete customer by id`() { //given val fakeId: Long = Random().nextLong() val fakeCustomer: Customer = buildCustomer(id = fakeId) every { customerRepository.findById(fakeId) } returns Optional.of(fakeCustomer) every { customerRepository.delete(fakeCustomer) } just runs //when customerService.delete(fakeId) //then verify(exactly = 1) { customerRepository.findById(fakeId) } verify(exactly = 1) { customerRepository.delete(fakeCustomer) } } private fun buildCustomer( firstName: String = "Lucas", lastName: String = "Tressoldi", cpf: String = "431.194.775-59", email: String = "[email protected]", password: String = "123", zipCode: String = "13844-023", street: String = "Rua do Lucas", income: BigDecimal = BigDecimal.valueOf(1000.0), id: Long = 1L ) = Customer( firstName = firstName, lastName = lastName, cpf = cpf, email = email, password = password, address = Address( zipCode = zipCode, street = street ), income = income, id = id ) }
CreditApplicationSystem/src/test/kotlin/me/dio/credit/application/system/service/CustomerServiceTest.kt
3308930399
package me.dio.credit.application.system.dto import jakarta.validation.constraints.Future import jakarta.validation.constraints.NotNull import me.dio.credit.application.system.entity.Credit import me.dio.credit.application.system.entity.Customer import java.math.BigDecimal import java.time.LocalDate data class CreditDto( @field:NotNull(message = "Invalid input") val creditValue: BigDecimal, @field:Future val dayFirstInstallment: LocalDate, @field:NotNull(message = "Invalid input") val numberOfInstallments: Int, @field:NotNull(message = "Invalid input") val customerId: Long ) { fun toEntity(): Credit = Credit( creditValue = this.creditValue, dayFirstInstallment = this.dayFirstInstallment, numberOfInstallments = this.numberOfInstallments, customer = Customer(id = this.customerId) ) }
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/dto/CreditDto.kt
2844286333
package me.dio.credit.application.system.dto import jakarta.validation.constraints.Email import jakarta.validation.constraints.NotEmpty import jakarta.validation.constraints.NotNull import me.dio.credit.application.system.entity.Address import me.dio.credit.application.system.entity.Customer import org.hibernate.validator.constraints.br.CPF import java.math.BigDecimal data class CustomerDto( @field:NotEmpty(message = "Invalid input") val firstName: String, @field:NotEmpty(message = "Invalid input") val lastName: String, @field:NotEmpty(message = "Invalid input") @field:CPF(message = "Invalid CPF") val cpf: String, @field:NotNull(message = "Invalid input") val income: BigDecimal, @field:NotEmpty(message = "Invalid input") @field:Email(message = "Invalid email") val email: String, @field:NotEmpty(message = "Invalid input") val password: String, @field:NotEmpty(message = "Invalid input") val zipCode: String, @field:NotEmpty(message = "Invalid input") val street: String ) { fun toEntity(): Customer = Customer( firstName = this.firstName, lastName = this.lastName, cpf = this.cpf, income = this.income, email = this.email, password = this.password, address = Address(zipCode = this.zipCode, street = this.street) ) }
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/dto/CustomerDto.kt
1388614439
package me.dio.credit.application.system.dto import me.dio.credit.application.system.entity.Credit import me.dio.credit.application.system.enummeration.Status import java.math.BigDecimal import java.util.UUID data class CreditView( val creditCode: UUID, val creditValue: BigDecimal, val numberOfInstallments: Int, val status: Status, val emailCustomer: String?, val incomeCustomer: BigDecimal? ) { constructor(credit: Credit) : this( creditCode = credit.creditCode, creditValue = credit.creditValue, numberOfInstallments = credit.numberOfInstallments, status = credit.status, emailCustomer = credit.customer?.email, incomeCustomer = credit.customer?.income ) }
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/dto/CreditView.kt
2922217574
package me.dio.credit.application.system.dto import jakarta.validation.constraints.NotEmpty import jakarta.validation.constraints.NotNull import me.dio.credit.application.system.entity.Customer import java.math.BigDecimal data class CustomerUpdateDto( @field:NotEmpty(message = "Invalid input") val firstName: String, @field:NotEmpty(message = "Invalid input") val lastName: String, @field:NotNull(message = "Invalid input") val income: BigDecimal, @field:NotEmpty(message = "Invalid input") val zipCode: String, @field:NotEmpty(message = "Invalid input") val street: String ) { fun toEntity(customer: Customer): Customer { customer.firstName = this.firstName customer.lastName = this.lastName customer.income = this.income customer.address.zipCode = this.zipCode customer.address.street = this.street return customer } }
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/dto/CustomerUpdateDto.kt
507126925
package me.dio.credit.application.system.dto import me.dio.credit.application.system.entity.Credit import java.math.BigDecimal import java.util.UUID data class CreditViewList( val creditCode: UUID, val creditValue: BigDecimal, val numberOfInstallments: Int ) { constructor(credit: Credit) : this( creditCode = credit.creditCode, creditValue = credit.creditValue, numberOfInstallments = credit.numberOfInstallments ) }
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/dto/CreditViewList.kt
2583717214
package me.dio.credit.application.system.dto import me.dio.credit.application.system.entity.Customer import java.math.BigDecimal data class CustomerView( val firstName: String, val lastName: String, val cpf: String, val income: BigDecimal, val email: String, val zipCode: String, val street: String, val id: Long? ) { constructor(customer: Customer): this ( firstName = customer.firstName, lastName = customer.lastName, cpf = customer.cpf, income = customer.income, email = customer.email, zipCode = customer.address.zipCode, street = customer.address.street, id = customer.id ) }
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/dto/CustomerView.kt
2856124615
package me.dio.credit.application.system.configuration import org.springdoc.core.models.GroupedOpenApi import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class Swagger3Config { @Bean fun publicApi(): GroupedOpenApi? { return GroupedOpenApi.builder().group("springcreditapplicationsystem-public") .pathsToMatch("/api/customers/**", "/api/credits/**").build() } }
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/configuration/Swagger3Config.kt
3756490166
package me.dio.credit.application.system.repository import me.dio.credit.application.system.entity.Credit import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.jpa.repository.Query import org.springframework.stereotype.Repository import java.util.UUID @Repository interface CreditRepository: JpaRepository<Credit, Long> { fun findByCreditCode(creditCode: UUID): Credit? @Query(value = "SELECT * FROM CREDIT WHERE CUSTOMER_ID = ?1", nativeQuery = true) fun findAllByCustomerId(customerId: Long): List<Credit> }
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/repository/CreditRepository.kt
4028667871
package me.dio.credit.application.system.repository import me.dio.credit.application.system.entity.Customer import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository @Repository interface CustomerRepository: JpaRepository<Customer, Long>
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/repository/CustomerRepository.kt
2917125201
package me.dio.credit.application.system.entity import jakarta.persistence.* import me.dio.credit.application.system.enummeration.Status import java.math.BigDecimal import java.time.LocalDate import java.util.UUID @Entity data class Credit( @Column(nullable = false, unique = true) var creditCode: UUID = UUID.randomUUID(), @Column(nullable = false) val creditValue: BigDecimal = BigDecimal.ZERO, @Column(nullable = false) val dayFirstInstallment: LocalDate, @Column(nullable = false) val numberOfInstallments: Int = 0, @Enumerated val status: Status = Status.IN_PROGRESS, @ManyToOne var customer: Customer? = null, @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long? = null )
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/entity/Credit.kt
1186588665
package me.dio.credit.application.system.entity import jakarta.persistence.* import java.math.BigDecimal @Entity data class Customer( @Column(nullable = false) var firstName: String = "", @Column(nullable = false) var lastName: String = "", @Column(nullable = false, unique = true) var email: String = "", @Column(nullable = false, unique = true) var cpf: String = "", @Column(nullable = false) var income: BigDecimal = BigDecimal.ZERO, @Column(nullable = false) var password: String = "", @Column(nullable = false) @Embedded var address: Address = Address(), @Column(nullable = false) @OneToMany(fetch = FetchType.LAZY, cascade = [CascadeType.REMOVE, CascadeType.PERSIST], mappedBy = "customer") var credits: List<Credit> = mutableListOf(), @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long? = null )
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/entity/Customer.kt
1123135062
package me.dio.credit.application.system.entity import jakarta.persistence.Column import jakarta.persistence.Embeddable @Embeddable data class Address( @Column(nullable = false) var zipCode: String = "", @Column(nullable = false) var street: String = "" )
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/entity/Address.kt
4051917962
package me.dio.credit.application.system.controller import jakarta.validation.Valid import me.dio.credit.application.system.dto.CustomerDto import me.dio.credit.application.system.dto.CustomerUpdateDto import me.dio.credit.application.system.dto.CustomerView import me.dio.credit.application.system.entity.Customer import me.dio.credit.application.system.service.impl.CustomerService import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PatchMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("/api/customers") class CustomerResource(private val customerService: CustomerService) { @PostMapping fun saveCustomer(@RequestBody @Valid customerDto: CustomerDto): ResponseEntity<String> { val savedCustomer = this.customerService.save(customerDto.toEntity()) return ResponseEntity.status(HttpStatus.CREATED).body("Customer ${savedCustomer.email} saved!") } @GetMapping("/{id}") fun findById(@PathVariable id: Long): ResponseEntity<CustomerView> { val customer: Customer = this.customerService.findById(id) return ResponseEntity.status(HttpStatus.OK).body(CustomerView(customer)) } @DeleteMapping("/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) fun delete(@PathVariable id: Long) = this.customerService.delete(id) @PatchMapping fun updateCustomer( @RequestParam(value = "customerId") id: Long, @RequestBody @Valid customerUpdateDto: CustomerUpdateDto ): ResponseEntity<CustomerView> { val customer: Customer = this.customerService.findById(id) val customerToUpdate = customerUpdateDto.toEntity(customer) val customerUpdated = this.customerService.save(customerToUpdate) return ResponseEntity.status(HttpStatus.OK).body(CustomerView(customerUpdated)) } }
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/controller/CustomerResource.kt
3448832263
package me.dio.credit.application.system.controller import jakarta.validation.Valid import me.dio.credit.application.system.dto.CreditDto import me.dio.credit.application.system.dto.CreditView import me.dio.credit.application.system.dto.CreditViewList import me.dio.credit.application.system.entity.Credit import me.dio.credit.application.system.service.impl.CreditService import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import java.util.UUID import java.util.stream.Collectors @RestController @RequestMapping("/api/credits") class CreditResource( private val creditService: CreditService ) { @PostMapping fun saveCredit(@RequestBody @Valid creditDto: CreditDto): ResponseEntity<String> { val credit = this.creditService.save(creditDto.toEntity()) return ResponseEntity.status(HttpStatus.CREATED) .body("Credit ${credit.creditCode} - Customer ${credit.customer?.firstName} saved!") } @GetMapping fun findAllByCustomerId(@RequestParam(value = "customerId") customerId: Long): ResponseEntity<List<CreditViewList>> { val creditViewList: List<CreditViewList> = this.creditService.findAllByCustomer(customerId).stream() .map { credit: Credit -> CreditViewList(credit) }.collect(Collectors.toList()) return ResponseEntity.status(HttpStatus.OK).body(creditViewList) } @GetMapping("/{creditCode}") fun findByCreditCode( @RequestParam(value = "customerId") customerId: Long, @PathVariable creditCode: UUID ): ResponseEntity<CreditView> { val credit: Credit = this.creditService.findByCreditCode(customerId, creditCode) return ResponseEntity.status(HttpStatus.OK).body(CreditView(credit)) } }
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/controller/CreditResource.kt
3245051678
package me.dio.credit.application.system.enummeration enum class Status { IN_PROGRESS, APPROVED, REJECTED }
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/enummeration/Status.kt
2973033076
package me.dio.credit.application.system.service.impl import me.dio.credit.application.system.entity.Customer import me.dio.credit.application.system.exception.BusinessException import me.dio.credit.application.system.repository.CustomerRepository import me.dio.credit.application.system.service.ICustomerService import org.springframework.stereotype.Service @Service class CustomerService(private val customerRepository: CustomerRepository) : ICustomerService { override fun save(customer: Customer): Customer = this.customerRepository.save(customer) override fun findById(id: Long): Customer = this.customerRepository.findById(id).orElseThrow { throw BusinessException("Id $id not found.") } override fun delete(id: Long) { val customer: Customer = this.findById(id) this.customerRepository.delete(customer) } }
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/service/impl/CustomerService.kt
2820511469
package me.dio.credit.application.system.service.impl import me.dio.credit.application.system.entity.Credit import me.dio.credit.application.system.exception.BusinessException import me.dio.credit.application.system.repository.CreditRepository import me.dio.credit.application.system.service.ICreditService import org.springframework.stereotype.Service import java.util.* @Service class CreditService( private val creditRepository: CreditRepository, private val customerService: CustomerService ) : ICreditService { override fun save(credit: Credit): Credit { credit.apply { customer = customerService.findById(credit.customer?.id!!) } return this.creditRepository.save(credit) } override fun findAllByCustomer(customerId: Long): List<Credit> = this.creditRepository.findAllByCustomerId(customerId) override fun findByCreditCode(customerId: Long, creditCode: UUID): Credit { val credit: Credit = (this.creditRepository.findByCreditCode(creditCode) ?: throw BusinessException("CreditCode $creditCode not found.")) return if (credit.customer?.id == customerId) credit else throw IllegalArgumentException( "Something wrong. Please, contact admin." ) } }
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/service/impl/CreditService.kt
4187476571
package me.dio.credit.application.system.service import me.dio.credit.application.system.entity.Customer interface ICustomerService { fun save(customer: Customer): Customer fun findById(id: Long): Customer fun delete(id: Long) }
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/service/ICustomerService.kt
3328967271
package me.dio.credit.application.system.service import me.dio.credit.application.system.entity.Credit import java.util.* interface ICreditService { fun save(credit: Credit): Credit fun findAllByCustomer(customerId: Long): List<Credit> fun findByCreditCode(customerId: Long, creditCode: UUID): Credit }
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/service/ICreditService.kt
2657315617
package me.dio.credit.application.system.exception import org.springframework.dao.DataAccessException import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.validation.FieldError import org.springframework.validation.ObjectError import org.springframework.web.bind.MethodArgumentNotValidException import org.springframework.web.bind.annotation.ExceptionHandler import org.springframework.web.bind.annotation.RestControllerAdvice import java.time.LocalDateTime @RestControllerAdvice class RestExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException::class) fun handlerValidException(ex: MethodArgumentNotValidException): ResponseEntity<ExceptionDetails> { val errors: MutableMap<String, String?> = HashMap() ex.bindingResult.allErrors.stream().forEach { err: ObjectError -> val fieldName: String = (err as FieldError).field val messageError: String? = err.defaultMessage errors[fieldName] = messageError } return ResponseEntity( ExceptionDetails( title = "Bad Request! Consult the documentation.", timestamp = LocalDateTime.now(), status = HttpStatus.BAD_REQUEST.value(), exception = ex.javaClass.toString(), details = errors ), HttpStatus.BAD_REQUEST ) } @ExceptionHandler(DataAccessException::class) fun handlerValidException(ex: DataAccessException): ResponseEntity<ExceptionDetails> { return ResponseEntity( ExceptionDetails( title = "Conflict! Consult the documentation.", timestamp = LocalDateTime.now(), status = HttpStatus.CONFLICT.value(), exception = ex.javaClass.toString(), details = mutableMapOf(ex.cause.toString() to ex.message) ), HttpStatus.CONFLICT ) } @ExceptionHandler(BusinessException::class) fun handlerValidException(ex: BusinessException): ResponseEntity<ExceptionDetails> { return ResponseEntity( ExceptionDetails( title = "Bad request! Consult the documentation.", timestamp = LocalDateTime.now(), status = HttpStatus.BAD_REQUEST.value(), exception = ex.javaClass.toString(), details = mutableMapOf(ex.cause.toString() to ex.message) ), HttpStatus.BAD_REQUEST ) } @ExceptionHandler(IllegalArgumentException::class) fun handlerValidException(ex: IllegalArgumentException): ResponseEntity<ExceptionDetails> { return ResponseEntity( ExceptionDetails( title = "Bad request! Consult the documentation.", timestamp = LocalDateTime.now(), status = HttpStatus.BAD_REQUEST.value(), exception = ex.javaClass.toString(), details = mutableMapOf(ex.cause.toString() to ex.message) ), HttpStatus.BAD_REQUEST ) } }
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/exception/RestExceptionHandler.kt
3258162004
package me.dio.credit.application.system.exception data class BusinessException(override val message: String?) : RuntimeException(message)
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/exception/BusinessException.kt
1587394322
package me.dio.credit.application.system.exception import java.time.LocalDateTime class ExceptionDetails( val title: String, val timestamp: LocalDateTime, val status: Int, val exception: String, val details: MutableMap<String, String?> ) { }
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/exception/ExceptionDetails.kt
3539025457
package me.dio.credit.application.system import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class CreditApplicationSystemApplication fun main(args: Array<String>) { runApplication<CreditApplicationSystemApplication>(*args) }
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/CreditApplicationSystemApplication.kt
3438845359
package com.example.circlecircledotdot 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.circlecircledotdot", appContext.packageName) } }
CircleCircleDotDot/app/src/androidTest/java/com/example/circlecircledotdot/ExampleInstrumentedTest.kt
4250219072
package com.example.circlecircledotdot 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) } }
CircleCircleDotDot/app/src/test/java/com/example/circlecircledotdot/ExampleUnitTest.kt
4036978480
package com.example.circlecircledotdot import android.os.Bundle import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (savedInstanceState == null) { supportFragmentManager.beginTransaction() .replace(R.id.container, InputFragment.newInstance()) .commitNow() } } }
CircleCircleDotDot/app/src/main/java/com/example/circlecircledotdot/MainActivity.kt
3964995016
package com.example.circlecircledotdot import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.os.Bundle import android.view.LayoutInflater import android.view.SurfaceHolder import android.view.SurfaceView import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import java.util.Random class DisplayFragment : Fragment() { companion object { private const val COLOR_KEY = "color" fun newInstance(color: Int): DisplayFragment { val fragment = DisplayFragment() val args = Bundle() args.putInt(COLOR_KEY, color) fragment.arguments = args return fragment } } private var color: Int = Color.BLACK // Default color if no argument is provided override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_display, container, false) val surfaceView = view.findViewById<SurfaceView>(R.id.surfaceView) surfaceView.holder.addCallback(object : SurfaceHolder.Callback { override fun surfaceCreated(holder: SurfaceHolder) { // Start drawing on surface created drawCircle(holder) } override fun surfaceChanged( holder: SurfaceHolder, format: Int, width: Int, height: Int ) { // Respond to surface changes if needed } override fun surfaceDestroyed(holder: SurfaceHolder) { // Handle surface destruction if needed } }) return view } private fun drawCircle(holder: SurfaceHolder) { val canvas: Canvas? = holder.lockCanvas() if (canvas != null) { canvas.drawColor(Color.WHITE) // Clear canvas val paint = Paint().apply { color = [email protected] isAntiAlias = true } // X 1.05f längst höger 30f längst vänster // y 1.03f = botten 20 f högst val random= Random() val screenWidth = canvas.width.toFloat() val screenHeight = canvas.height.toFloat() val centerX = random.nextFloat()*screenWidth val centerY = random.nextFloat()*screenHeight val radius = 50f // val centerX = canvas.width / 20f // val centerY = canvas.height / 30f canvas.drawCircle(centerX, centerY, radius, paint) holder.unlockCanvasAndPost(canvas) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { color = it.getInt(COLOR_KEY) } } }
CircleCircleDotDot/app/src/main/java/com/example/circlecircledotdot/DisplayFragment.kt
3860431655
package com.example.circlecircledotdot import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.fragment.app.Fragment import kotlin.random.Random class InputFragment : Fragment() { companion object { fun newInstance() = InputFragment() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_input, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val btnCreate = view.findViewById<Button>(R.id.btn_create) btnCreate.setOnClickListener { val randomColor = getRandomColor() val displayFragment = DisplayFragment.newInstance(randomColor) activity?.supportFragmentManager?.beginTransaction() ?.replace(R.id.container, displayFragment) ?.addToBackStack(null) ?.commit() } } private fun getRandomColor(): Int { val random = Random return android.graphics.Color.argb( 255, random.nextInt(256), random.nextInt(256), random.nextInt(256) ) } }
CircleCircleDotDot/app/src/main/java/com/example/circlecircledotdot/InputFragment.kt
2392581252
package org.rgoussey.aoc2023.day4 import java.io.File import java.util.stream.Collectors fun main() { val lines = File({}.javaClass.getResource("/day4/input.txt")!!.toURI()).readLines(); process(lines); } fun process(lines: List<String>) { val cards = lines.stream().map { line -> Card(line) }.toList() var sum = 0; cards.forEach { card -> run { val score = card.getScore() println("score $score") sum += score } } print(sum) } class Card(line: String) { private var duplicateNumbers: Set<Int> private val losingNumbers: Set<Int> private val winningNumbers: Set<Int> init { val numbers = line.split(":")[1].split("|") winningNumbers = parseNumbers(numbers[0]) losingNumbers = parseNumbers(numbers[1]) duplicateNumbers = losingNumbers.stream().filter(winningNumbers::contains).collect(Collectors.toSet()) } fun getScore(): Int { val size = duplicateNumbers.size return if (size <= 1) { size; } else { 1 shl size - 1 } } private fun parseNumbers(line: String): Set<Int> { val result: MutableSet<Int> = HashSet(); val numbers = line.split(" ") numbers.forEach { number -> run { try { result.add(number.toInt()) } catch (e: Exception) { //Ignore } } } return result; } }
advent_of_code23/src/main/kotlin/org/rgoussey/aoc2023/day4/Main.kt
3916953134
package org.rgoussey.aoc2023.day3 import java.io.File import kotlin.math.max import kotlin.math.min fun main() { val lines = File({}.javaClass.getResource("/day3/input.txt")!!.toURI()).readLines(); process(lines); } fun process(lines: List<String>) { val characters = mutableListOf<MutableList<Char>>() val symbols = mutableListOf<MutableList<Boolean>>() val numbers = mutableListOf<MutableList<Boolean>>() val closeToSymbol = mutableListOf<MutableList<Boolean>>() for (i in lines.indices) { characters.add(i, mutableListOf()) symbols.add(i, mutableListOf()) numbers.add(i, mutableListOf()) closeToSymbol.add(i, mutableListOf()) for (j in lines[i].indices) { val currentChar = lines[i][j] characters[i].add(j, currentChar) val isSymbol = isSymbol(currentChar) symbols[i].add(j, isSymbol) numbers[i].add(j, isNumber(currentChar)) } } for (i in lines.indices) { for (j in lines[i].indices) { closeToSymbol[i].add(j, adjacentToSymbol(symbols, i, j)) } } printMap(symbols) printMap(numbers) printMap(closeToSymbol) var sum = 0; for (i in characters.indices) { var currentNumber = ""; var lastNumberIndex = 0; var numberIsValid = false; for (j in characters[i].indices) { val isNumber = numbers[i][j] if (isNumber) { numberIsValid = numberIsValid or adjacentToSymbol(symbols, i, j) lastNumberIndex = j currentNumber += characters[i][j] val endOfLine = j == characters[i].size-1 if (endOfLine) { val number = Integer.parseInt(currentNumber) if (numberIsValid) { // println("Valid number $number") sum += number; } else { // println(" Not valid number $number") } currentNumber = "" lastNumberIndex = 0; } } else { val numberEnded = lastNumberIndex + 1 == j if (numberEnded && currentNumber != "") { val number = Integer.parseInt(currentNumber) // println("Number is detected %s".format(number)) if (numberIsValid) { // println("Valid number $number") sum += number; } else { // println(" Not valid number $number") } currentNumber = ""; numberIsValid=false } lastNumberIndex = 0; } } } println("Sum is $sum") } fun printMap(map: MutableList<MutableList<Boolean>>) { for (i in map.indices) { for (j in map[i].indices) { if (map[i][j]) { print('x') } else { print('.') } } print("\n"); } print("\n"); } fun adjacentToSymbol(symbols: MutableList<MutableList<Boolean>>, x: Int, y: Int): Boolean { for (i in max(x - 1, 0)..min(x + 1, symbols.size - 1)) { for (j in max(y - 1, 0)..min(y + 1, symbols[x].size - 1)) { if (symbols[i][j]) { return true } } } return false; } fun isSymbol(char: Char): Boolean { return !isNumber(char) && char != '.'; } fun isNumber(char: Char): Boolean { return char in '0'..'9'; }
advent_of_code23/src/main/kotlin/org/rgoussey/aoc2023/day3/Main.kt
3997070164
package com.hezd.test 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.hezd.mapplatform", appContext.packageName) } }
MapPlatform/app/src/androidTest/java/com/hezd/test/ExampleInstrumentedTest.kt
1320207124
package com.hezd.test 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) } }
MapPlatform/app/src/test/java/com/hezd/test/ExampleUnitTest.kt
3074187498
package com.hezd.test.map import android.os.Bundle import android.view.ViewGroup.LayoutParams import android.widget.FrameLayout import androidx.appcompat.app.AppCompatActivity import com.hezd.map.platform.CalcRoteError import com.hezd.map.platform.Map import com.hezd.map.platform.MapCalcRouteCallback import com.hezd.map.platform.MapPlatform import com.hezd.map.platform.bean.GCJLatLng import com.hezd.map.platform.bean.PathInfo import com.hezd.test.map.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private lateinit var mapPlatform: MapPlatform override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) initMap(savedInstanceState) } private fun initMap(savedInstanceState: Bundle?) { mapPlatform = MapPlatform.Builder(Map.TencentMap()) .build() mapPlatform.init(this,savedInstanceState) val mapView = mapPlatform.getMapView(this) val layoutParams = LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT) mapView.layoutParams = layoutParams binding.mapLayout.addView(mapView) mapPlatform.startCalculatePath(GCJLatLng(40.007056,116.389895), GCJLatLng(39.894551,116.321515),object : MapCalcRouteCallback { override fun onSuccess(paths: List<PathInfo>) { if(paths.size>0){ mapPlatform.setRouteZoomToSpan(0) } } override fun onError(calcRoteError: CalcRoteError) { calcRoteError.errorCode } }) } override fun onStart() { super.onStart() mapPlatform.onStart() } override fun onRestart() { super.onRestart() mapPlatform.onRestart() } override fun onResume() { super.onResume() mapPlatform.onResume() } override fun onPause() { super.onPause() mapPlatform.onPause() } override fun onStop() { super.onStop() mapPlatform.onStop() } override fun onDestroy() { super.onDestroy() mapPlatform.onDestroy() } }
MapPlatform/app/src/main/java/com/hezd/test/map/MainActivity.kt
3345568243
package com.hezd.test.map import android.app.Application import com.tencent.navix.api.NavigatorConfig import com.tencent.navix.api.NavigatorZygote import com.tencent.tencentmap.mapsdk.maps.TencentMapInitializer /** * @author hezd * @date 2024/1/23 18:00 * @description */ class MapPlatformApplication : Application() { override fun onCreate() { super.onCreate() // 设置同意地图SDK隐私协议 TencentMapInitializer.setAgreePrivacy(this, true) // 初始化导航SDK NavigatorZygote.with(this).init( NavigatorConfig.builder() // 设置同意导航SDK隐私协议 .setUserAgreedPrivacy(true) // 设置自定义的可区分设备的ID .setDeviceId("tyt_custom_id_123456") .experiment().setUseSharedMap(false) // 单实例有泄漏问题,使用多实例 .build()) } }
MapPlatform/app/src/main/java/com/hezd/test/map/MapPlatformApplication.kt
3003013967
package com.hezd.test.platform 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.hezd.map.platform", appContext.packageName) } }
MapPlatform/map-platform/src/androidTest/java/com/hezd/test/platform/ExampleInstrumentedTest.kt
2465628214
package com.hezd.test.platform 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) } }
MapPlatform/map-platform/src/test/java/com/hezd/test/platform/ExampleUnitTest.kt
482869933
package com.hezd.map.platform import android.content.Context import android.os.Bundle import android.view.View import com.hezd.map.platform.bean.GCJLatLng import com.hezd.map.platform.bean.TruckInfo /** * @author hezd * @date 2024/1/10 14:27 * @description 路径规划策略 */ interface MapStrategy : UiLifecycle { /** * 初始化 */ fun init(context: Context, savedInstanceState: Bundle? = null,markOptions: MarkOptions?) /** * 获取地图View */ fun getMapView(context: Context): View /** * 开始路径规划 */ fun startCalculatePath( start: GCJLatLng, end: GCJLatLng, truckInfo: TruckInfo?=null, calcRoteCallback: MapCalcRouteCallback?, ) /** * 开始定位 */ fun startLocation() /** * 导航路线被点击时回调 */ fun setOnRouteLineClickListener(onRouteLineClickListener: OnRouteLineClickListener) /** * 设置某个路线图层以自适应缩放 */ fun setRouteZoomToSpan(index:Int) /** * 地图放大 */ fun setZoomIn() /** * 地图缩小 */ fun setZoomOut() }
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/MapStrategy.kt
2192100500
package com.hezd.map.platform import com.hezd.map.platform.amap.AMapStrategy import com.hezd.map.platform.tencentmap.TencentMapStrategy /** * @author hezd * @date 2024/1/12 14:30 * @description 地图平台 */ sealed class Map : IMap { open class AMap : Map() { override fun getPlatForm() = AMapStrategy() } open class TencentMap : Map() { override fun getPlatForm(): MapStrategy = TencentMapStrategy() } } interface IMap { fun getPlatForm(): MapStrategy }
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/Map.kt
668386607
package com.hezd.map.platform /** * @author hezd * @date 2024/1/10 17:39 * @description */ data class CalcRoteError(val errorCode:Int,val message:String)
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/CalcRoteError.kt
3401482951
package com.hezd.map.platform.bean import com.amap.api.navi.model.NaviLatLng import com.tencent.navix.api.model.NavSearchPoint /** * @author hezd * @date 2024/1/10 16:54 * @description GCJ-02 - 国测局坐标 */ data class GCJLatLng(val latitude: Double, val longitude: Double) { /** * 转化为高德坐标 */ fun toAMapLatLng(): NaviLatLng = NaviLatLng(latitude, longitude) /** * 转化为腾讯坐标 */ fun toTencentMapLatLng(): NavSearchPoint = NavSearchPoint(latitude, longitude) }
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/bean/GCJLatLng.kt
1667111976
package com.hezd.map.platform.bean /** * @author hezd * @date 2024/1/10 17:36 * @description */ data class PathInfo(val title:String,val navTime:String,val distanceInfo:String)
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/bean/PathInfo.kt
3150126082
package com.hezd.map.platform.bean import com.amap.api.navi.model.AMapCarInfo /** * @author hezd * @date 2024/1/10 18:21 * @description 货车信息 */ data class TruckInfo @JvmOverloads constructor( /** * Unknown, * Mini, * Light, * Medium, * Heavy; * 车辆类型,0未,1迷你型 2轻型 3中型 4重型 */ val carType: String?, /** * 车牌号 */ val carNumber: String?, /** * 货车长度 */ val truckLong: String?, /** * 货车宽 */ val truckWidth: String?, /** * 货车高 */ val truckHigh: String?, /** * 总重量 */ val truckWeight: String?, /** * 货车核定载重 */ val truckApprovedLoad: String?, /** * 轴数 */ val axesNumber: String?, /** * Unknown, * I, * II, * III, * IV, * V, * VI; * 排放标准 0未知 1国一 2国二 3国三 4国四 5国五 6国六 */ val emissionStandards: String?, /** * Unknown, * Blue, * Yellow, * Black, * White, * Green, * YellowGreen; * 车牌颜色 0未知 1蓝牌 2黄牌 3黑牌 4白牌 5绿牌 6黄绿牌 */ val licensePlateColor: String? = null, /** * 货车类型 * 例如高德1-微型货车 2-轻型/小型货车 3-中型货车 4-重型货车 默认取值4,目前不可更改 * 腾讯地图枚举类型 微型,轻型,中型,重型,没有默认值需要选择 */ val mVehicleSize: String?, ) { fun toAMapCarInfo(): AMapCarInfo { return AMapCarInfo().apply { carType = [email protected] carNumber = [email protected] vehicleSize = "4" vehicleLoad = [email protected] vehicleWeight = [email protected] vehicleLength = [email protected] vehicleWidth = [email protected] vehicleHeight = [email protected] vehicleAxis = [email protected] isVehicleLoadSwitch = true isRestriction = true } } class Builder { /** * 车辆类型,0小车,1货车 */ private var carType: String? = null /** * 车牌号 */ private var carNumber: String? = null /** * 货车长度 */ private var truckLong: String? = null /** * 货车宽 */ private var truckWidth: String? = null /** * 货车高 */ private var truckHigh: String? = null /** * 总重量 */ private var truckWeight: String? = null /** * 货车核定载重 */ private var truckApprovedLoad: String? = null /** * 轴数 */ private var axesNumber: String? = null /** * 排放标准 */ private var emissionStandards: String? = null /** * 车牌颜色 */ private var licensePlateColor: String? = null /** * 货车类型 * 例如高德1-微型货车 2-轻型/小型货车 3-中型货车 4-重型货车 默认取值4,目前不可更改 * 腾讯地图枚举类型 微型,轻型,中型,重型,没有默认值需要选择 */ private var mVehicleSize: String? = null fun carType(carType: String): Builder { this.carType = carType return this } fun carNumber(carNumber: String): Builder { this.carNumber = carNumber return this } fun truckLong(truckLong: String): Builder { this.truckLong = truckLong return this } fun truckWidth(truckWidth: String): Builder { this.truckWidth = truckWidth return this } fun truckHigh(truckHigh: String): Builder { this.truckHigh = truckHigh return this } fun truckWeight(truckWeight: String): Builder { this.truckWeight = truckWeight return this } fun truckApprovedLoad(truckApprovedLoad: String): Builder { this.truckApprovedLoad = truckApprovedLoad return this } fun axesNumber(axesNumber: String): Builder { this.axesNumber = axesNumber return this } fun emissionStandards(emissionStandards: String): Builder { this.emissionStandards = emissionStandards return this } fun licensePlateColor(licensePlateColor: String): Builder { this.licensePlateColor = licensePlateColor return this } fun mVehicleSize(mVehicleSize: String): Builder { this.mVehicleSize = mVehicleSize return this } fun build(): TruckInfo { return TruckInfo( carType = carType, carNumber = carNumber, truckLong = truckLong, truckWidth = truckWidth, truckHigh = truckHigh, truckWeight = truckWeight, truckApprovedLoad = truckApprovedLoad, axesNumber = axesNumber, emissionStandards = emissionStandards, licensePlateColor = licensePlateColor, mVehicleSize = mVehicleSize ) } } }
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/bean/TruckInfo.kt
1436276509
package com.hezd.map.platform.tencentmap import android.content.Context import android.graphics.BitmapFactory import android.graphics.Color import android.util.AttributeSet import android.util.TypedValue import android.view.LayoutInflater import android.widget.LinearLayout import com.hezd.map.platform.MarkOptions import com.hezd.map.platform.OnRouteLineClickListener import com.hezd.map.platform.R import com.tencent.navix.api.map.MapApi import com.tencent.navix.api.model.NavRoutePlan import com.tencent.navix.core.NavigatorContext import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory import com.tencent.tencentmap.mapsdk.maps.TencentMap import com.tencent.tencentmap.mapsdk.maps.TencentMap.OnPolylineClickListener import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptorFactory import com.tencent.tencentmap.mapsdk.maps.model.LatLng import com.tencent.tencentmap.mapsdk.maps.model.LatLngBounds import com.tencent.tencentmap.mapsdk.maps.model.Marker import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions import com.tencent.tencentmap.mapsdk.maps.model.OverlayLevel import com.tencent.tencentmap.mapsdk.maps.model.Polyline import com.tencent.tencentmap.mapsdk.maps.model.PolylineOptions class RouteView(context: Context, attrs: AttributeSet?) : LinearLayout(context, attrs) { private var selectIndex = 0 private var marker: Marker? = null private lateinit var tencentMap: MapApi private var plan: NavRoutePlan<*>? = null private var markOptions: MarkOptions? = null private val DP_20 = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 20f, NavigatorContext.share().applicationContext.resources.displayMetrics ).toInt() private val ROUTE_COLOR_MAIN: Int = 0xFF00CC66.toInt() private val ROUTE_COLOR_MAIN_STROKE: Int = 0xFF009449.toInt() private val ROUTE_COLOR_BACKUP: Int = 0xFFAFDBC7.toInt() private val ROUTE_COLOR_BACKUP_STROKE: Int = 0xFF8BB8A3.toInt() private var onPolylineClickListener: TencentMap.OnPolylineClickListener? = null init { LayoutInflater.from(context).inflate(R.layout.view_route, this) } fun injectMap(map: MapApi, markOptions: MarkOptions? = null) { tencentMap = map this.markOptions = markOptions } fun setOnRouteLineClickListener(onRouteLineClickListener: OnRouteLineClickListener) { removeOnPolyLineClickListener() onPolylineClickListener = OnPolylineClickListener { polyLine, _ -> polylineMap.onEachIndexed { index, entry -> if (entry.value == polyLine) { selectIndex = index drawRoute() onRouteLineClickListener.onClick(index) return@OnPolylineClickListener } } } tencentMap.addOnPolylineClickListener(onPolylineClickListener) } fun removeOnPolyLineClickListener() { onPolylineClickListener?.let { tencentMap.removeOnPolylineClickListener(it) } } fun currentIndex(): Int { return selectIndex } fun selectRoute(index: Int) { selectIndex = index drawRoute() } fun updateRoutePlan(routePlan: NavRoutePlan<*>?) { plan = routePlan selectIndex = 0 drawRoute() } fun clear() { polylineMap.forEach { it.value.remove() } polylineMap.clear() startMarker?.remove() startMarker = null endMarker?.remove() endMarker = null } private val polylineMap = mutableMapOf<Int, Polyline>() private var startMarker: Marker? = null private var endMarker: Marker? = null private fun drawRoute() { clear() plan?.apply { val startIconId = markOptions?.startIconId ?: R.mipmap.app_icon_start_point val endIconId = markOptions?.endIconId ?: R.mipmap.app_icon_end_point startMarker = tencentMap.addMarker( MarkerOptions(LatLng(startPoi.latitude, startPoi.longitude)) .icon( BitmapDescriptorFactory.fromBitmap( BitmapFactory.decodeResource( resources, startIconId ) ) ) ) endMarker = tencentMap.addMarker( MarkerOptions(LatLng(endPoi.latitude, endPoi.longitude)) .icon( BitmapDescriptorFactory.fromBitmap( BitmapFactory.decodeResource( resources, endIconId ) ) ) ) } val builder = LatLngBounds.Builder() plan?.routeDatas?.forEachIndexed { index, routeData -> var zIndex = 100 val indexes = intArrayOf(0, routeData.routePoints.size) var colors = intArrayOf(ROUTE_COLOR_BACKUP, ROUTE_COLOR_BACKUP) var borderColors = intArrayOf(ROUTE_COLOR_BACKUP_STROKE, ROUTE_COLOR_BACKUP_STROKE) if (index == selectIndex) { colors = intArrayOf(ROUTE_COLOR_MAIN, ROUTE_COLOR_MAIN) borderColors = intArrayOf(ROUTE_COLOR_MAIN_STROKE, ROUTE_COLOR_MAIN_STROKE) zIndex = 200 } builder.include(routeData.routePoints) val options = PolylineOptions() options.addAll(routeData.routePoints) .arrow(true) .arrowTexture( BitmapDescriptorFactory.fromBitmap( BitmapFactory.decodeResource( resources, R.mipmap.app_arrow_texture ) ) ) .color(Color.GREEN) .lineType(0) .arrowSpacing(150) .zIndex(zIndex) .level(OverlayLevel.OverlayLevelAboveBuildings) .width(32f) .clickable(true) .borderWidth(4f) .borderColors(borderColors) .colors(colors, indexes) polylineMap[index] = tencentMap.addPolyline(options) } tencentMap.moveCamera( CameraUpdateFactory.newLatLngBoundsRect( builder.build(), DP_20, DP_20, DP_20, DP_20 ) ) } fun showLocation(latLng: LatLng) { clear() // 创建 MarkerOptions 对象 val markerOptions: MarkerOptions = MarkerOptions(latLng) .title("Current Location") .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_location)) // 添加 Marker 到地图上 marker = tencentMap.addMarker(markerOptions) tencentMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15f)) } fun zoomIn() { tencentMap.moveCamera(CameraUpdateFactory.zoomIn()) } fun zoomOut() { tencentMap.moveCamera(CameraUpdateFactory.zoomOut()) } fun removeMarker() { marker?.remove() } }
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/tencentmap/RouteView.kt
753910043
package com.hezd.map.platform.tencentmap import android.annotation.SuppressLint import android.content.Context import android.os.Bundle import android.os.Looper import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.hezd.map.platform.CalcRoteError import com.hezd.map.platform.MapCalcRouteCallback import com.hezd.map.platform.MapStrategy import com.hezd.map.platform.MarkOptions import com.hezd.map.platform.OnRouteLineClickListener import com.hezd.map.platform.R import com.hezd.map.platform.bean.GCJLatLng import com.hezd.map.platform.bean.PathInfo import com.hezd.map.platform.bean.TruckInfo import com.hezd.map.platform.formatSToHMStr import com.tencent.map.geolocation.TencentLocation import com.tencent.map.geolocation.TencentLocationListener import com.tencent.map.geolocation.TencentLocationManager import com.tencent.navix.api.NavigatorZygote import com.tencent.navix.api.layer.NavigatorLayerRootDrive import com.tencent.navix.api.layer.NavigatorViewStub import com.tencent.navix.api.model.NavDriveRoute import com.tencent.navix.api.model.NavError import com.tencent.navix.api.model.NavRoutePlan import com.tencent.navix.api.model.NavRouteReqParam import com.tencent.navix.api.model.NavSearchPoint import com.tencent.navix.api.navigator.NavigatorDrive import com.tencent.navix.api.observer.SimpleNavigatorDriveObserver import com.tencent.navix.api.plan.DriveRoutePlanOptions import com.tencent.navix.api.plan.DriveRoutePlanRequestCallback import com.tencent.navix.api.plan.RoutePlanRequester import com.tencent.navix.ui.NavigatorLayerViewDrive import com.tencent.tencentmap.mapsdk.maps.model.LatLng /** * @author hezd * @date 2024/1/11 18:16 * @description */ class TencentMapStrategy : MapStrategy { private var navigatorDrive: NavigatorDrive? = null private var layerRootDrive: NavigatorLayerRootDrive? = null private var layerViewDrive: NavigatorLayerViewDrive? = null private var routeView: RouteView? = null private var mapView: View? = null private var locationManager: TencentLocationManager? = null private val driveObserver: SimpleNavigatorDriveObserver = object : SimpleNavigatorDriveObserver() { override fun onWillArriveDestination() { super.onWillArriveDestination() if (navigatorDrive != null) { navigatorDrive!!.stopNavigation() } } } @SuppressLint("InflateParams") override fun init(context: Context, savedInstanceState: Bundle?,markOptions: MarkOptions?) { // 创建驾车 NavigatorDrive navigatorDrive = NavigatorZygote.with(context.applicationContext).navigator( NavigatorDrive::class.java ) // 创建导航地图层 NavigatorLayerRootDrive mapView = LayoutInflater.from(context).inflate(R.layout.layout_nav, null) val navigatorViewStub = mapView?.findViewById<NavigatorViewStub>(R.id.navigator_view_stub) navigatorViewStub?.setTravelMode(NavRouteReqParam.TravelMode.TravelModeDriving) navigatorViewStub?.inflate() layerRootDrive = navigatorViewStub?.getNavigatorView() // 创建默认面板 NavigatorLayerViewDrive,并添加到导航地图层 layerViewDrive = NavigatorLayerViewDrive(context) layerRootDrive?.addViewLayer(layerViewDrive) // 将导航地图层绑定到Navigator navigatorDrive?.bindView(layerRootDrive) // 注册导航监听 navigatorDrive?.registerObserver(driveObserver) initRouteView(context,markOptions) // 单次定位 locationManager = TencentLocationManager.getInstance(context.applicationContext, null) } private fun initRouteView(context: Context,markOptions: MarkOptions?) { routeView = RouteView(context, null) routeView?.injectMap(layerRootDrive!!.mapApi,markOptions) } override fun getMapView(context: Context): View { if (mapView == null) throw RuntimeException("map view not initialization,invoke init method first") return mapView!! } override fun startCalculatePath( start: GCJLatLng, end: GCJLatLng, truckInfo: TruckInfo?, calcRoteCallback: MapCalcRouteCallback?, ) { routeView?.removeMarker() routeView?.clear() val routePlanRequesterBuilder = RoutePlanRequester.Companion.newBuilder(NavRouteReqParam.TravelMode.TravelModeDriving) .start(NavSearchPoint(start.latitude, start.longitude)) .end(NavSearchPoint(end.latitude, end.longitude)) if (truckInfo != null) { val truckType = when (truckInfo.carType) { "0" -> DriveRoutePlanOptions.TruckOptions.TruckType.Unknown "1" -> DriveRoutePlanOptions.TruckOptions.TruckType.Mini "2" -> DriveRoutePlanOptions.TruckOptions.TruckType.Light "3" -> DriveRoutePlanOptions.TruckOptions.TruckType.Medium "4" -> DriveRoutePlanOptions.TruckOptions.TruckType.Heavy else -> DriveRoutePlanOptions.TruckOptions.TruckType.Heavy } val plateColor = when (truckInfo.licensePlateColor) { "0" -> DriveRoutePlanOptions.TruckOptions.PlateColor.Unknown "1" -> DriveRoutePlanOptions.TruckOptions.PlateColor.Blue "2" -> DriveRoutePlanOptions.TruckOptions.PlateColor.Yellow "3" -> DriveRoutePlanOptions.TruckOptions.PlateColor.Black "4" -> DriveRoutePlanOptions.TruckOptions.PlateColor.White "5" -> DriveRoutePlanOptions.TruckOptions.PlateColor.Green "6" -> DriveRoutePlanOptions.TruckOptions.PlateColor.YellowGreen else -> DriveRoutePlanOptions.TruckOptions.PlateColor.Yellow } val emissionStandards = when (truckInfo.emissionStandards) { "0" -> DriveRoutePlanOptions.TruckOptions.EmissionStandard.Unknown "1" -> DriveRoutePlanOptions.TruckOptions.EmissionStandard.I "2" -> DriveRoutePlanOptions.TruckOptions.EmissionStandard.II "3" -> DriveRoutePlanOptions.TruckOptions.EmissionStandard.III "4" -> DriveRoutePlanOptions.TruckOptions.EmissionStandard.IV "5" -> DriveRoutePlanOptions.TruckOptions.EmissionStandard.V "6" -> DriveRoutePlanOptions.TruckOptions.EmissionStandard.VI else -> DriveRoutePlanOptions.TruckOptions.EmissionStandard.V } routePlanRequesterBuilder .options( DriveRoutePlanOptions.Companion.newBuilder() .licenseNumber(truckInfo.carNumber) // 车牌号 .truckOptions( DriveRoutePlanOptions.TruckOptions.newBuilder() .setHeight(truckInfo.truckHigh?.toFloat() ?: 0f) // 设置货车高度。单位:m .setLength(truckInfo.truckLong?.toFloat() ?: 0f) // 设置货车长度。单位:m .setWidth(truckInfo.truckWidth?.toFloat() ?: 0f) // 设置货车宽度。单位:m .setWeight(truckInfo.truckWeight?.toFloat() ?: 0f) // 设置货车重量。单位:t .setAxisCount(truckInfo.axesNumber?.toInt() ?: 0) // 设置货车轴数 // .setAxisLoad( // 4f // ) // 设置货车轴重。单位:t .setPlateColor(plateColor) // 设置车牌颜色。 .setTrailerType(DriveRoutePlanOptions.TruckOptions.TrailerType.Container) // 设置是否是拖挂车。 .setTruckType(truckType) // 设置货车类型。 // .setEmissionStandard(emissionStandards) // 设置排放标准 .setPassType(DriveRoutePlanOptions.TruckOptions.PassType.NoNeed) // 设置通行证。 .setEnergyType(DriveRoutePlanOptions.TruckOptions.EnergyType.Diesel) // 设置能源类型。 .setFunctionType(DriveRoutePlanOptions.TruckOptions.FunctionType.Normal) // 设置 .build() ) .build() ) } val routePlanRequester = routePlanRequesterBuilder.build() navigatorDrive?.searchRoute(routePlanRequester, DriveRoutePlanRequestCallback { navRoutePlan: NavRoutePlan<NavDriveRoute?>?, error: NavError? -> if (error != null) { // handle error calcRoteCallback?.onError(CalcRoteError(error.errorCode, error.message)) return@DriveRoutePlanRequestCallback } if (navRoutePlan != null) { // handle result routeView?.let { it.updateRoutePlan(navRoutePlan) val routes = navRoutePlan.routes val paths = routes.map { it ?: return@map null val title = it.tag val time = formatSToHMStr(it.getTime() * 60) val distance = it.distance / 1000 val distanceInfo = "${distance}公里 ¥${it.fee}" return@map PathInfo( title = title, navTime = time, distanceInfo = distanceInfo ) }.filterNotNull() calcRoteCallback?.onSuccess(paths) } } }) } override fun startLocation() { routeView?.clear() locationManager?.requestSingleLocationFresh(object : TencentLocationListener { override fun onLocationChanged( tencentLocation: TencentLocation, errorCode: Int, reason: String, ) { if (errorCode == TencentLocation.ERROR_OK) { // 获取到位置信息,更新地图 val currentLatLng = LatLng(tencentLocation.latitude, tencentLocation.longitude) // 在地图上添加标记表示当前位置 addMarker(currentLatLng) } } override fun onStatusUpdate(p0: String?, p1: Int, p2: String?) { } override fun onGnssInfoChanged(p0: Any?) { } override fun onNmeaMsgChanged(p0: String?) { } }, Looper.getMainLooper()) } private fun addMarker(currentLatLng: LatLng) { // 获取当前位置坐标,这里假设定位成功后获取到经纬度 routeView?.showLocation(currentLatLng) } /** * 腾讯地图demo中是不支持,需要在调研一下,暂时空实现 */ override fun setOnRouteLineClickListener(onRouteLineClickListener: OnRouteLineClickListener) { routeView?.setOnRouteLineClickListener(onRouteLineClickListener) } override fun setRouteZoomToSpan(index: Int) { routeView?.selectRoute(index) } override fun setZoomIn() { routeView?.zoomIn() } override fun setZoomOut() { routeView?.zoomOut() } override fun onStart() { layerRootDrive?.onStart() } override fun onRestart() { layerRootDrive?.onRestart() } override fun onPause() { layerRootDrive?.onPause() } override fun onResume() { layerRootDrive?.onResume() } override fun onStop() { layerRootDrive?.onStop() } override fun onDestroy() { layerRootDrive?.onDestroy() // 移除导航监听 navigatorDrive?.unregisterObserver(driveObserver) // 移除默认面板 layerRootDrive?.removeViewLayer(layerViewDrive) // 解绑导航地图 navigatorDrive?.unbindView(layerRootDrive) // 移除mapView (mapView?.parent as ViewGroup).removeView(mapView) // 关闭导航 navigatorDrive?.stopNavigation() // 移除监听器 routeView?.removeOnPolyLineClickListener() layerRootDrive = null navigatorDrive = null routeView = null mapView = null } }
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/tencentmap/TencentMapStrategy.kt
1660855229
package com.hezd.map.platform /** * @author hezd * @date 2024/1/10 15:36 * @description */ interface UiLifecycle { fun onStart() fun onRestart() fun onPause() fun onResume() fun onStop() fun onDestroy() }
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/UiLifecycle.kt
1705012168
package com.hezd.map.platform import com.hezd.map.platform.bean.PathInfo /** * @author hezd * @date 2024/1/10 17:15 * @description 路径规划回调 */ interface MapCalcRouteCallback { fun onSuccess(paths: List<PathInfo>) fun onError(calcRoteError: CalcRoteError) }
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/MapCalcRouteCallback.kt
1968919260
package com.hezd.map.platform.amap import android.content.Context import android.graphics.BitmapFactory import android.os.Bundle import android.util.Log import android.view.View import com.amap.api.location.AMapLocation import com.amap.api.location.AMapLocationClient import com.amap.api.location.AMapLocationClientOption import com.amap.api.location.AMapLocationListener import com.amap.api.maps.AMap import com.amap.api.maps.CameraUpdateFactory import com.amap.api.maps.MapView import com.amap.api.maps.model.BitmapDescriptorFactory import com.amap.api.maps.model.LatLng import com.amap.api.maps.model.Marker import com.amap.api.maps.model.MarkerOptions import com.amap.api.navi.AMapNavi import com.amap.api.navi.AMapNaviListener import com.amap.api.navi.enums.PathPlanningStrategy import com.amap.api.navi.model.AMapCalcRouteResult import com.amap.api.navi.model.AMapCarInfo import com.amap.api.navi.model.RouteOverlayOptions import com.amap.api.navi.view.RouteOverLay import com.hezd.map.platform.MapCalcRouteCallback import com.hezd.map.platform.MapStrategy import com.hezd.map.platform.MarkOptions import com.hezd.map.platform.OnRouteLineClickListener import com.hezd.map.platform.R import com.hezd.map.platform.ROUTE_SELECTED_TRANSPARENCY import com.hezd.map.platform.ROUTE_UNSELECTED_TRANSPARENCY import com.hezd.map.platform.TAG import com.hezd.map.platform.bean.GCJLatLng import com.hezd.map.platform.bean.PathInfo import com.hezd.map.platform.bean.TruckInfo import com.hezd.map.platform.formatSToHMStr import kotlin.math.floor /** * @author hezd * @date 2024/1/10 14:30 * @description 高德路径规划 */ class AMapStrategy : MapStrategy, AMapLocationListener { private var mapView: MapView? = null private var aMap: AMap? = null private lateinit var aMapNavi: AMapNavi private lateinit var locationClientSingle: AMapLocationClient private var route1OverLay: RouteOverLay? = null private var route2OverLay: RouteOverLay? = null private var route3OverLay: RouteOverLay? = null private var locationMarker: Marker? = null private var aMapNaviListener: AMapNaviListener? = null override fun init(context: Context, savedInstanceState: Bundle?, markOptions: MarkOptions?) { mapView = MapView(context) mapView?.onCreate(savedInstanceState) aMap = mapView?.map aMapNavi = AMapNavi.getInstance(context.applicationContext) locationClientSingle = AMapLocationClient(context.applicationContext) val locationClientSingleOption = AMapLocationClientOption() locationClientSingleOption.setOnceLocation(true) locationClientSingleOption.setLocationCacheEnable(false) locationClientSingle.setLocationOption(locationClientSingleOption) locationClientSingle.setLocationListener(this) route1OverLay = RouteOverLay(aMap, null, context) route2OverLay = RouteOverLay(aMap, null, context) route3OverLay = RouteOverLay(aMap, null, context) val overlayOptions = RouteOverlayOptions() overlayOptions.lineWidth = 70f val startBitmap = if (markOptions == null) BitmapFactory.decodeResource( context.resources, R.mipmap.app_icon_start_point ) else { BitmapFactory.decodeResource(context.resources, markOptions.startIconId) } val endBitmap = if (markOptions == null) BitmapFactory.decodeResource( context.resources, R.mipmap.app_icon_end_point ) else { BitmapFactory.decodeResource(context.resources, markOptions.endIconId) } route1OverLay?.setStartPointBitmap(startBitmap) route1OverLay?.setEndPointBitmap(endBitmap) route2OverLay?.setStartPointBitmap(startBitmap) route2OverLay?.setEndPointBitmap(endBitmap) route3OverLay?.setStartPointBitmap(startBitmap) route3OverLay?.setEndPointBitmap(endBitmap) route1OverLay?.showRouteStart(false) route2OverLay?.showRouteStart(false) route3OverLay?.showRouteStart(false) route1OverLay?.showRouteEnd(false) route2OverLay?.showRouteEnd(false) route3OverLay?.showRouteEnd(false) route1OverLay?.routeOverlayOptions = overlayOptions route2OverLay?.routeOverlayOptions = overlayOptions route3OverLay?.routeOverlayOptions = overlayOptions route1OverLay?.showForbiddenMarker(false) route2OverLay?.showForbiddenMarker(false) route3OverLay?.showForbiddenMarker(false) } override fun getMapView(context: Context): View { if (mapView == null) throw RuntimeException("map view not initialization,invoke init method first") return mapView!! } override fun startCalculatePath( start: GCJLatLng, end: GCJLatLng, truckInfo: TruckInfo?, calcRoteCallback: MapCalcRouteCallback?, ) { clearRouteOverlay() val aMapStart = start.toAMapLatLng() val aMapEnd = end.toAMapLatLng() aMapNaviListener = object : AMapNaviAdaptListener() { override fun onCalculateRouteFailure(error: AMapCalcRouteResult) { Log.e( TAG, "amap calculate error,code=${error.errorCode},message=${error.errorDescription}" ) } override fun onCalculateRouteSuccess(result: AMapCalcRouteResult) { val pathList = aMapNavi.naviPaths.map { it.value }.map { val title = it.labels val time = formatSToHMStr(it.allTime) val length = (it.allLength / 1000.0 * 10).toInt() / 10.0 val distance = floor(length).toInt().toString() val formatDistance = distance + "公里 ¥" + it.tollCost PathInfo(title, time, formatDistance) } drawNaviPath() calcRoteCallback?.onSuccess(pathList) } private fun drawNaviPath() { val naviPaths = aMapNavi.naviPaths.values.toList() if (naviPaths.isNotEmpty()) { route1OverLay?.aMapNaviPath = naviPaths[0] route1OverLay?.setTransparency(1f) route1OverLay?.setLightsVisible(false) route1OverLay?.addToMap() route1OverLay?.zoomToSpan() } if (naviPaths.size >= 2) { route2OverLay?.aMapNaviPath = naviPaths[1] route2OverLay?.setTransparency(0.3f) route2OverLay?.setLightsVisible(false) route2OverLay?.addToMap() route2OverLay?.zoomToSpan() } if (naviPaths.size >= 3) { route3OverLay?.aMapNaviPath = naviPaths[2] route3OverLay?.setTransparency(0.3f) route3OverLay?.setLightsVisible(false) route3OverLay?.addToMap() route3OverLay?.zoomToSpan() } } } aMapNavi.addAMapNaviListener(aMapNaviListener) val aMapCarInfo: AMapCarInfo if (truckInfo == null) { aMapCarInfo = AMapCarInfo().apply { carType = "0" // 设置车辆类型,0小车,1货车 } } else { aMapCarInfo = truckInfo.toAMapCarInfo() } aMapNavi.setCarInfo(aMapCarInfo) aMapNavi.calculateDriveRoute( arrayListOf(aMapStart), arrayListOf(aMapEnd), null, PathPlanningStrategy.DRIVING_MULTIPLE_ROUTES_DEFAULT ) } override fun startLocation() { locationClientSingle.startLocation() } private fun setOverlayTransparency(route1: Float, route2: Float, route3: Float) { route1OverLay?.setTransparency(route1) route2OverLay?.setTransparency(route2) route3OverLay?.setTransparency(route3) } override fun setOnRouteLineClickListener(onRouteLineClickListener: OnRouteLineClickListener) { aMap?.setOnPolylineClickListener { if (route1OverLay?.polylineIdList?.contains(it.id) == true) { onRouteLineClickListener.onClick(0) } else if (route2OverLay?.polylineIdList?.contains(it.id) == true) { onRouteLineClickListener.onClick(1) } else if (route2OverLay?.polylineIdList?.contains(it.id) == true) { onRouteLineClickListener.onClick(2) } } } override fun setRouteZoomToSpan(index: Int) { when (index) { 0 -> { route1OverLay?.zoomToSpan() setOverlayTransparency( ROUTE_SELECTED_TRANSPARENCY, ROUTE_UNSELECTED_TRANSPARENCY, ROUTE_UNSELECTED_TRANSPARENCY ) } 1 -> { route2OverLay?.zoomToSpan() setOverlayTransparency( ROUTE_UNSELECTED_TRANSPARENCY, ROUTE_SELECTED_TRANSPARENCY, ROUTE_UNSELECTED_TRANSPARENCY ) } 2 -> { route3OverLay?.zoomToSpan() setOverlayTransparency( ROUTE_UNSELECTED_TRANSPARENCY, ROUTE_UNSELECTED_TRANSPARENCY, ROUTE_SELECTED_TRANSPARENCY ) } } } override fun setZoomIn() { aMap?.animateCamera(CameraUpdateFactory.zoomIn()) } override fun setZoomOut() { aMap?.animateCamera(CameraUpdateFactory.zoomOut()) } override fun onStart() = Unit override fun onRestart() = Unit override fun onStop() = Unit private fun clearRouteOverlay() { route1OverLay?.removeFromMap() route2OverLay?.removeFromMap() route3OverLay?.removeFromMap() } override fun onPause() { mapView?.onPause() } override fun onResume() { mapView?.onResume() } override fun onDestroy() { mapView?.onDestroy() mapView = null route1OverLay?.destroy() route1OverLay = null route2OverLay?.destroy() route2OverLay = null route3OverLay?.destroy() route3OverLay = null aMapNavi.removeAMapNaviListener(aMapNaviListener) aMapNavi.stopNavi() AMapNavi.destroy() locationClientSingle.onDestroy() } /** * 定位回调 */ override fun onLocationChanged(amapLocation: AMapLocation) { if (amapLocation.errorCode == 0) { val mCurrentLatLng = LatLng(amapLocation.latitude, amapLocation.longitude) if (locationMarker == null) { locationMarker = aMap?.addMarker( MarkerOptions().position(mCurrentLatLng).icon( BitmapDescriptorFactory.fromResource(R.mipmap.ic_location) ) ) } else { locationMarker?.position = mCurrentLatLng } aMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(mCurrentLatLng, 15f)) } } }
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/amap/AMapStrategy.kt
832534581
package com.hezd.map.platform.amap import com.amap.api.navi.AMapNaviListener import com.amap.api.navi.model.AMapLaneInfo import com.amap.api.navi.model.AMapModelCross import com.amap.api.navi.model.AMapNaviCameraInfo import com.amap.api.navi.model.AMapNaviCross import com.amap.api.navi.model.AMapNaviLocation import com.amap.api.navi.model.AMapNaviRouteNotifyData import com.amap.api.navi.model.AMapNaviTrafficFacilityInfo import com.amap.api.navi.model.AMapServiceAreaInfo import com.amap.api.navi.model.AimLessModeCongestionInfo import com.amap.api.navi.model.AimLessModeStat import com.amap.api.navi.model.NaviInfo /** * @author hezd * @date 2024/1/10 18:48 * @description */ abstract class AMapNaviAdaptListener : AMapNaviListener { override fun onInitNaviFailure() { } override fun onInitNaviSuccess() { } override fun onStartNavi(p0: Int) { } override fun onTrafficStatusUpdate() { } override fun onLocationChange(p0: AMapNaviLocation?) { } override fun onGetNavigationText(p0: Int, p1: String?) { } override fun onGetNavigationText(p0: String?) { } override fun onEndEmulatorNavi() { } override fun onArriveDestination() { } override fun onCalculateRouteFailure(p0: Int) { } override fun onReCalculateRouteForYaw() { } override fun onReCalculateRouteForTrafficJam() { } override fun onArrivedWayPoint(p0: Int) { } override fun onGpsOpenStatus(p0: Boolean) { } override fun onNaviInfoUpdate(p0: NaviInfo?) { } override fun updateCameraInfo(p0: Array<out AMapNaviCameraInfo>?) { } override fun updateIntervalCameraInfo( p0: AMapNaviCameraInfo?, p1: AMapNaviCameraInfo?, p2: Int, ) { } override fun onServiceAreaUpdate(p0: Array<out AMapServiceAreaInfo>?) { } override fun showCross(p0: AMapNaviCross?) { } override fun hideCross() { } override fun showModeCross(p0: AMapModelCross?) { } override fun hideModeCross() { } override fun showLaneInfo(p0: Array<out AMapLaneInfo>?, p1: ByteArray?, p2: ByteArray?) { } override fun showLaneInfo(p0: AMapLaneInfo?) { } override fun hideLaneInfo() { } override fun onCalculateRouteSuccess(p0: IntArray?) { } override fun notifyParallelRoad(p0: Int) { } override fun OnUpdateTrafficFacility(p0: Array<out AMapNaviTrafficFacilityInfo>?) { } override fun OnUpdateTrafficFacility(p0: AMapNaviTrafficFacilityInfo?) { } override fun updateAimlessModeStatistics(p0: AimLessModeStat?) { } override fun updateAimlessModeCongestionInfo(p0: AimLessModeCongestionInfo?) { } override fun onPlayRing(p0: Int) { } override fun onNaviRouteNotify(p0: AMapNaviRouteNotifyData?) { } override fun onGpsSignalWeak(p0: Boolean) { } }
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/amap/AMapNaviAdaptListener.kt
2949589894
package com.hezd.map.platform import androidx.annotation.DrawableRes /** * @author hezd * @date 2024/1/19 17:35 * @description */ class MarkOptions private constructor( /** * 起始点marker图标 */ @DrawableRes val startIconId: Int = R.mipmap.app_icon_start_point, /** * 目的地marker图标 */ @DrawableRes val endIconId: Int = R.mipmap.app_icon_end_point, /** * 当前定位点marker图标 */ @DrawableRes val locationIconId: Int = R.mipmap.ic_location, ) { class Builder { /** * 起始点marker图标 */ private var startIconId: Int = R.mipmap.app_icon_start_point /** * 目的地marker图标 */ private var endIconId: Int = R.mipmap.app_icon_end_point /** * 当前定位点marker图标 */ private var locationIconId: Int = R.mipmap.ic_location fun startIconId(@DrawableRes startIconId: Int): Builder { this.startIconId = startIconId return this } fun destIconId(@DrawableRes destIconId: Int): Builder { this.endIconId = destIconId return this } fun locationIconId(@DrawableRes locationIconId: Int): Builder { this.locationIconId = locationIconId; return this } fun build(): MarkOptions { return MarkOptions(startIconId, endIconId, locationIconId) } } }
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/MarkOptions.kt
3677207054
package com.hezd.map.platform /** * @author hezd * @date 2024/1/12 14:14 * @description */ /** * 时间转化 * @param 秒数 */ fun formatSToHMStr(second: Int): String { val hour = second / 3600 val minute = second % 3600 / 60 return if (hour > 0) { hour.toString() + "小时" + minute + "分钟" } else minute.toString() + "分钟" }
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/MapStrategyExtensions.kt
3038502687
package com.hezd.map.platform /** * @author hezd * @date 2024/1/10 18:53 * @description */ const val TAG:String = "tytMap" const val ROUTE_UNSELECTED_TRANSPARENCY = 0.3f const val ROUTE_SELECTED_TRANSPARENCY = 1f
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/ConstantValues.kt
1995606395
package com.hezd.map.platform /** * @author hezd * @date 2024/1/11 14:29 * @description */ interface OnRouteLineClickListener { /** * @param index 被点击的路线下标 */ fun onClick(index:Int) }
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/OnRouteLineClickListener.kt
3663837097
package com.hezd.map.platform import android.content.Context import android.os.Bundle import android.view.View import com.hezd.map.platform.bean.GCJLatLng import com.hezd.map.platform.bean.TruckInfo /** * @author hezd * @date 2024/1/10 14:10 * @description */ class MapPlatform private constructor( /** * 导航策略 */ private val strategy: MapStrategy, private val markOptions: MarkOptions? = null, ) { /** * 路径规划初始化 */ fun init(context: Context, savedInstanceState: Bundle? = null) { strategy.init(context, savedInstanceState, markOptions) } /** * 获取地图View */ fun getMapView(context: Context): View = strategy.getMapView(context) /** * 开始路径规划 * @param start 起始点经纬度 * @param end 终点经纬度 * @param calcRoteCallback 路径规划回调 */ fun startCalculatePath( start: GCJLatLng, end: GCJLatLng, calcRoteCallback: MapCalcRouteCallback?, truckInfo: TruckInfo? = null, ) { strategy.startCalculatePath(start, end, truckInfo, calcRoteCallback) } /** * 定位 */ fun startLocation() { strategy.startLocation() } /** * 导航路线被点击时回调 */ fun setOnRouteLineClickListener(onRouteLineClickListener: OnRouteLineClickListener) { strategy.setOnRouteLineClickListener(onRouteLineClickListener) } /** * 设置某个路线图层以自适应缩放 */ fun setRouteZoomToSpan(index: Int) { strategy.setRouteZoomToSpan(index) } /** * 地图放大 */ fun setZoomIn() { strategy.setZoomIn() } /** * 地图缩小 */ fun setZoomOut() { strategy.setZoomOut() } fun onStart() { strategy.onStart() } fun onRestart() { strategy.onRestart() } fun onResume() { strategy.onResume() } fun onPause() { strategy.onPause() } fun onStop() { strategy.onStop() } fun onDestroy() { strategy.onDestroy() } class Builder constructor(private val map: Map) { /** * 车辆信息json数据 */ private var markOptions: MarkOptions? = null fun markOptions(markOptions: MarkOptions): Builder { this.markOptions = markOptions return this } fun build(): MapPlatform { return MapPlatform(map.getPlatForm(), markOptions) } } }
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/MapPlatform.kt
3089644000
package com.example.dzhiadze 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.dzhiadze", appContext.packageName) } }
Dzhiadze/app/src/androidTest/java/com/example/dzhiadze/ExampleInstrumentedTest.kt
1903341849
package com.example.dzhiadze 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) } }
Dzhiadze/app/src/test/java/com/example/dzhiadze/ExampleUnitTest.kt
3800925079
package com.example.dzhiadze import android.app.Activity import android.view.View import android.view.View.VISIBLE import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.dzhiadze.models.MovieModel import com.example.dzhiadze.retrofit.RetrofitClass import com.example.dzhiadze.retrofit.models.Movies import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch open class ActivityViewModel : ViewModel() { val filmCardState:MutableLiveData<Int> by lazy { MutableLiveData<Int>(VISIBLE) } val reddy:MutableLiveData<Boolean> by lazy { MutableLiveData<Boolean>(false) } val internetConection:MutableLiveData<Boolean> by lazy { MutableLiveData<Boolean>(false) } val movies:MutableLiveData<MutableList<MovieModel>> by lazy { MutableLiveData<MutableList<MovieModel>>() } val favesMovies:MutableLiveData<MutableList<MovieModel>> by lazy { MutableLiveData<MutableList<MovieModel>>() } }
Dzhiadze/app/src/main/java/com/example/dzhiadze/ActivityViewModel.kt
3988525223
package com.example.dzhiadze import android.app.Application import androidx.room.Room import com.example.dzhiadze.movies.room.RoomFavesRepository class App : Application() { companion object{ const val FROM="Faves" } lateinit var service: Service private lateinit var db: AppDatabase override fun onCreate() { super.onCreate() db = Room.databaseBuilder( applicationContext, AppDatabase::class.java, "Faves.db" ) .createFromAsset("favesMov.db")//.fallbackToDestructiveMigration() .build() val repositoryFaves = RoomFavesRepository(db.getMoviesDao()) service = Service(repositoryFaves) } }
Dzhiadze/app/src/main/java/com/example/dzhiadze/App.kt
2806820859
package com.example.dzhiadze import android.content.Context import android.net.ConnectivityManager import android.net.NetworkInfo import android.os.Bundle import android.view.View.GONE import android.view.View.VISIBLE import androidx.activity.enableEdgeToEdge import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupWithNavController import com.example.dzhiadze.databinding.ActivityMainBinding import com.example.dzhiadze.models.MovieModel import com.example.dzhiadze.retrofit.RetrofitClass import com.google.android.material.bottomnavigation.BottomNavigationView import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { private val controller by lazy { val navHostFragment = supportFragmentManager .findFragmentById(R.id.fragmentContainerView) as NavHostFragment navHostFragment.navController } private val service: Service get() = (applicationContext as App).service private val datamodel: ActivityViewModel by viewModels() private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) datamodel.internetConection.value=hasConnection() datamodel.filmCardState.observe(this) { state -> binding.navView.visibility = datamodel.filmCardState.value!! } datamodel.internetConection.observe(this) { state -> if (state == true) { val navView: BottomNavigationView = binding.navView navView.setupWithNavController(controller) binding.normalCont.visibility = VISIBLE binding.internetProbCont.visibility = GONE binding.topBar.setupWithNavController(controller) val appBarConfiguration = AppBarConfiguration(setOf(R.id.homeFragment, R.id.profileFragment)) binding.topBar.setupWithNavController(controller, appBarConfiguration) if (datamodel.reddy.value==false and state){ loadData() } } else{ binding.normalCont.visibility = GONE binding.internetProbCont.visibility = VISIBLE binding.update.setOnClickListener{ val tmp=hasConnection() if (tmp != datamodel.internetConection.value) datamodel.internetConection.value=tmp } } } } private fun loadData(){ val apiOb = RetrofitClass() val k = mutableListOf<Int>() var s = listOf<MovieModel>() val faves = mutableListOf<MovieModel>() lifecycleScope.launch(Dispatchers.IO) { for (i in 1..5) { s = s + apiOb.getMoviesFromApi(i) } val t = service.getFavsMoviesId() launch(Dispatchers.Main) { for (i in t) k.add(i.movieId) for (i in 0 until s.size) if (s[i].kinopoiskId in k) { s[i].isFavs = VISIBLE faves.add(s[i]) } datamodel.favesMovies.value = faves datamodel.movies.value = s.toMutableList() datamodel.reddy.value=true } } } private fun hasConnection(): Boolean { val cm: ConnectivityManager = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager var wifiInfo: NetworkInfo? = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI) if (wifiInfo != null && wifiInfo.isConnected) { return true } wifiInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) if (wifiInfo != null && wifiInfo.isConnected) { return true } wifiInfo = cm.activeNetworkInfo return wifiInfo != null && wifiInfo.isConnected } }
Dzhiadze/app/src/main/java/com/example/dzhiadze/MainActivity.kt
2316927858
package com.example.dzhiadze.fragments.home import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class HomeViewModel : ViewModel() { }
Dzhiadze/app/src/main/java/com/example/dzhiadze/fragments/home/HomeViewModel.kt
3817943258
package com.example.dzhiadze.fragments.home import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.example.dzhiadze.ActivityViewModel import com.example.dzhiadze.App import com.example.dzhiadze.adapters.HomeAdapter import com.example.dzhiadze.Service import com.example.dzhiadze.adapters.CinemasHomeAdapter import com.example.dzhiadze.adapters.FavesAdapter import com.example.dzhiadze.databinding.FragmentHomeBinding class HomeFragment : Fragment() { private lateinit var binding: FragmentHomeBinding private lateinit var adapter: HomeAdapter private val datamodel: ActivityViewModel by activityViewModels() private val service: Service get() = (context?.applicationContext as App).service override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { datamodel.filmCardState.value= View.VISIBLE binding = FragmentHomeBinding.inflate(inflater, container, false) val homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java) if (datamodel.reddy.value==false) { datamodel.reddy.observe(viewLifecycleOwner) { state -> if (state == true) { loadRecycler() } } } else { loadRecycler() } return binding.root } private fun loadRecycler() { val controller = findNavController() adapter = HomeAdapter(controller, datamodel, service) adapter.movies = datamodel.movies.value!! val layoutManagerTomorrow = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) binding.recyclerToday.layoutManager = layoutManagerTomorrow binding.progressBar.visibility=GONE binding.recyclerToday.adapter = adapter ////////////////////////// val adapter2 = CinemasHomeAdapter() adapter2.cinemas = datamodel.movies.value!! val layoutManagerCinemas = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) binding.recyclerCinemas.layoutManager = layoutManagerCinemas binding.recyclerCinemas.adapter = adapter2 } }
Dzhiadze/app/src/main/java/com/example/dzhiadze/fragments/home/HomeFragment.kt
1376882678
package com.example.dzhiadze.fragments.movie import android.content.Context import android.net.ConnectivityManager import android.net.NetworkInfo import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import android.view.ViewGroup import androidx.fragment.app.activityViewModels import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import com.example.dzhiadze.ActivityViewModel import com.example.dzhiadze.databinding.FragmentMovieBinding import com.example.dzhiadze.retrofit.RetrofitClass import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class MovieFragment : Fragment() { private lateinit var binding: FragmentMovieBinding private val datamodel: ActivityViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentMovieBinding.inflate(inflater, container, false) val movieViewModel = ViewModelProvider(this).get(MovieViewModel::class.java) val id = arguments?.getInt("id") datamodel.internetConection.value=hasConnection() datamodel.internetConection.observe(viewLifecycleOwner) { state -> if (state == true) { loadData(id!!) } } return binding.root } private fun loadData(id:Int) { val apiOb = RetrofitClass() var genres="" var countries="" var year="" lifecycleScope.launch(Dispatchers.IO) { val s = apiOb.getMovieByIdFromApi(id) launch(Dispatchers.Main) { Glide.with(binding.poster.context) .load(s.posterUrl) .transition(DrawableTransitionOptions.withCrossFade()) .into(binding.poster) binding.movieName.text=s.nameRu binding.description.text=s.description if (s.year!=0) { year = s.year.toString() }else { year = "Неизвестно" } binding.year.text=year if (s.filmLength!=0) { binding.length.text=s.filmLength.toString()+ " минут" }else { binding.length.text="Неизвестно" } if (s.countries.isNotEmpty()){ countries += s.countries[0].country for (i in 1 until s.countries.size) countries+=", " + s.countries[i].country } else { countries = "Неизвестно" } binding.country.text=countries if (s.genres.isNotEmpty()){ genres += s.genres[0].genre for (i in 1 until s.genres.size) genres+=", " + s.genres[i].genre } else { genres = "Неизвестно" } binding.genre.text=genres binding.movFr.visibility=VISIBLE binding.progressBar.visibility= GONE } } } private fun hasConnection(): Boolean { val cm: ConnectivityManager = requireActivity().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager var wifiInfo: NetworkInfo? = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI) if (wifiInfo != null && wifiInfo.isConnected) { return true } wifiInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) if (wifiInfo != null && wifiInfo.isConnected) { return true } wifiInfo = cm.activeNetworkInfo return wifiInfo != null && wifiInfo.isConnected } }
Dzhiadze/app/src/main/java/com/example/dzhiadze/fragments/movie/MovieFragment.kt
3709766421
package com.example.dzhiadze.fragments.movie import androidx.lifecycle.ViewModel class MovieViewModel: ViewModel() { }
Dzhiadze/app/src/main/java/com/example/dzhiadze/fragments/movie/MovieViewModel.kt
3120644447
package com.example.dzhiadze.fragments.favourites import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.View.VISIBLE import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.recyclerview.widget.LinearLayoutManager import com.example.dzhiadze.ActivityViewModel import com.example.dzhiadze.App import com.example.dzhiadze.R import com.example.dzhiadze.adapters.FavesAdapter import com.example.dzhiadze.Service import com.example.dzhiadze.databinding.FragmentFavoritesBinding class FavoritesFragment : Fragment() { private lateinit var binding: FragmentFavoritesBinding private val datamodel: ActivityViewModel by activityViewModels() private lateinit var adapter: FavesAdapter private val service: Service get() = (context?.applicationContext as App).service override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentFavoritesBinding.inflate(inflater, container, false) val controller = findNavController() adapter = FavesAdapter(controller, datamodel, service) adapter.movies = datamodel.favesMovies.value!! val layoutManagerTomorrow = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) binding.recyclerToday.layoutManager = layoutManagerTomorrow binding.progressBar.visibility= View.GONE binding.recyclerToday.adapter = adapter return binding.root } override fun onDestroy() { super.onDestroy() datamodel.filmCardState.value= VISIBLE } }
Dzhiadze/app/src/main/java/com/example/dzhiadze/fragments/favourites/FavoritesFragment.kt
1559895464
package com.example.dzhiadze.fragments.profile import androidx.lifecycle.ViewModel class ProfileViewModel : ViewModel() { // TODO: Implement the ViewModel }
Dzhiadze/app/src/main/java/com/example/dzhiadze/fragments/profile/ProfileViewModel.kt
1299102008
package com.example.dzhiadze.fragments.profile import androidx.lifecycle.ViewModelProvider import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.View.INVISIBLE import android.view.ViewGroup import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController import com.example.dzhiadze.ActivityViewModel import com.example.dzhiadze.R import com.example.dzhiadze.databinding.FragmentProfileBinding class ProfileFragment : Fragment() { private var _binding: FragmentProfileBinding? = null private val binding get() = _binding!! private lateinit var viewModel: ProfileViewModel private val datamodel: ActivityViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentProfileBinding.inflate(inflater, container, false) val controller = findNavController() binding.favesBut.setOnClickListener { datamodel.filmCardState.value=INVISIBLE controller.navigate(R.id.action_profileFragment_to_favoritesFragment) } return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProvider(this).get(ProfileViewModel::class.java) // TODO: Use the ViewModel } }
Dzhiadze/app/src/main/java/com/example/dzhiadze/fragments/profile/ProfileFragment.kt
3759053396
package com.example.dzhiadze.models import android.view.View import com.example.dzhiadze.retrofit.models.Country import com.example.dzhiadze.retrofit.models.Genre data class MovieInfoModel( val nameRu: String, val description:String, val filmLength: Int, val genres: List<Genre>, val posterUrl: String, val year: Int, val countries: List<Country> )
Dzhiadze/app/src/main/java/com/example/dzhiadze/models/MovieInfoModel.kt
3612613929
package com.example.dzhiadze.models import android.view.View.INVISIBLE import com.example.dzhiadze.retrofit.models.Genre data class MovieModel( val kinopoiskId: Int, val nameRu: String, val genres: List<Genre>, val posterUrl: String, val posterUrlPreview: String, val year: Int, var isFavs: Int =INVISIBLE )
Dzhiadze/app/src/main/java/com/example/dzhiadze/models/MovieModel.kt
618140567
package com.example.dzhiadze.retrofit import com.example.dzhiadze.retrofit.models.MovieInfo import com.example.dzhiadze.retrofit.models.Movies import retrofit2.http.GET import retrofit2.http.Header import retrofit2.http.Headers import retrofit2.http.Path import retrofit2.http.Query interface RetrofitRepository { @Headers("Content-Type: application/json") @GET("/api/v2.2/films/{id}") suspend fun getMovieById( @Header("x-api-key") token: String, @Path("id") id: Int ) : MovieInfo @Headers("Content-Type: application/json") @GET("/api/v2.2/films/top?type=TOP_100_POPULAR_FILMS") suspend fun searchMovies( @Header("x-api-key") token: String, @Query("page") page: Int //@Query("type") type: String ) : Movies }
Dzhiadze/app/src/main/java/com/example/dzhiadze/retrofit/RetrofitRepository.kt
3771452362
package com.example.dzhiadze.retrofit.models import com.example.dzhiadze.models.MovieModel data class Movie( val filmId: Int, val nameRu: String?, val nameEn: String?, val genres: List<Genre>, val posterUrl: String, val posterUrlPreview: String, val year: Int ) { fun toMovieModel(): MovieModel = MovieModel( kinopoiskId = filmId, nameRu = nameRu ?: nameEn ?: "-", genres = genres, posterUrl = posterUrl, posterUrlPreview = posterUrlPreview, year = year ) }
Dzhiadze/app/src/main/java/com/example/dzhiadze/retrofit/models/Movie.kt
3510022963
package com.example.dzhiadze.retrofit.models data class Country( val country: String )
Dzhiadze/app/src/main/java/com/example/dzhiadze/retrofit/models/Country.kt
1988502042
package com.example.dzhiadze.retrofit.models data class Genre( val genre : String )
Dzhiadze/app/src/main/java/com/example/dzhiadze/retrofit/models/Genre.kt
3702203925
package com.example.dzhiadze.retrofit.models data class Movies( val films: List<Movie> )
Dzhiadze/app/src/main/java/com/example/dzhiadze/retrofit/models/Movies.kt
2815690306
package com.example.dzhiadze.retrofit.models import com.example.dzhiadze.models.MovieInfoModel import com.example.dzhiadze.models.MovieModel data class MovieInfo( val nameRu: String?, val nameEn: String?, val genres: List<Genre>, val description:String?, val filmLength: Int?, val posterUrl: String, val year: Int?, val countries: List<Country> ) { fun toMovieInfoModel(): MovieInfoModel = MovieInfoModel( nameRu = nameRu ?: nameEn ?: "Неизвестно", genres = genres, description = description?: "Неизвестно", filmLength = filmLength?: 0, posterUrl = posterUrl, year = year?: 0, countries = countries ) }
Dzhiadze/app/src/main/java/com/example/dzhiadze/retrofit/models/MovieInfo.kt
2312313316