path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
CMPE-277-HACKATHON/Frontend/app/src/main/java/com/rfid/hack277/dao/Service.kt
3055009433
package com.rfid.hack277.dao import com.rfid.hack277.model.Response import retrofit2.Call open interface Service { fun get( country: String, startYear: String, endYear: String, filter: String ): Call<List<Response>> }
CMPE-277-HACKATHON/Frontend/app/src/main/java/com/rfid/hack277/charting/Marker.kt
2486035651
package com.rfid.hack277.charting import android.graphics.Typeface import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.unit.dp import com.patrykandpatrick.vico.compose.component.lineComponent import com.patrykandpatrick.vico.compose.component.overlayingComponent import com.patrykandpatrick.vico.compose.component.shapeComponent import com.patrykandpatrick.vico.compose.component.textComponent import com.patrykandpatrick.vico.compose.dimensions.dimensionsOf import com.patrykandpatrick.vico.core.chart.dimensions.HorizontalDimensions import com.patrykandpatrick.vico.core.chart.insets.Insets import com.patrykandpatrick.vico.core.component.marker.MarkerComponent import com.patrykandpatrick.vico.core.component.shape.DashedShape import com.patrykandpatrick.vico.core.component.shape.ShapeComponent import com.patrykandpatrick.vico.core.component.shape.Shapes import com.patrykandpatrick.vico.core.component.shape.cornered.Corner import com.patrykandpatrick.vico.core.component.shape.cornered.MarkerCorneredShape import com.patrykandpatrick.vico.core.context.MeasureContext import com.patrykandpatrick.vico.core.extension.copyColor import com.patrykandpatrick.vico.core.marker.Marker @Composable internal fun rememberMarker(): Marker { val labelBackgroundColor = MaterialTheme.colorScheme.surface val labelBackground = remember(labelBackgroundColor) { ShapeComponent(labelBackgroundShape, labelBackgroundColor.toArgb()).setShadow( radius = LABEL_BACKGROUND_SHADOW_RADIUS, dy = LABEL_BACKGROUND_SHADOW_DY, applyElevationOverlay = true, ) } val label = textComponent( background = labelBackground, lineCount = LABEL_LINE_COUNT, padding = labelPadding, typeface = Typeface.MONOSPACE, ) val indicatorInnerComponent = shapeComponent(Shapes.pillShape, MaterialTheme.colorScheme.surface) val indicatorCenterComponent = shapeComponent(Shapes.pillShape, Color.White) val indicatorOuterComponent = shapeComponent(Shapes.pillShape, Color.White) val indicator = overlayingComponent( outer = indicatorOuterComponent, inner = overlayingComponent( outer = indicatorCenterComponent, inner = indicatorInnerComponent, innerPaddingAll = indicatorInnerAndCenterComponentPaddingValue, ), innerPaddingAll = indicatorCenterAndOuterComponentPaddingValue, ) val guideline = lineComponent( MaterialTheme.colorScheme.onSurface.copy(GUIDELINE_ALPHA), guidelineThickness, guidelineShape, ) return remember(label, indicator, guideline) { object : MarkerComponent(label, indicator, guideline) { init { indicatorSizeDp = INDICATOR_SIZE_DP onApplyEntryColor = { entryColor -> indicatorOuterComponent.color = entryColor.copyColor(INDICATOR_OUTER_COMPONENT_ALPHA) with(indicatorCenterComponent) { color = entryColor setShadow(radius = INDICATOR_CENTER_COMPONENT_SHADOW_RADIUS, color = entryColor) } } } override fun getInsets( context: MeasureContext, outInsets: Insets, horizontalDimensions: HorizontalDimensions, ) = with(context) { outInsets.top = label.getHeight(context) + labelBackgroundShape.tickSizeDp.pixels + LABEL_BACKGROUND_SHADOW_RADIUS.pixels * SHADOW_RADIUS_MULTIPLIER - LABEL_BACKGROUND_SHADOW_DY.pixels } } } } private const val LABEL_BACKGROUND_SHADOW_RADIUS = 4f private const val LABEL_BACKGROUND_SHADOW_DY = 2f private const val LABEL_LINE_COUNT = 1 private const val GUIDELINE_ALPHA = .2f private const val INDICATOR_SIZE_DP = 36f private const val INDICATOR_OUTER_COMPONENT_ALPHA = 32 private const val INDICATOR_CENTER_COMPONENT_SHADOW_RADIUS = 12f private const val GUIDELINE_DASH_LENGTH_DP = 8f private const val GUIDELINE_GAP_LENGTH_DP = 4f private const val SHADOW_RADIUS_MULTIPLIER = 1.3f private val labelBackgroundShape = MarkerCorneredShape(Corner.FullyRounded) private val labelHorizontalPaddingValue = 8.dp private val labelVerticalPaddingValue = 4.dp private val labelPadding = dimensionsOf(labelHorizontalPaddingValue, labelVerticalPaddingValue) private val indicatorInnerAndCenterComponentPaddingValue = 5.dp private val indicatorCenterAndOuterComponentPaddingValue = 10.dp private val guidelineThickness = 2.dp private val guidelineShape = DashedShape(Shapes.pillShape, GUIDELINE_DASH_LENGTH_DP, GUIDELINE_GAP_LENGTH_DP)
CMPE-277-HACKATHON/Frontend/app/src/main/java/com/rfid/hack277/model/DataViewModel.kt
638243700
package com.rfid.hack277.model import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import com.rfid.hack277.dao.AgricultureService import com.rfid.hack277.dao.MacroeconomicService import com.rfid.hack277.dao.TradeService import com.rfid.hack277.ui.Option import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class DataViewModel: ViewModel() { val isPersonaElevated = mutableStateOf(false) val country = mutableStateOf("India") val showProgress = mutableStateOf(false) val mustRefresh = mutableIntStateOf(0) var chartArguments = mutableStateListOf<Option>() }
CMPE-277-HACKATHON/Frontend/app/src/main/java/com/rfid/hack277/model/Response.kt
81276686
package com.rfid.hack277.model data class Response(val year: String, val value: String)
CMPE-277-HACKATHON/Frontend/app/src/main/java/com/rfid/hack277/nav/Fragment.kt
3178146647
package com.rfid.hack277.nav import androidx.annotation.StringRes import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Agriculture import androidx.compose.material.icons.filled.BarChart import androidx.compose.material.icons.filled.Cloud import androidx.compose.material.icons.filled.CurrencyExchange import androidx.compose.ui.graphics.vector.ImageVector import com.rfid.hack277.R sealed class Fragment( val title: String, val route: String, val icon: ImageVector, @StringRes val resourceId: Int ) { object Macroeconomic: Fragment( "Macroeconomic", "macroeconomic", Icons.Filled.BarChart, R.string.bottom_nav_item_macroeconomic) object Agriculture: Fragment( "Agriculture", "agriculture", Icons.Filled.Agriculture, R.string.bottom_nav_item_agriculture) object Trade: Fragment( "Trade", "trade", Icons.Filled.CurrencyExchange, R.string.bottom_nav_item_trade) object ChatGpt: Fragment( "ChatGPT", "chatgpt", Icons.Filled.Cloud, R.string.bottom_nav_item_chatgpt) }
CMPE-277-HACKATHON/Frontend/app/src/main/java/com/rfid/hack277/nav/Page.kt
724135306
package com.rfid.hack277.nav sealed class Page( val title: String, val route: String ) { object corePage: Page( "Food Security App", "core-page" ) }
CMPE-277-HACKATHON/Frontend/app/src/main/java/com/rfid/hack277/nav/Chart.kt
3096491691
package com.rfid.hack277.nav import androidx.navigation.NamedNavArgument import androidx.navigation.NavArgument import androidx.navigation.navArgument import com.rfid.hack277.ui.Category import com.rfid.hack277.ui.Option import com.rfid.hack277.ui.categoryMap sealed class Chart( val route: String, val arguments: List<NamedNavArgument> ) { object Macroeconomic : Chart( "macroeconomic-chart/{category}?${getOptionsList(Category.MACROECONOMIC)}", getNavArgsList(Category.MACROECONOMIC) ) object Agriculture : Chart( "agriculture-chart/{category}?${getOptionsList(Category.AGRICULTURE)}", getNavArgsList(Category.AGRICULTURE) ) object Trade : Chart( "trade-chart/{category}?${getOptionsList(Category.TRADE)}", getNavArgsList(Category.TRADE) ) } private fun getOptionsList(category: Category): String = categoryMap[category]!!.keys.joinToString("&") { "${it.name}={${it.name}}" } private fun getNavArgsList(category: Category): List<NamedNavArgument> = categoryMap[category]!!.keys.map { navArgument(it.name) { defaultValue = "" } } fun getOptionKeySetForCategory(category: Category) = categoryMap[category]!!.keys
a74/src/main/kotlin/Solution.kt
3202624614
/** * 2<=id_list<=1000 ์ด์šฉ์ž ์•„์ด๋”” ๊ฐ€ ๋‹ด๊ธด ๋ฌธ์ž์—ด ๋ฐฐ์—ด * 1<=report<=200,000 ๊ฐ ์ด์šฉ์ž ๊ฐ€ ์‹ ๊ณ ํ•œ ์ด์šฉ์ž ID ์ •๋ณด ๊ฐ€ ๋‹ด๊ธด ๋ฌธ์ž์—ด ๋ฐฐ์—ด * k : ์ •์ง€ ๊ธฐ์ค€๋˜๋Š” ์‹ ๊ณ  ํšŸ์ˆ˜ * ๊ฐ ์œ ์ €๋ณ„๋กœ ์ฒ˜๋ฆฌ ๊ฒฐ๊ณผ ,๋ฉ”์ผ์„ ๋ฐ›์€ ํšŸ์ˆ˜๋ฅผ ๋ฐฐ์—ด๋กœ return */ class Solution { fun solution(id_list: Array<String>, report: Array<String>, k: Int): IntArray { var answer: IntArray = intArrayOf() var id = id_list.toList() var reportMaps = mutableMapOf<String,Int>() var resultMaps = mutableMapOf<String,Int>() var checkReport = listOf<String>() //Maps ์ดˆ๊ธฐํ™” for(i in id.indices){ reportMaps.put(id[i],0) resultMaps.put(id[i],0) } // ์‹ ๊ณ  ๊ฐฏ์ˆ˜ ํŒŒ์•…ํ•˜๊ธฐ for(i in report.indices){ checkReport = report[i].split(" ") //checkReport[0] ์‹ ๊ณ ์ž checkReport[1] ์ œ์ œ ๋Œ€์ƒ reportMaps.replace(checkReport[1], reportMaps.get(checkReport[1])?.plus(1)!!) } // ์ผ์ • ๊ฐ’ ๋„˜์œผ๋ฉด ํ•ด๋‹น๋˜๋Š” ์‚ฌ๋žŒ์—๊ฒŒ ๋ณด๋‚ผ๋ฉ”์„ธ์ง€๋ฅผ ๊ณ„์‚ฐ var result = reportMaps.filter{it.value>=k}.map{it.key} for(i in report.indices){ checkReport = report[i].split(" ") if(result.contains(checkReport[1])){ resultMaps.put(checkReport[0],resultMaps.get(checkReport[0])?.plus(1)!!) } } return answer } } fun main(){ var a = Solution() a.solution(arrayOf("muzi", "frodo", "apeach", "neo"), arrayOf("muzi frodo","apeach frodo","frodo neo","muzi neo","apeach muzi"),2) //[2,1,1,0] a.solution(arrayOf("con", "ryan"), arrayOf("ryan con", "ryan con", "ryan con", "ryan con"),3) //[0] }
ContactsApp_Firebase/app/src/androidTest/java/com/example/contactsapp/ExampleInstrumentedTest.kt
2207377162
package com.example.contactsapp 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.contactsapp", appContext.packageName) } }
ContactsApp_Firebase/app/src/test/java/com/example/contactsapp/ExampleUnitTest.kt
70594236
package com.example.contactsapp 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) } }
ContactsApp_Firebase/app/src/main/java/com/example/contactsapp/ui/viewmodel/ContactDetailViewModel.kt
420394383
package com.example.contactsapp.ui.viewmodel import androidx.lifecycle.ViewModel import com.example.contactsapp.data.datasource.ContactsDataSource import com.example.contactsapp.data.repo.ContactsRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class ContactDetailViewModel @Inject constructor(var crepo: ContactsRepository) : ViewModel() { fun update(contact_id: String , contact_name: String, contact_number: String) { crepo.update(contact_id,contact_name,contact_number) } }
ContactsApp_Firebase/app/src/main/java/com/example/contactsapp/ui/viewmodel/ContactRegisterViewModel.kt
3642180868
package com.example.contactsapp.ui.viewmodel import androidx.lifecycle.ViewModel import com.example.contactsapp.data.datasource.ContactsDataSource import com.example.contactsapp.data.repo.ContactsRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class ContactRegisterViewModel @Inject constructor(var crepo: ContactsRepository): ViewModel() { fun save(contact_name: String, contact_number: String) { crepo.save(contact_name, contact_number) } }
ContactsApp_Firebase/app/src/main/java/com/example/contactsapp/ui/viewmodel/HomepageViewModel.kt
1271094565
package com.example.contactsapp.ui.viewmodel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.contactsapp.data.datasource.ContactsDataSource import com.example.contactsapp.data.entity.Contacts import com.example.contactsapp.data.repo.ContactsRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class HomepageViewModel @Inject constructor(var crepo: ContactsRepository) : ViewModel() { var contactList = MutableLiveData<List<Contacts>>() init { loadContacts() } fun delete(contact_id:String) { crepo.delete(contact_id) } fun loadContacts() { contactList = crepo.loadContacts() } fun search(searchWord: String) { contactList = crepo.search(searchWord) } }
ContactsApp_Firebase/app/src/main/java/com/example/contactsapp/ui/adapter/ContactsAdapter.kt
843925044
package com.example.contactsapp.ui.adapter import android.content.Context import android.util.Log import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBinderMapper import androidx.databinding.DataBindingUtil import androidx.navigation.Navigation import androidx.recyclerview.widget.RecyclerView import com.example.contactsapp.R import com.example.contactsapp.data.entity.Contacts import com.example.contactsapp.databinding.CardDesignBinding import com.example.contactsapp.databinding.FragmentHomePageBinding import com.example.contactsapp.ui.fragment.HomePageFragmentDirections import com.example.contactsapp.ui.viewmodel.HomepageViewModel import com.example.contactsapp.util.doNavigation import com.google.android.material.snackbar.Snackbar class ContactsAdapter(var mContext: Context, var contactList:List<Contacts>, var viewModel: HomepageViewModel) : RecyclerView.Adapter<ContactsAdapter.CardDesignHolder>() { inner class CardDesignHolder(var design:CardDesignBinding) : RecyclerView.ViewHolder(design.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardDesignHolder { val binding: CardDesignBinding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.card_design, parent, false) return CardDesignHolder(binding) } override fun onBindViewHolder(holder: CardDesignHolder, position: Int) { val contact = contactList.get(position) val t = holder.design t.contactObject = contact t.textViewContactName.text = contact.contact_name t.textViewContactNumber.text = contact.contact_number t.cardViewRow.setOnClickListener { val navigate = HomePageFragmentDirections.contactDetailNavigate(contact = contact) Navigation.doNavigation(it, navigate) } t.imageViewDelete.setOnClickListener { Snackbar.make(it, "${contact.contact_name} will removed, are you sure?", Snackbar.LENGTH_SHORT) .setAction("YES") { viewModel.delete(contact.contact_id!!) } .show() } } override fun getItemCount(): Int { return contactList.size } }
ContactsApp_Firebase/app/src/main/java/com/example/contactsapp/ui/fragment/ContactRegisterFragment.kt
2976715286
package com.example.contactsapp.ui.fragment import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.viewModels import com.example.contactsapp.R import com.example.contactsapp.databinding.FragmentContactRegisterBinding import com.example.contactsapp.ui.viewmodel.ContactRegisterViewModel import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class ContactRegisterFragment : Fragment() { private lateinit var binding: FragmentContactRegisterBinding private lateinit var viewModel: ContactRegisterViewModel override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_contact_register, container, false) binding.contactRegisterFragment = this binding.contactRegisterToolbarTitle = "Contact Register" return binding.root } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val tempViewModel:ContactRegisterViewModel by viewModels() viewModel = tempViewModel } fun buttonSave(contact_name: String, contact_number: String) { viewModel.save(contact_name, contact_number) } }
ContactsApp_Firebase/app/src/main/java/com/example/contactsapp/ui/fragment/HomePageFragment.kt
3967020787
package com.example.contactsapp.ui.fragment import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.SearchView import androidx.databinding.DataBindingUtil import androidx.fragment.app.viewModels import androidx.navigation.Navigation import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.example.contactsapp.R import com.example.contactsapp.data.entity.Contacts import com.example.contactsapp.databinding.FragmentHomePageBinding import com.example.contactsapp.ui.adapter.ContactsAdapter import com.example.contactsapp.ui.viewmodel.ContactDetailViewModel import com.example.contactsapp.ui.viewmodel.HomepageViewModel import com.example.contactsapp.util.doNavigation import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class HomePageFragment : Fragment() { private lateinit var binding: FragmentHomePageBinding private lateinit var viewModel: HomepageViewModel override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_home_page, container, false) binding.homePageFragment = this binding.homePageToolbarTitle = "Contacts" binding.rv.layoutManager = LinearLayoutManager(requireContext()) //binding.rv.layoutManager = StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL) viewModel.contactList.observe(viewLifecycleOwner) { val contactsAdapter = ContactsAdapter(requireContext(), it, viewModel) binding.contactAdapter = contactsAdapter } binding.searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { if (query != null) { viewModel.search(query) } return true } override fun onQueryTextChange(newText: String?): Boolean { if (newText != null) { viewModel.search(newText) } return true } }) return binding.root } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val tempViewModel: HomepageViewModel by viewModels() viewModel = tempViewModel } fun fabClick(it:View) { Navigation.doNavigation(it, R.id.contactRegisterNavigate) } }
ContactsApp_Firebase/app/src/main/java/com/example/contactsapp/ui/fragment/ContactDetailFragment.kt
2692227258
package com.example.contactsapp.ui.fragment import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.viewModels import androidx.navigation.fragment.navArgs import com.example.contactsapp.R import com.example.contactsapp.databinding.FragmentContactDetailBinding import com.example.contactsapp.ui.viewmodel.ContactDetailViewModel import com.example.contactsapp.ui.viewmodel.ContactRegisterViewModel import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class ContactDetailFragment : Fragment() { private lateinit var binding: FragmentContactDetailBinding private lateinit var viewModel: ContactDetailViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = DataBindingUtil.inflate(inflater,R.layout.fragment_contact_detail, container, false) binding.contactDetailFragment = this binding.contactDetailToolbarTitle = "Contact Detail" val bundle: ContactDetailFragmentArgs by navArgs() val comerContact = bundle.contact binding.contactObject = comerContact return binding.root } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val tempViewModel: ContactDetailViewModel by viewModels() viewModel = tempViewModel } fun buttonUpdate(contact_id:String, contact_name: String, contact_number: String) { viewModel.update(contact_id, contact_name, contact_number) } }
ContactsApp_Firebase/app/src/main/java/com/example/contactsapp/MainActivity.kt
2628329805
package com.example.contactsapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
ContactsApp_Firebase/app/src/main/java/com/example/contactsapp/di/AppModule.kt
2013489568
package com.example.contactsapp.di import com.example.contactsapp.data.datasource.ContactsDataSource import com.example.contactsapp.data.repo.ContactsRepository import com.google.firebase.Firebase import com.google.firebase.firestore.CollectionReference import com.google.firebase.firestore.firestore import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class AppModule { @Provides @Singleton fun provideContactsDataSource(collectionContacts:CollectionReference) : ContactsDataSource { return ContactsDataSource(collectionContacts) } @Provides @Singleton fun provideContactsRepository(cds: ContactsDataSource) : ContactsRepository { return ContactsRepository(cds) } @Provides @Singleton fun provideCollectionReference() : CollectionReference { return Firebase.firestore.collection("Contacts") } }
ContactsApp_Firebase/app/src/main/java/com/example/contactsapp/di/HiltApplication.kt
3960888017
package com.example.contactsapp.di import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class HiltApplication : Application() { }
ContactsApp_Firebase/app/src/main/java/com/example/contactsapp/util/Extensions.kt
3162523804
package com.example.contactsapp.util import android.view.View import androidx.navigation.NavDirections import androidx.navigation.Navigation fun Navigation.doNavigation(it:View, id:Int) { findNavController(it).navigate(id) } fun Navigation.doNavigation(it:View, id:NavDirections) { findNavController(it).navigate(id) }
ContactsApp_Firebase/app/src/main/java/com/example/contactsapp/data/datasource/ContactsDataSource.kt
440908636
package com.example.contactsapp.data.datasource import android.util.Log import androidx.lifecycle.MutableLiveData import com.example.contactsapp.data.entity.Contacts import com.google.firebase.firestore.CollectionReference import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class ContactsDataSource(var collectionContacts: CollectionReference) { var contactList = MutableLiveData<List<Contacts>>() fun loadContacts() : MutableLiveData<List<Contacts>> { collectionContacts.addSnapshotListener { value, error -> if (value != null) { val list = ArrayList<Contacts>() for (d in value.documents) { val contact = d.toObject(Contacts::class.java) if(contact != null) { contact.contact_id = d.id list.add(contact) } } contactList.value = list } } return contactList } fun search(searchWord: String) : MutableLiveData<List<Contacts>> { collectionContacts.addSnapshotListener { value, error -> if (value != null) { val list = ArrayList<Contacts>() for (d in value.documents) { val contact = d.toObject(Contacts::class.java) if(contact != null) { if(contact.contact_name!!.lowercase().contains(searchWord.lowercase())) { contact.contact_id = d.id list.add(contact) } } } contactList.value = list } } return contactList } fun save(contact_name: String, contact_number: String) { val newContact = Contacts("", contact_name, contact_number) collectionContacts.document().set(newContact) } fun update(contact_id:String, contact_name: String, contact_number: String) { val updatedContact = HashMap<String, Any>() updatedContact["contact_name"] = contact_name updatedContact["contact_number"] = contact_number collectionContacts.document(contact_id).update(updatedContact) } fun delete(contact_id:String) { collectionContacts.document(contact_id).delete() } }
ContactsApp_Firebase/app/src/main/java/com/example/contactsapp/data/entity/Contacts.kt
687532295
package com.example.contactsapp.data.entity import java.io.Serializable class Contacts(var contact_id:String? = "", var contact_name:String? = "", var contact_number: String? = "") : Serializable { }
ContactsApp_Firebase/app/src/main/java/com/example/contactsapp/data/repo/ContactsRepository.kt
2607330179
package com.example.contactsapp.data.repo import androidx.lifecycle.MutableLiveData import com.example.contactsapp.data.datasource.ContactsDataSource import com.example.contactsapp.data.entity.Contacts class ContactsRepository(var cds:ContactsDataSource) { fun save(contact_name: String, contact_number: String) = cds.save(contact_name, contact_number) fun update(contact_id:String, contact_name: String, contact_number: String) = cds.update(contact_id, contact_name, contact_number) fun delete(contact_id:String) = cds.delete(contact_id) fun loadContacts() : MutableLiveData<List<Contacts>> = cds.loadContacts() fun search(searchWord: String) : MutableLiveData<List<Contacts>> = cds.search(searchWord) }
just/app/src/androidTest/java/com/example/aviatickets/ExampleInstrumentedTest.kt
91970574
package com.example.aviatickets 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.aviatickets", appContext.packageName) } }
just/app/src/test/java/com/example/aviatickets/ExampleUnitTest.kt
2495463373
package com.example.aviatickets 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) } }
just/app/src/main/java/com/example/aviatickets/activity/MainActivity.kt
1457783052
package com.example.aviatickets.activity import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.aviatickets.R import com.example.aviatickets.databinding.ActivityMainBinding import com.example.aviatickets.fragment.OfferListFragment class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) supportFragmentManager .beginTransaction() .add(R.id.fragment_container_view, OfferListFragment.newInstance()) .commit() } }
just/app/src/main/java/com/example/aviatickets/adapter/OfferListAdapter.kt
1471910065
package com.example.aviatickets.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.aviatickets.R import com.example.aviatickets.databinding.ItemOfferBinding import com.example.aviatickets.model.entity.Offer class OfferListAdapter : ListAdapter<Offer, OfferListAdapter.ViewHolder>(DiffUtils()) { private val items: ArrayList<Offer> = arrayListOf() class DiffUtils: DiffUtil.ItemCallback<Offer>(){ override fun areItemsTheSame(oldItem: Offer, newItem: Offer): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: Offer, newItem: Offer): Boolean { return oldItem == newItem } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( ItemOfferBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(getItem(position)) } inner class ViewHolder( private val binding: ItemOfferBinding ) : RecyclerView.ViewHolder(binding.root) { private val context = binding.root.context fun bind(offer: Offer) { val flight = offer.flight with(binding) { departureTime.text = flight.departureTimeInfo arrivalTime.text = flight.arrivalTimeInfo route.text = context.getString( R.string.route_fmt, flight.departureLocation.code, flight.arrivalLocation.code ) duration.text = context.getString( R.string.time_fmt, getTimeFormat(flight.duration).first.toString(), getTimeFormat(flight.duration).second.toString() ) direct.text = context.getString(R.string.direct) price.text = context.getString(R.string.price_fmt, offer.price.toString()) if(flight.airline.name == "Air Astana"){ Glide.with(itemView.context) .load("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACoCAMAAABt9SM9AAAAwFBMVEX///8kSZqfhlEbRJgMPZUAOpQRP5Yg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isN+6iG8Y3y2D3j7+s9YRu29Vou5cyo+1Vinitic7lJKV5ZVLmvKHVWHab/mrlW/PhMlFuagx6lNC4Mdvo7XrBNGqpOxM62xuuLcuatyQWLIftdivR7t2sfcXamK6Hg0a8O31/D7aTKzg5ZuTxUwz0iVEHWvV3LRv+t7gXA33/hcvz8QYrYYe8svyvZpN6/51Oqt8fIZo5v07dt/Pj800M9E6QsqJWUq5rkox+9Hbqbp0r2R8NZAsOSEh6qSydoSIC6ffh0bMKSf2EDtUqJPXjzEx5BhEQyqiXmL8X8/mFPyjfg+SfKsBH4k7iMurljrfZkEQZFV2rDJsg0I9O3ZE/gk++iL/zPXgEgPUy2S8sEBk00OOfsSvNx69LFKs8GxQLQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQZD/Gv8DxRjaL5SIZ5EAAAAASUVORK5CYII=") .into(airlineImage) } else if(flight.airline.name == "FlyArystan"){ Glide.with(itemView.context) .load("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAA3lBMVEX///+iHzQAHmGhGzGcABudACKhGC+dAB+gEyybABaeACScABqbABecAB2bABSfDyoAAFUAAFeaAA768/QAAFEAG2DfvcHz5efoz9LXrLHasrfAeIHct7u7a3Xw4OL37u+3YWzKkJeqOkqzVmLTparr1tmtQ1LPnKKwTVqmKz7CfoYACFoAFl7kyMzNlp2uR1Xr7fGWAACoMkTHiJC4ZXDCfIW9wc94gJ7k5uxbZYu3u8qJj6nO0tyVm7Ll5+2rsMIPJ2Y/THtLV4IgMGouPXKEi6ZtdZdUXodDT30AAEcBuHK+AAAWnUlEQVR4nO1dZ3viSBIWKNISakC2yCKJaAM24PEE+ybszOze//9Dp1YAdZAQ0MDsPbx3H2ZBYL1UdXWlLgnCDTfccMMNN9xwww033PD/B8uZ1xfr9mCyHI2Wk+5Lrz6vXvueOMIaT5+fKyqEmhJAg0Au6uqkN7eufW/c0LHXUxMoOQwKVPV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Glide.with(itemView.context) .load("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAn1BMVEX///8AaK8AZq4AZa4AY60AYawAX6sAXKoAWqkAWann7vWDt9mIu9vW4e5po87q8ff2+vx7sdY9hL3G1+hGisCwx98YcLMhdLWXttbB0+bK2upenMpxqdF8pM3g6vONr9IzfrpfksNum8imwNtTk8VNj8MpeLeVtNVxncl9pc21y+JLhr3a5vFjnssAU6agvNmWwN631OhXjMAATaSkyeJFWkEgAAAYOElEQVR4nO09C3uqurIlL6AgAqWggoqKtFZdruXd//+33QRQEwgPxT48X+ecb5+zLWImM5n3TJ6efuEXfuEXfuEXfuEXfuEXeHiZH32E/O30Y/jdS/kMGG6QiiEAQIGYeH9n372eu8NGR0DJAaaGtU7+x3AcAKycwTdcDJEf/fvuVd0RDjq4IIisBNH/AYoTPn/3wu4Fc03hAJhBzqyeow2+e2n3gY0qIKgUGCq+CbTJdy/uHjDiKQggQE6Isv+bGhDo/wNUHOs8fu46hq4ZUxQBjhKoKPjhVeOzehEyMDAcihYKzTXEyj6C7DP/u1fYF1J4IWFgeAjRf0drw3BMC2S44+V3L7EfzAmnJpw1ypkVKa4XnCwA7eO7F9kHZvwh9E0qSKnZBmIPggtpAbG/e5k9wOU0PUhNAFUSB/o6Qrz+QIvvXubt8CEoCsVM4xf6qf1vT3gMFf1xtaIPBFqtX4rP7aOAInhYebo64ZFJTaC9XP60FFBUX79vkb3gQiN2HvUx/7ejcBSV71piP3g90QmGIVTUkfhXhedgsvqeJfaE8ymEXoTQtvTXCadIKLbfssKeMD67FNTGxlWl987zqfqIan8LcyEDEQKmhA1tIijLb1hhT3jWcyFjGFHoOmvJEyNenj6gMzxnkRlmnKVeYjnSsBNPRPR4BnhOQcenWELVkj4y58JTj2edTtSMRZPsMKpj6TND3qgjj6b1qaRkCFIqURxBzUMLznmEZXXy04GAHEEYUH9+XvPQCx+j0h8rnvGi0jPIEPSNNdRqw9uQkzUPZtdM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Pair( first = minutes / 60, second = minutes % 60 ) } }
just/app/src/main/java/com/example/aviatickets/fragment/OfferListFragment.kt
1621846272
package com.example.aviatickets.fragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import com.example.aviatickets.R import com.example.aviatickets.adapter.OfferListAdapter import com.example.aviatickets.databinding.FragmentOfferListBinding import com.example.aviatickets.model.entity.Offer import com.example.aviatickets.model.network.ApiClient import com.example.aviatickets.model.service.FakeService import retrofit2.Call import retrofit2.Response class OfferListFragment : Fragment() { private var flightOffers: List<Offer> = emptyList() companion object { fun newInstance() = OfferListFragment() } private var _binding: FragmentOfferListBinding? = null private val binding get() = _binding!! private val adapter: OfferListAdapter by lazy { OfferListAdapter() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentOfferListBinding.inflate(layoutInflater, container, false) return _binding?.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupUI() ApiClient.apiService.getFlights().enqueue(object : retrofit2.Callback<List<Offer>> { override fun onResponse(call: Call<List<Offer>>, response: Response<List<Offer>>) { if (response.isSuccessful) { flightOffers = response.body() ?: emptyList() adapter.submitList(flightOffers) } else { Toast.makeText(requireContext(), "Something is wrong!", Toast.LENGTH_SHORT).show() } } override fun onFailure(call: Call<List<Offer>>, t: Throwable) { } }) } private fun setupUI() { with(binding) { offerList.adapter = adapter sortRadioGroup.setOnCheckedChangeListener { _, checkedId -> when (checkedId) { R.id.sort_by_price -> { val sortedByPrice = flightOffers.sortedBy { it.price } adapter.submitList(sortedByPrice.toList()) } R.id.sort_by_duration -> { val sortedByDuration = flightOffers.sortedBy { it.flight.duration } adapter.submitList(sortedByDuration.toList()) } } } } } }
just/app/src/main/java/com/example/aviatickets/model/entity/Location.kt
263656425
package com.example.aviatickets.model.entity import com.google.gson.annotations.SerializedName data class Location( @SerializedName("city_name") val cityName: String, val code: String )
just/app/src/main/java/com/example/aviatickets/model/entity/Offer.kt
872707810
package com.example.aviatickets.model.entity data class Offer( val id: String, val price: Int, val flight: Flight )
just/app/src/main/java/com/example/aviatickets/model/entity/Airline.kt
197109898
package com.example.aviatickets.model.entity data class Airline( val name: String, val code: String )
just/app/src/main/java/com/example/aviatickets/model/entity/Flight.kt
1571843220
package com.example.aviatickets.model.entity import com.google.gson.annotations.SerializedName data class Flight( @SerializedName("departure_location") val departureLocation: Location, @SerializedName("arrival_location") val arrivalLocation: Location, @SerializedName("departure_time_info") val departureTimeInfo: String, @SerializedName("arrival_time_info") val arrivalTimeInfo: String, @SerializedName("flight_number") val flightNumber: String, @SerializedName("airline") val airline: Airline, @SerializedName("duration") val duration: Int )
just/app/src/main/java/com/example/aviatickets/model/network/ApiService.kt
2682275851
package com.example.aviatickets.model.network import com.example.aviatickets.model.entity.Offer import retrofit2.Call import retrofit2.http.GET interface ApiService { @GET("offer_list") fun getFlights(): Call<List<Offer>> }
just/app/src/main/java/com/example/aviatickets/model/network/ApiClient.kt
2990681043
package com.example.aviatickets.model.network import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object ApiClient { private val retrofit = Retrofit.Builder() .baseUrl("https://my-json-server.typicode.com/estharossa/fake-api-demo/") .addConverterFactory(GsonConverterFactory.create()) .build() val apiService: ApiService by lazy { retrofit.create(ApiService::class.java) } }
just/app/src/main/java/com/example/aviatickets/model/service/FakeService.kt
3729211622
package com.example.aviatickets.model.service import com.example.aviatickets.model.entity.Airline import com.example.aviatickets.model.entity.Flight import com.example.aviatickets.model.entity.Location import com.example.aviatickets.model.entity.Offer import java.util.UUID object FakeService { val offerList = listOf( Offer( id = UUID.randomUUID().toString(), price = 24550, flight = Flight( departureLocation = Location( cityName = "ะะปะผะฐั‚ั‹", code = "ALA" ), departureTimeInfo = "20:30", arrivalLocation = Location( cityName = "ะัั‚ะฐะฝะฐ", code = "NQZ" ), arrivalTimeInfo = "22-30", flightNumber = "981", airline = Airline( name = "Air Astana", code = "KC" ), duration = 120 ) ), Offer( id = UUID.randomUUID().toString(), price = 16250, flight = Flight( departureLocation = Location( cityName = "ะะปะผะฐั‚ั‹", code = "ALA" ), departureTimeInfo = "16:00", arrivalLocation = Location( cityName = "ะัั‚ะฐะฝะฐ", code = "NQZ" ), arrivalTimeInfo = "18-00", flightNumber = "991", airline = Airline( name = "Air Astana", code = "KC" ), duration = 120 ) ), Offer( id = UUID.randomUUID().toString(), price = 8990, flight = Flight( departureLocation = Location( cityName = "ะะปะผะฐั‚ั‹", code = "ALA" ), departureTimeInfo = "09:30", arrivalLocation = Location( cityName = "ะัั‚ะฐะฝะฐ", code = "NQZ" ), arrivalTimeInfo = "11-10", flightNumber = "445", airline = Airline( name = "FlyArystan", code = "KC" ), duration = 100 ) ), Offer( id = UUID.randomUUID().toString(), price = 14440, flight = Flight( departureLocation = Location( cityName = "ะะปะผะฐั‚ั‹", code = "ALA" ), departureTimeInfo = "14:30", arrivalLocation = Location( cityName = "ะัั‚ะฐะฝะฐ", code = "NQZ" ), arrivalTimeInfo = "16-00", flightNumber = "223", airline = Airline( name = "SCAT Airlines", code = "DV" ), duration = 90 ) ), Offer( id = UUID.randomUUID().toString(), price = 15100, flight = Flight( departureLocation = Location( cityName = "ะะปะผะฐั‚ั‹", code = "ALA" ), departureTimeInfo = "18:00", arrivalLocation = Location( cityName = "ะัั‚ะฐะฝะฐ", code = "NQZ" ), arrivalTimeInfo = "20:15", flightNumber = "171", airline = Airline( name = "QazaqAir", code = "IQ" ), duration = 135 ) ) ) }
kotlin-native-practice-001/src/nativeMain/kotlin/Main.kt
2767350267
import kotlinx.cinterop.ExperimentalForeignApi import kotlinx.cinterop.refTo import kotlinx.cinterop.toKString import platform.posix.fgets import platform.posix.pclose import platform.posix.popen fun main() { val tmuxPanes = getTmuxPanes() val activeTmuxPane = getActiveTmuxPane() val widestTmuxPane = tmuxPanes?.maxBy { it.width } "Tmux Panes: $tmuxPanes".println() "Active Pane: $activeTmuxPane".println() "Widest Pane: $widestTmuxPane".println() if(widestTmuxPane != null && activeTmuxPane != widestTmuxPane.paneId && tmuxPanes.size > 1) { "Swapping ${widestTmuxPane.paneId} and $activeTmuxPane".println() tmuxSwitchPane(widestTmuxPane.paneId, activeTmuxPane) } } @OptIn(ExperimentalForeignApi::class) fun executeCommand( command: String, trim: Boolean = true, redirectStderr: Boolean = true, ): String { val commandToExecute = if (redirectStderr) "$command 2>&1" else command val fp = popen(commandToExecute, "r") ?: error("Failed to run command: $command") val stdout = buildString { val buffer = ByteArray(4096) while (true) { val input = fgets(buffer.refTo(0), buffer.size, fp) ?: break append(input.toKString()) } } val status = pclose(fp) if (status != 0) { error("Command `$command` failed with status $status${if (redirectStderr) ": $stdout" else ""}") } return if (trim) stdout.trim() else stdout } fun Any.println() = println(this) data class TmuxPane( val paneId: String, val width: Int ) fun getTmuxPanes(): List<TmuxPane>? { return executeCommand( "tmux list-panes -F '#{pane_index}:#{pane_width}'" ).let { it.split("\n").map { paneLine -> with(paneLine.split(":")) { TmuxPane(get(0), get(1).toInt()) } } } } fun getActiveTmuxPane(): String { return executeCommand( // "tmux display-message -p '#I'" "tmux display -p '#{pane_index}'" ) } fun tmuxSwitchPane( paneIdOne: String, paneIdTwo: String, ): String? { return executeCommand( "tmux swap-pane -s${paneIdOne} -t${paneIdTwo}" ) }
Prueba_compartida/MyApplication/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt
1188990709
package com.example.myapplication import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.myapplication", appContext.packageName) } }
Prueba_compartida/MyApplication/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt
2019423820
package com.example.myapplication import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
Prueba_compartida/MyApplication/app/src/main/java/com/example/myapplication/MainActivity.kt
3966238622
package com.example.myapplication import android.os.Bundle import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_main) ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } } }
AndroidMidka/app/src/androidTest/java/com/example/aviatickets/ExampleInstrumentedTest.kt
91970574
package com.example.aviatickets 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.aviatickets", appContext.packageName) } }
AndroidMidka/app/src/test/java/com/example/aviatickets/ExampleUnitTest.kt
2495463373
package com.example.aviatickets 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) } }
AndroidMidka/app/src/main/java/com/example/aviatickets/activity/MainActivity.kt
1457783052
package com.example.aviatickets.activity import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.aviatickets.R import com.example.aviatickets.databinding.ActivityMainBinding import com.example.aviatickets.fragment.OfferListFragment class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) supportFragmentManager .beginTransaction() .add(R.id.fragment_container_view, OfferListFragment.newInstance()) .commit() } }
AndroidMidka/app/src/main/java/com/example/aviatickets/adapter/OfferListAdapter.kt
2327975229
package com.example.aviatickets.adapter import android.os.Bundle import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.aviatickets.R import com.example.aviatickets.databinding.ItemOfferBinding import com.example.aviatickets.model.entity.Offer class OfferListAdapter : RecyclerView.Adapter<OfferListAdapter.ViewHolder>() { private val items: ArrayList<Offer> = arrayListOf() fun setItems(offerList: List<Offer>) { items.clear() items.addAll(offerList) notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( ItemOfferBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun getItemCount(): Int { return items.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(items[position]) } fun sortByPrice() { items.sortBy { it.price } notifyDataSetChanged() } fun sortByDuration() { items.sortBy { it.flight.duration } notifyDataSetChanged() } inner class ViewHolder( private val binding: ItemOfferBinding ) : RecyclerView.ViewHolder(binding.root) { private val context = binding.root.context fun bind(offer: Offer) { val flight = offer.flight with(binding) { Glide.with(itemView) .load(flight.airline.logoUrl) // Replace with the actual URL or resource identifier .into(airlineLogoImageView) departureTime.text = flight.departureTimeInfo arrivalTime.text = flight.arrivalTimeInfo route.text = context.getString( R.string.route_fmt, flight.departureLocation.code, flight.arrivalLocation.code ) duration.text = context.getString( R.string.time_fmt, getTimeFormat(flight.duration).first.toString(), getTimeFormat(flight.duration).second.toString() ) direct.text = context.getString(R.string.direct) price.text = context.getString(R.string.price_fmt, offer.price.toString()) } } private fun getTimeFormat(minutes: Int): Pair<Int, Int> = Pair( first = minutes / 60, second = minutes % 60 ) } } class OfferDiffCallback : DiffUtil.ItemCallback<Offer>() { override fun areItemsTheSame(oldItem: Offer, newItem: Offer): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: Offer, newItem: Offer): Boolean { return oldItem == newItem } override fun getChangePayload(oldItem: Offer, newItem: Offer): Any? { val diffBundle = Bundle() if (oldItem.price != newItem.price) { diffBundle.putDouble("price", newItem.price.toDouble()) } if (oldItem.flight.duration != newItem.flight.duration) { diffBundle.putInt("duration", newItem.flight.duration) } return if (diffBundle.isEmpty) null else diffBundle } }
AndroidMidka/app/src/main/java/com/example/aviatickets/fragment/OfferListFragment.kt
1867984000
package com.example.aviatickets.fragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.lifecycle.lifecycleScope import com.example.aviatickets.R import com.example.aviatickets.adapter.OfferListAdapter import com.example.aviatickets.databinding.FragmentOfferListBinding import com.example.aviatickets.model.entity.Offer import com.example.aviatickets.model.network.ApiClient import com.example.aviatickets.model.service.FakeService import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import retrofit2.HttpException class OfferListFragment : Fragment() { companion object { fun newInstance() = OfferListFragment() } private var _binding: FragmentOfferListBinding? = null private val binding get() = _binding!! private val adapter: OfferListAdapter by lazy { OfferListAdapter() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentOfferListBinding.inflate(layoutInflater, container, false) return _binding?.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupUI() adapter.setItems(FakeService.offerList) } private fun setupUI() { with(binding) { offerList.adapter = adapter sortRadioGroup.setOnCheckedChangeListener { _, checkedId -> when (checkedId) { R.id.sort_by_price -> { adapter.sortByPrice() } R.id.sort_by_duration -> { adapter.sortByDuration() } } } fetchOfferList() } } private fun fetchOfferList() { lifecycleScope.launch(Dispatchers.IO) { try { val response = ApiClient.apiService.getOffers() if (response.isSuccessful) { val offerResponse = response.body() val offerList = offerResponse?.offers ?: emptyList() updateOfferList(offerList) } else { showError("Failed to fetch offers: ${response.errorBody()}") } } catch (e: HttpException) { showError("HTTP error occurred: ${e.message()}") } catch (e: Throwable) { showError("An error occurred: ${e.message}") } } } private fun updateOfferList(offers: List<Offer>) { requireActivity().runOnUiThread { adapter.setItems(offers) } } private fun showError(message: String) { requireActivity().runOnUiThread { Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show() } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
AndroidMidka/app/src/main/java/com/example/aviatickets/model/entity/Location.kt
1503829551
package com.example.aviatickets.model.entity data class Location( val cityName: String, val code: String )
AndroidMidka/app/src/main/java/com/example/aviatickets/model/entity/Offer.kt
872707810
package com.example.aviatickets.model.entity data class Offer( val id: String, val price: Int, val flight: Flight )
AndroidMidka/app/src/main/java/com/example/aviatickets/model/entity/OfferResponse.kt
4049189158
package com.example.aviatickets.model.entity data class OfferResponse( val offers: List<Offer> )
AndroidMidka/app/src/main/java/com/example/aviatickets/model/entity/Airline.kt
1976328334
package com.example.aviatickets.model.entity data class Airline( val name: String, val code: String val logoUrl: String )
AndroidMidka/app/src/main/java/com/example/aviatickets/model/entity/ApiService.kt
3630993577
package com.example.aviatickets.model.entity import retrofit2.Response import retrofit2.http.GET interface ApiService { @GET("offers") suspend fun getOffers(): Response<OfferResponse> }
AndroidMidka/app/src/main/java/com/example/aviatickets/model/entity/Flight.kt
3657800238
package com.example.aviatickets.model.entity /** * think about json deserialization considering its snake_case format */ data class Flight( val departureLocation: Location, val arrivalLocation: Location, val departureTimeInfo: String, val arrivalTimeInfo: String, val flightNumber: String, val airline: Airline, val duration: Int )
AndroidMidka/app/src/main/java/com/example/aviatickets/model/network/ApiClient.kt
1709923541
package com.example.aviatickets.model.network import com.example.aviatickets.model.entity.ApiService import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object ApiClient { private val retrofit = Retrofit.Builder() .baseUrl("YOUR_BASE_URL") .addConverterFactory(GsonConverterFactory.create()) .build() val apiService: ApiService = retrofit.create(ApiService::class.java) }
AndroidMidka/app/src/main/java/com/example/aviatickets/model/service/FakeService.kt
96052179
package com.example.aviatickets.model.service import com.example.aviatickets.model.entity.Airline import com.example.aviatickets.model.entity.Flight import com.example.aviatickets.model.entity.Location import com.example.aviatickets.model.entity.Offer import java.util.UUID object FakeService { val offerList = listOf( Offer( id = UUID.randomUUID().toString(), price = 24550, flight = Flight( departureLocation = Location( cityName = "ะะปะผะฐั‚ั‹", code = "ALA" ), departureTimeInfo = "20:30", arrivalLocation = Location( cityName = "ะัั‚ะฐะฝะฐ", code = "NQZ" ), arrivalTimeInfo = "22-30", flightNumber = "981", airline = Airline( name = "Air Astana", code = "KC", logoUrl = "https://avatars.mds.yandex.net/i?id=68fbf3d772010d0264b5ac697f097eb93e96dd20-10703102-images-thumbs&n=13" ), duration = 120 ) ), Offer( id = UUID.randomUUID().toString(), price = 16250, flight = Flight( departureLocation = Location( cityName = "ะะปะผะฐั‚ั‹", code = "ALA" ), departureTimeInfo = "16:00", arrivalLocation = Location( cityName = "ะัั‚ะฐะฝะฐ", code = "NQZ" ), arrivalTimeInfo = "18-00", flightNumber = "991", airline = Airline( name = "Air Astana", code = "KC", logoUrl = "https://avatars.mds.yandex.net/i?id=68fbf3d772010d0264b5ac697f097eb93e96dd20-10703102-images-thumbs&n=13" ), duration = 120 ) ), Offer( id = UUID.randomUUID().toString(), price = 8990, flight = Flight( departureLocation = Location( cityName = "ะะปะผะฐั‚ั‹", code = "ALA" ), departureTimeInfo = "09:30", arrivalLocation = Location( cityName = "ะัั‚ะฐะฝะฐ", code = "NQZ" ), arrivalTimeInfo = "11-10", flightNumber = "445", airline = Airline( name = "FlyArystan", code = "KC", logoUrl = "https://cdn.nur.kz/images/1200x675/5a2119bb0eb0649f.jpeg?version=1" ), duration = 100 ) ), Offer( id = UUID.randomUUID().toString(), price = 14440, flight = Flight( departureLocation = Location( cityName = "ะะปะผะฐั‚ั‹", code = "ALA" ), departureTimeInfo = "14:30", arrivalLocation = Location( cityName = "ะัั‚ะฐะฝะฐ", code = "NQZ" ), arrivalTimeInfo = "16-00", flightNumber = "223", airline = Airline( name = "SCAT Airlines", code = "DV", logoUrl = "https://avatars.mds.yandex.net/i?id=f6f32c04264e74d71cc7c3ab4a1341edd4ac8629-12496607-images-thumbs&n=13" ), duration = 90 ) ), Offer( id = UUID.randomUUID().toString(), price = 15100, flight = Flight( departureLocation = Location( cityName = "ะะปะผะฐั‚ั‹", code = "ALA" ), departureTimeInfo = "18:00", arrivalLocation = Location( cityName = "ะัั‚ะฐะฝะฐ", code = "NQZ" ), arrivalTimeInfo = "20:15", flightNumber = "171", airline = Airline( name = "QazaqAir", code = "IQ", logoUrl = "https://sun1-17.userapi.com/s/v1/if1/2JcXOGBXu9Ap3EAYoqDexW2yw5FPcBEIlwvvVafpj4SJZqmQriZ0r6B9tpymT15wqnP8Zw.jpg?size=1535x1535&quality=96&crop=0,0,1535,1535&ava=1" ), duration = 135 ) ) ) }
CoApi/spring-boot-starter/src/test/kotlin/me/ahoo/coapi/spring/boot/starter/CoApiPropertiesTest.kt
2989523101
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring.boot.starter import me.ahoo.coapi.spring.client.ClientProperties import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers import org.hamcrest.Matchers.equalTo import org.hamcrest.Matchers.sameInstance import org.junit.jupiter.api.Test class CoApiPropertiesTest { @Test fun getEnabled() { val properties = CoApiProperties() assertThat(properties.enabled, equalTo(true)) } @Test fun setEnabled() { val properties = CoApiProperties(false) properties.enabled = true assertThat(properties.enabled, equalTo(true)) } @Test fun getBasePackages() { val properties = CoApiProperties() assertThat(properties.basePackages, Matchers.empty()) } @Test fun getFilterIfDefault() { val properties = CoApiProperties() assertThat(properties.getFilter("test").names, Matchers.empty()) assertThat(properties.getFilter("test").types, Matchers.empty()) } @Test fun getFilter() { val properties = CoApiProperties( clients = mutableMapOf( "test" to ClientDefinition( reactive = ReactiveClientDefinition( filter = ClientProperties.FilterDefinition( listOf("test") ) ) ) ) ) assertThat(properties.getFilter("test").names, Matchers.hasSize(1)) assertThat(properties.getFilter("test").types, Matchers.empty()) } @Test fun getInterceptor() { val properties = CoApiProperties() assertThat(properties.getInterceptor("test").names, Matchers.empty()) assertThat(properties.getInterceptor("test").types, Matchers.empty()) } @Test fun setClientDefinition() { val properties = ClientDefinition() val reactive = ReactiveClientDefinition() properties.reactive = reactive assertThat(properties.reactive, sameInstance(reactive)) val sync = SyncClientDefinition() properties.sync = sync assertThat(properties.sync, sameInstance(sync)) } @Test fun setReactiveClientDefinition() { val properties = ReactiveClientDefinition() val filter = ClientProperties.FilterDefinition() properties.filter = filter assertThat(properties.filter, sameInstance(filter)) } @Test fun setSyncClientDefinition() { val properties = SyncClientDefinition() val interceptor = ClientProperties.InterceptorDefinition() properties.interceptor = interceptor assertThat(properties.interceptor, sameInstance(interceptor)) } }
CoApi/spring-boot-starter/src/test/kotlin/me/ahoo/coapi/spring/boot/starter/CoApiAutoConfigurationTest.kt
1439960364
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring.boot.starter import io.mockk.mockk import me.ahoo.coapi.example.consumer.client.GitHubApiClient import me.ahoo.coapi.example.consumer.client.ServiceApiClient import me.ahoo.coapi.example.consumer.client.ServiceApiClientUseFilterBeanName import me.ahoo.coapi.example.consumer.client.ServiceApiClientUseFilterType import me.ahoo.coapi.example.provider.client.TodoClient import me.ahoo.coapi.spring.ClientMode import me.ahoo.coapi.spring.EnableCoApi import me.ahoo.coapi.spring.client.reactive.ReactiveHttpExchangeAdapterFactory import me.ahoo.coapi.spring.client.sync.SyncHttpExchangeAdapterFactory import org.assertj.core.api.AssertionsForInterfaceTypes import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.hamcrest.Matchers.notNullValue import org.junit.jupiter.api.Test import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration import org.springframework.boot.test.context.runner.ApplicationContextRunner import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor import org.springframework.cloud.client.loadbalancer.reactive.LoadBalancedExchangeFilterFunction class CoApiAutoConfigurationTest { private val filterNamePropertyK = "coapi.clients.ServiceApiClientUseFilterBeanName.reactive.filter.names" private val filterNameProperty = "$filterNamePropertyK=loadBalancerExchangeFilterFunction" private val filterTypePropertyK = "coapi.clients.ServiceApiClientUseFilterType.reactive.filter.types" private val filterTypeProperty = "$filterTypePropertyK=org.springframework.cloud.client.loadbalancer.reactive.LoadBalancedExchangeFilterFunction" private val interceptorNamePropertyK = "coapi.clients.ServiceApiClientUseFilterBeanName.sync.interceptor.names" private val interceptorNameProperty = "$interceptorNamePropertyK=loadBalancerInterceptor" private val interceptorTypePropertyK = "coapi.clients.ServiceApiClientUseFilterType.sync.interceptor.types" private val interceptorTypeProperty = "$interceptorTypePropertyK=org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor" @Test fun `should create Reactive CoApi bean`() { ApplicationContextRunner() .withPropertyValues("github.url=https://api.github.com") .withPropertyValues(filterNameProperty) .withPropertyValues(filterTypeProperty) .withBean("loadBalancerExchangeFilterFunction", LoadBalancedExchangeFilterFunction::class.java, { mockk() }) .withUserConfiguration(WebClientAutoConfiguration::class.java) .withUserConfiguration(EnableCoApiConfiguration::class.java) .withUserConfiguration(CoApiAutoConfiguration::class.java) .run { context -> AssertionsForInterfaceTypes.assertThat(context) .hasSingleBean(ReactiveHttpExchangeAdapterFactory::class.java) .hasSingleBean(GitHubApiClient::class.java) .hasSingleBean(ServiceApiClient::class.java) val coApiProperties = context.getBean(CoApiProperties::class.java) assertThat(coApiProperties.mode, equalTo(ClientMode.AUTO)) assertThat(coApiProperties.clients["ServiceApiClientUseFilterBeanName"], notNullValue()) context.getBean(GitHubApiClient::class.java) context.getBean(ServiceApiClient::class.java) context.getBean(ServiceApiClientUseFilterBeanName::class.java) context.getBean(ServiceApiClientUseFilterType::class.java) } } @Test fun `should create Sync CoApi bean`() { ApplicationContextRunner() .withPropertyValues("${ClientMode.COAPI_CLIENT_MODE_PROPERTY}=SYNC") .withPropertyValues("github.url=https://api.github.com") .withPropertyValues(interceptorNameProperty) .withPropertyValues(interceptorTypeProperty) .withBean("loadBalancerInterceptor", LoadBalancerInterceptor::class.java, { mockk() }) .withUserConfiguration(EnableCoApiConfiguration::class.java) .withUserConfiguration(CoApiAutoConfiguration::class.java) .run { context -> AssertionsForInterfaceTypes.assertThat(context) .hasSingleBean(SyncHttpExchangeAdapterFactory::class.java) .hasSingleBean(GitHubApiClient::class.java) .hasSingleBean(ServiceApiClient::class.java) val coApiProperties = context.getBean(CoApiProperties::class.java) assertThat(coApiProperties.mode, equalTo(ClientMode.SYNC)) context.getBean(GitHubApiClient::class.java) context.getBean(ServiceApiClient::class.java) context.getBean(ServiceApiClientUseFilterBeanName::class.java) context.getBean(ServiceApiClientUseFilterType::class.java) } } @Test fun basePackages() { ApplicationContextRunner() .withPropertyValues("github.url=https://api.github.com") .withPropertyValues("${CoApiProperties.COAPI_BASE_PACKAGES}=me.ahoo.coapi.spring.boot.starter") .withPropertyValues(filterNameProperty) .withPropertyValues(filterTypeProperty) .withBean("loadBalancerExchangeFilterFunction", LoadBalancedExchangeFilterFunction::class.java, { mockk() }) .withUserConfiguration(WebClientAutoConfiguration::class.java) .withUserConfiguration(CoApiAutoConfiguration::class.java) .run { context -> AssertionsForInterfaceTypes.assertThat(context) .hasSingleBean(ReactiveHttpExchangeAdapterFactory::class.java) .hasSingleBean(me.ahoo.coapi.spring.boot.starter.GitHubApiClient::class.java) } } @Test fun basePackagesMultiple() { ApplicationContextRunner() .withPropertyValues("github.url=https://api.github.com") .withPropertyValues( "${CoApiProperties.COAPI_BASE_PACKAGES}=me.ahoo.coapi.spring.boot.starter" + ",me.ahoo.coapi.example.consumer.client" ) .withPropertyValues(filterNameProperty) .withPropertyValues(filterTypeProperty) .withBean("loadBalancerExchangeFilterFunction", LoadBalancedExchangeFilterFunction::class.java, { mockk() }) .withUserConfiguration(WebClientAutoConfiguration::class.java) .withUserConfiguration(CoApiAutoConfiguration::class.java) .run { context -> AssertionsForInterfaceTypes.assertThat(context) .hasSingleBean(ReactiveHttpExchangeAdapterFactory::class.java) .hasSingleBean(me.ahoo.coapi.spring.boot.starter.GitHubApiClient::class.java) .hasSingleBean(ServiceApiClient::class.java) } } @Test fun basePackagesYaml() { ApplicationContextRunner() .withPropertyValues("github.url=https://api.github.com") .withPropertyValues( "${CoApiProperties.COAPI_BASE_PACKAGES}[0]=me.ahoo.coapi.spring.boot.starter" ) .withPropertyValues( "${CoApiProperties.COAPI_BASE_PACKAGES}[1]=me.ahoo.coapi.example.consumer.client" ) .withPropertyValues(filterNameProperty) .withPropertyValues(filterTypeProperty) .withBean("loadBalancerExchangeFilterFunction", LoadBalancedExchangeFilterFunction::class.java, { mockk() }) .withUserConfiguration(WebClientAutoConfiguration::class.java) .withUserConfiguration(CoApiAutoConfiguration::class.java) .run { context -> AssertionsForInterfaceTypes.assertThat(context) .hasSingleBean(ReactiveHttpExchangeAdapterFactory::class.java) .hasSingleBean(me.ahoo.coapi.spring.boot.starter.GitHubApiClient::class.java) .hasSingleBean(ServiceApiClient::class.java) } } } @SpringBootApplication @EnableCoApi( clients = [ GitHubApiClient::class, ServiceApiClient::class, ServiceApiClientUseFilterBeanName::class, ServiceApiClientUseFilterType::class, TodoClient::class, me.ahoo.coapi.spring.boot.starter.GitHubApiClient::class ] ) class EnableCoApiConfiguration
CoApi/spring-boot-starter/src/test/kotlin/me/ahoo/coapi/spring/boot/starter/GitHubApiClient.kt
699149446
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring.boot.starter import me.ahoo.coapi.api.CoApi import me.ahoo.coapi.example.consumer.client.Issue import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.service.annotation.GetExchange import reactor.core.publisher.Flux @CoApi(baseUrl = "\${github.url}") interface GitHubApiClient { @GetExchange("repos/{owner}/{repo}/issues") fun getIssue(@PathVariable owner: String, @PathVariable repo: String): Flux<Issue> }
CoApi/spring-boot-starter/src/main/kotlin/me/ahoo/coapi/spring/boot/starter/ConditionalOnCoApiEnabled.kt
1004294322
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring.boot.starter import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty @ConditionalOnProperty( value = [ConditionalOnCoApiEnabled.ENABLED_KEY], matchIfMissing = true, havingValue = "true", ) annotation class ConditionalOnCoApiEnabled { companion object { const val ENABLED_KEY: String = COAPI_PREFIX + ENABLED_SUFFIX_KEY } }
CoApi/spring-boot-starter/src/main/kotlin/me/ahoo/coapi/spring/boot/starter/AutoCoApiRegistrar.kt
3830492959
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring.boot.starter import me.ahoo.coapi.api.CoApi import me.ahoo.coapi.spring.AbstractCoApiRegistrar import me.ahoo.coapi.spring.CoApiDefinition import me.ahoo.coapi.spring.CoApiDefinition.Companion.toCoApiDefinition import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition import org.springframework.boot.autoconfigure.AutoConfigurationPackages import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider import org.springframework.core.env.Environment import org.springframework.core.type.AnnotationMetadata import org.springframework.core.type.filter.AnnotationTypeFilter class AutoCoApiRegistrar : AbstractCoApiRegistrar() { private fun getCoApiBasePackages(): List<String> { val basePackages = env.getProperty(CoApiProperties.COAPI_BASE_PACKAGES) if (basePackages?.isNotBlank() == true) { return basePackages.split(",").distinct().toList() } var currentIndex = 0 buildList { while (true) { val basePackage = env.getProperty("${CoApiProperties.COAPI_BASE_PACKAGES}[$currentIndex]") if (basePackage.isNullOrBlank()) { return this } add(basePackage) currentIndex++ } } } private fun getScanBasePackages(): List<String> { val coApiBasePackages = getCoApiBasePackages() if (coApiBasePackages.isNotEmpty()) { return coApiBasePackages } return AutoConfigurationPackages.get(appContext) + coApiBasePackages } override fun getCoApiDefinitions(importingClassMetadata: AnnotationMetadata): Set<CoApiDefinition> { val scanBasePackages = getScanBasePackages() return scanBasePackages.toApiClientDefinitions() } private fun List<String>.toApiClientDefinitions(): Set<CoApiDefinition> { val scanner = ApiClientScanner(false, env) return flatMap { basePackage -> scanner.findCandidateComponents(basePackage) }.map { beanDefinition -> Class.forName(beanDefinition.beanClassName).toCoApiDefinition(env) }.toSet() } } class ApiClientScanner(useDefaultFilters: Boolean, environment: Environment) : ClassPathScanningCandidateComponentProvider(useDefaultFilters, environment) { init { addIncludeFilter(AnnotationTypeFilter(CoApi::class.java)) } override fun isCandidateComponent(beanDefinition: AnnotatedBeanDefinition): Boolean { return beanDefinition.metadata.isInterface } }
CoApi/spring-boot-starter/src/main/kotlin/me/ahoo/coapi/spring/boot/starter/CoApiAutoConfiguration.kt
210276749
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring.boot.starter import org.springframework.boot.autoconfigure.AutoConfiguration import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.annotation.Import @AutoConfiguration @ConditionalOnCoApiEnabled @Import(AutoCoApiRegistrar::class) @EnableConfigurationProperties(CoApiProperties::class) class CoApiAutoConfiguration
CoApi/spring-boot-starter/src/main/kotlin/me/ahoo/coapi/spring/boot/starter/CoApiProperties.kt
300603511
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring.boot.starter import me.ahoo.coapi.spring.ClientMode import me.ahoo.coapi.spring.client.ClientProperties import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.boot.context.properties.bind.DefaultValue const val COAPI_PREFIX = "coapi" const val ENABLED_SUFFIX_KEY = ".enabled" @ConfigurationProperties(prefix = COAPI_PREFIX) data class CoApiProperties( @DefaultValue("true") var enabled: Boolean = true, val mode: ClientMode = ClientMode.AUTO, val basePackages: List<String> = emptyList(), val clients: Map<String, ClientDefinition> = emptyMap(), ) : ClientProperties { companion object { const val COAPI_BASE_PACKAGES = "$COAPI_PREFIX.base-packages" } override fun getFilter(coApiName: String): ClientProperties.FilterDefinition { return clients[coApiName]?.reactive?.filter ?: ClientProperties.FilterDefinition() } override fun getInterceptor(coApiName: String): ClientProperties.InterceptorDefinition { return clients[coApiName]?.sync?.interceptor ?: ClientProperties.InterceptorDefinition() } } data class ClientDefinition( var reactive: ReactiveClientDefinition = ReactiveClientDefinition(), var sync: SyncClientDefinition = SyncClientDefinition() ) data class ReactiveClientDefinition( var filter: ClientProperties.FilterDefinition = ClientProperties.FilterDefinition() ) data class SyncClientDefinition( var interceptor: ClientProperties.InterceptorDefinition = ClientProperties.InterceptorDefinition() )
CoApi/example/example-sync/src/test/kotlin/me/ahoo/coapi/example/sync/ExampleServerTest.kt
954994990
package me.ahoo.coapi.example.sync import me.ahoo.coapi.spring.client.sync.SyncHttpExchangeAdapterFactory import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.notNullValue import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class ExampleServerTest { @Autowired private lateinit var httpExchangeAdapterFactory: SyncHttpExchangeAdapterFactory @Autowired private lateinit var gitHubApiClient: GitHubSyncClient @Autowired private lateinit var serviceApiClient: GitHubSyncLbClient @Test fun httpExchangeAdapterFactoryIsNotNull() { assertThat(httpExchangeAdapterFactory, notNullValue()) } @Test fun getIssueByGitHubApiClient() { gitHubApiClient.getIssue("Ahoo-Wang", "Wow") } @Test fun getIssueByServiceApiClient() { serviceApiClient.getIssue("Ahoo-Wang", "Wow") } }
CoApi/example/example-sync/src/main/kotlin/me/ahoo/coapi/example/sync/ExampleSyncServer.kt
490885905
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.example.sync import me.ahoo.coapi.spring.EnableCoApi import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @EnableCoApi( clients = [ GitHubSyncClient::class ] ) @SpringBootApplication class ExampleSyncServer fun main(args: Array<String>) { runApplication<ExampleSyncServer>(*args) }
CoApi/example/example-sync/src/main/kotlin/me/ahoo/coapi/example/sync/GithubController.kt
871563184
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.example.sync import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController import org.springframework.web.service.annotation.HttpExchange import reactor.core.publisher.Flux @RestController @HttpExchange("github") class GithubController( private val gitHubApiClient: GitHubSyncClient, private val gitHubLbApiClient: GitHubSyncLbClient ) { @GetMapping("/baseUrl") fun baseUrl(): List<Issue> { return gitHubApiClient.getIssue("Ahoo-Wang", "Wow") } @GetMapping("/getIssueWithReactive") fun getIssueWithReactive(): Flux<Issue> { return gitHubApiClient.getIssueWithReactive("Ahoo-Wang", "Wow") } @GetMapping("/serviceId") fun serviceId(): List<Issue> { return gitHubLbApiClient.getIssue("Ahoo-Wang", "Wow") } }
CoApi/example/example-consumer-client/src/main/kotlin/me/ahoo/coapi/example/consumer/client/UriApiClient.kt
192015646
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.example.consumer.client import me.ahoo.coapi.api.CoApi import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.service.annotation.GetExchange import org.springframework.web.util.UriBuilderFactory import reactor.core.publisher.Flux import java.net.URI @CoApi interface UriApiClient { @GetExchange fun getIssueByUri(uri: URI): Flux<Issue> @GetExchange fun getIssue( uriBuilderFactory: UriBuilderFactory, @PathVariable owner: String, @PathVariable repo: String ): Flux<Issue> }
CoApi/example/example-consumer-client/src/main/kotlin/me/ahoo/coapi/example/consumer/client/ServiceApiClientUseFilterBeanName.kt
461417008
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.example.consumer.client import me.ahoo.coapi.api.CoApi import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.service.annotation.GetExchange import reactor.core.publisher.Flux @CoApi(serviceId = "github-service") interface ServiceApiClientUseFilterBeanName { @GetExchange("repos/{owner}/{repo}/issues") fun getIssue(@PathVariable owner: String, @PathVariable repo: String): Flux<Issue> }
CoApi/example/example-consumer-client/src/main/kotlin/me/ahoo/coapi/example/consumer/client/GitHubApiClient.kt
3273455200
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.example.consumer.client import me.ahoo.coapi.api.CoApi import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.service.annotation.GetExchange import reactor.core.publisher.Flux @CoApi(baseUrl = "\${github.url}") interface GitHubApiClient { @GetExchange("repos/{owner}/{repo}/issues") fun getIssue(@PathVariable owner: String, @PathVariable repo: String): Flux<Issue> } data class Issue( val url: String )
CoApi/example/example-consumer-client/src/main/kotlin/me/ahoo/coapi/example/consumer/client/ServiceApiClient.kt
1530580526
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.example.consumer.client import me.ahoo.coapi.api.CoApi import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.service.annotation.GetExchange import reactor.core.publisher.Flux @CoApi(serviceId = "github-service", name = "GitHubApi") interface ServiceApiClient { @GetExchange("repos/{owner}/{repo}/issues") fun getIssue(@PathVariable owner: String, @PathVariable repo: String): Flux<Issue> }
CoApi/example/example-consumer-client/src/main/kotlin/me/ahoo/coapi/example/consumer/client/ServiceApiClientUseFilterType.kt
2764826712
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.example.consumer.client import me.ahoo.coapi.api.CoApi import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.service.annotation.GetExchange import reactor.core.publisher.Flux @CoApi(serviceId = "github-service") interface ServiceApiClientUseFilterType { @GetExchange("repos/{owner}/{repo}/issues") fun getIssue(@PathVariable owner: String, @PathVariable repo: String): Flux<Issue> }
CoApi/example/example-provider-server/src/test/kotlin/me/ahoo/coapi/example/provider/ProviderServerTest.kt
1537996663
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.example.provider import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class ProviderServerTest { @Test fun contextLoads() = Unit }
CoApi/example/example-provider-server/src/main/kotlin/me/ahoo/coapi/example/provider/TodoController.kt
859105160
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.example.provider import me.ahoo.coapi.example.provider.api.Todo import me.ahoo.coapi.example.provider.api.TodoApi import org.springframework.web.bind.annotation.RestController import reactor.core.publisher.Flux @RestController class TodoController : TodoApi { override fun getTodo(): Flux<Todo> { return Flux.range(1, 10) .map { Todo("todo-$it") } } }
CoApi/example/example-provider-server/src/main/kotlin/me/ahoo/coapi/example/provider/ProviderServer.kt
213890560
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.example.provider import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class ProviderServer fun main(args: Array<String>) { runApplication<ProviderServer>(*args) }
CoApi/example/example-consumer-server/src/test/kotlin/me/ahoo/coapi/example/consumer/ConsumerServerTest.kt
2713844427
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.example.consumer import me.ahoo.coapi.example.consumer.client.GitHubApiClient import me.ahoo.coapi.example.consumer.client.ServiceApiClient import me.ahoo.coapi.spring.client.reactive.ReactiveHttpExchangeAdapterFactory import org.hamcrest.MatcherAssert import org.hamcrest.Matchers import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class ConsumerServerTest { @Autowired private lateinit var httpExchangeAdapterFactory: ReactiveHttpExchangeAdapterFactory @Autowired private lateinit var gitHubApiClient: GitHubApiClient @Autowired private lateinit var serviceApiClient: ServiceApiClient @Test fun httpExchangeAdapterFactoryIsNotNull() { MatcherAssert.assertThat(httpExchangeAdapterFactory, Matchers.notNullValue()) } @Test fun getIssueByGitHubApiClient() { gitHubApiClient.getIssue("Ahoo-Wang", "Wow") .doOnNext { println(it) } .blockLast() } @Test fun getIssueByServiceApiClient() { serviceApiClient.getIssue("Ahoo-Wang", "Wow") .doOnNext { println(it) } .blockLast() } }
CoApi/example/example-consumer-server/src/main/kotlin/me/ahoo/coapi/example/consumer/TodoController.kt
2638675102
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.example.consumer import me.ahoo.coapi.example.provider.api.Todo import me.ahoo.coapi.example.provider.client.TodoClient import org.springframework.web.bind.annotation.RestController import org.springframework.web.service.annotation.GetExchange import org.springframework.web.service.annotation.HttpExchange import reactor.core.publisher.Flux @RestController @HttpExchange("todo") class TodoController(private val todoClient: TodoClient) { @GetExchange fun getProviderTodo(): Flux<Todo> { return todoClient.getTodo() } }
CoApi/example/example-consumer-server/src/main/kotlin/me/ahoo/coapi/example/consumer/GithubController.kt
139485322
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.example.consumer import me.ahoo.coapi.example.consumer.client.GitHubApiClient import me.ahoo.coapi.example.consumer.client.Issue import me.ahoo.coapi.example.consumer.client.ServiceApiClient import me.ahoo.coapi.example.consumer.client.UriApiClient import org.slf4j.LoggerFactory import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController import org.springframework.web.reactive.function.client.WebClientResponseException import org.springframework.web.service.annotation.GetExchange import org.springframework.web.service.annotation.HttpExchange import org.springframework.web.util.DefaultUriBuilderFactory import reactor.core.publisher.Flux import java.net.URI @RestController @HttpExchange("github") class GithubController( private val gitHubApiClient: GitHubApiClient, private val serviceApiClient: ServiceApiClient, private val uriApiClient: UriApiClient ) { companion object { private val log = LoggerFactory.getLogger(GithubController::class.java) } @GetMapping("/baseUrl") fun baseUrl(): Flux<Issue> { return gitHubApiClient.getIssue("Ahoo-Wang", "Wow") } @GetExchange("/serviceId") fun serviceId(): Flux<Issue> { return serviceApiClient.getIssue("Ahoo-Wang", "CoApi").doOnError(WebClientResponseException::class.java) { log.error(it.responseBodyAsString) } } @GetExchange("/uri") fun uri(): Flux<Issue> { val uri = URI.create("https://api.github.com/repos/Ahoo-Wang/CoApi/issues") return uriApiClient.getIssueByUri(uri) } @GetExchange("/uriBuilder") fun uriBuilder(): Flux<Issue> { val uriBuilderFactory = DefaultUriBuilderFactory("https://api.github.com/repos/{owner}/{repo}/issues") return uriApiClient.getIssue(uriBuilderFactory, "Ahoo-Wang", "Wow") } }
CoApi/example/example-consumer-server/src/main/kotlin/me/ahoo/coapi/example/consumer/ConsumerServer.kt
2868344424
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.example.consumer import me.ahoo.coapi.example.consumer.client.GitHubApiClient import me.ahoo.coapi.example.consumer.client.ServiceApiClient import me.ahoo.coapi.example.consumer.client.ServiceApiClientUseFilterBeanName import me.ahoo.coapi.example.consumer.client.ServiceApiClientUseFilterType import me.ahoo.coapi.example.consumer.client.UriApiClient import me.ahoo.coapi.example.provider.client.TodoClient import me.ahoo.coapi.spring.EnableCoApi import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @EnableCoApi( clients = [ GitHubApiClient::class, ServiceApiClient::class, ServiceApiClientUseFilterBeanName::class, ServiceApiClientUseFilterType::class, UriApiClient::class, TodoClient::class ] ) @SpringBootApplication class ConsumerServer fun main(args: Array<String>) { runApplication<ConsumerServer>(*args) }
CoApi/example/example-provider-api/src/main/kotlin/me/ahoo/coapi/example/provider/api/TodoApi.kt
915426880
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.example.provider.api import org.springframework.web.service.annotation.GetExchange import org.springframework.web.service.annotation.HttpExchange import reactor.core.publisher.Flux @HttpExchange("todo") interface TodoApi { @GetExchange fun getTodo(): Flux<Todo> } data class Todo(val title: String)
CoApi/example/example-provider-api/src/main/kotlin/me/ahoo/coapi/example/provider/client/TodoClient.kt
2968660814
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.example.provider.client import me.ahoo.coapi.api.CoApi import me.ahoo.coapi.example.provider.api.TodoApi @CoApi(serviceId = "provider-service") interface TodoClient : TodoApi
CoApi/api/src/main/kotlin/me/ahoo/coapi/api/CoApi.kt
953783909
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.api import org.springframework.stereotype.Component @Target(AnnotationTarget.CLASS) @Component annotation class CoApi( val serviceId: String = "", val baseUrl: String = "", val name: String = "" )
CoApi/spring/src/test/kotlin/me/ahoo/coapi/spring/ClientModeTest.kt
2404528347
package me.ahoo.coapi.spring import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.junit.jupiter.api.Test class ClientModeTest { @Test fun inferClientModeIfNull() { val mode = ClientMode.inferClientMode { null } assertThat(mode, equalTo(ClientMode.REACTIVE)) } @Test fun inferClientMode() { val mode = ClientMode.inferClientMode { "SYNC" } assertThat(mode, equalTo(ClientMode.SYNC)) } }
CoApi/spring/src/test/kotlin/me/ahoo/coapi/spring/CoApiDefinitionTest.kt
1302957722
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring import io.mockk.mockk import me.ahoo.coapi.spring.CoApiDefinition.Companion.toCoApiDefinition import org.junit.jupiter.api.Test class CoApiDefinitionTest { @Test fun toCoApiDefinitionIfNoCoApi() { org.junit.jupiter.api.assertThrows<IllegalArgumentException> { CoApiDefinitionTest::class.java.toCoApiDefinition(mockk()) } } }
CoApi/spring/src/test/kotlin/me/ahoo/coapi/spring/client/reactive/auth/JwtFixture.kt
778747356
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring.client.reactive.auth import com.auth0.jwt.JWT import com.auth0.jwt.algorithms.Algorithm import java.util.Date object JwtFixture { var ALGORITHM = Algorithm.HMAC256("FyN0Igd80Gas8stTavArGKOYnS9uLWGA_") fun generateToken(expiresAt: Date): String { val accessTokenBuilder = JWT.create() .withExpiresAt(expiresAt) return accessTokenBuilder.sign(ALGORITHM) } }
CoApi/spring/src/test/kotlin/me/ahoo/coapi/spring/client/reactive/auth/CachedExpirableTokenProviderTest.kt
1013220009
package me.ahoo.coapi.spring.client.reactive.auth import me.ahoo.coapi.spring.client.reactive.auth.ExpirableToken.Companion.jwtToExpirableToken import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.junit.jupiter.api.Test import reactor.core.publisher.Mono import reactor.kotlin.test.test import java.util.* class CachedExpirableTokenProviderTest { @Test fun getBearerToken() { val cachedExpirableTokenProvider = CachedExpirableTokenProvider(MockBearerTokenProvider) cachedExpirableTokenProvider.getToken() .test() .consumeNextWith { // ไป…ๅฝ“็ผ“ๅญ˜ๅฝ“ๅ‰ๅทฒๅกซๅ……ๆ—ถๆ‰ไผš่ฏ„ไผฐ assertThat(it, equalTo(MockBearerTokenProvider.expiredToken)) }.verifyComplete() cachedExpirableTokenProvider.getToken() .test() .consumeNextWith { assertThat(it, equalTo(MockBearerTokenProvider.notExpiredToken)) }.verifyComplete() cachedExpirableTokenProvider.getToken() .test() .consumeNextWith { assertThat(it, equalTo(MockBearerTokenProvider.notExpiredToken)) }.verifyComplete() cachedExpirableTokenProvider.getToken() .test() .consumeNextWith { assertThat(it, equalTo(MockBearerTokenProvider.notExpiredToken)) }.verifyComplete() } object MockBearerTokenProvider : ExpirableTokenProvider { @Volatile private var isFistCall = true val expiredToken = JwtFixture .generateToken(Date(System.currentTimeMillis() - 10000)).jwtToExpirableToken() val notExpiredToken = JwtFixture .generateToken(Date(System.currentTimeMillis() + 10000)).jwtToExpirableToken() override fun getToken(): Mono<ExpirableToken> { return Mono.create { if (isFistCall) { isFistCall = false it.success(expiredToken) } else { it.success(notExpiredToken) } } } } }
CoApi/spring/src/test/kotlin/me/ahoo/coapi/spring/client/reactive/auth/BearerTokenFilterTest.kt
116512883
package me.ahoo.coapi.spring.client.reactive.auth import io.mockk.mockk import me.ahoo.coapi.spring.client.reactive.auth.BearerHeaderValueMapper.withBearerPrefix import me.ahoo.coapi.spring.client.reactive.auth.ExpirableToken.Companion.jwtToExpirableToken import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.junit.jupiter.api.Test import org.springframework.http.HttpHeaders import org.springframework.http.HttpMethod import org.springframework.web.reactive.function.client.ClientRequest import org.springframework.web.reactive.function.client.ExchangeFunction import reactor.core.publisher.Mono import reactor.kotlin.test.test import java.net.URI import java.util.* class BearerTokenFilterTest { @Test fun filter() { val clientRequest = ClientRequest .create(HttpMethod.GET, URI.create("http://localhost")) .build() val jwtToken = JwtFixture.generateToken(Date()) val nextException = ExchangeFunction { request -> assertThat(request.headers().getFirst(HttpHeaders.AUTHORIZATION), equalTo(jwtToken.withBearerPrefix())) Mono.empty() } val tokenProvider = object : ExpirableTokenProvider { override fun getToken(): Mono<ExpirableToken> { return Mono.just(jwtToken.jwtToExpirableToken()) } } val bearerTokenFilter = BearerTokenFilter(tokenProvider) bearerTokenFilter.filter(clientRequest, nextException) .test() .verifyComplete() } @Test fun filter_ContainsKey() { val jwtToken = JwtFixture.generateToken(Date()) val clientRequest = ClientRequest .create(HttpMethod.GET, URI.create("http://localhost")) .headers { it.setBearerAuth(jwtToken) } .build() val nextException = ExchangeFunction { request -> Mono.empty() } val tokenProvider = mockk<ExpirableTokenProvider>() val bearerTokenFilter = BearerTokenFilter(tokenProvider) bearerTokenFilter.filter(clientRequest, nextException) .test() .verifyComplete() } }
CoApi/spring/src/test/kotlin/me/ahoo/coapi/spring/CoApiContextTest.kt
3863073479
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring import io.mockk.mockk import me.ahoo.coapi.example.consumer.client.GitHubApiClient import me.ahoo.coapi.example.consumer.client.ServiceApiClient import me.ahoo.coapi.example.consumer.client.ServiceApiClientUseFilterBeanName import me.ahoo.coapi.example.consumer.client.ServiceApiClientUseFilterType import me.ahoo.coapi.example.provider.client.TodoClient import me.ahoo.coapi.spring.client.ClientProperties import me.ahoo.coapi.spring.client.reactive.ReactiveHttpExchangeAdapterFactory import me.ahoo.coapi.spring.client.reactive.WebClientBuilderCustomizer import me.ahoo.coapi.spring.client.sync.RestClientBuilderCustomizer import me.ahoo.coapi.spring.client.sync.SyncHttpExchangeAdapterFactory import org.assertj.core.api.AssertionsForInterfaceTypes import org.junit.jupiter.api.Test import org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration import org.springframework.boot.test.context.runner.ApplicationContextRunner import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor import org.springframework.cloud.client.loadbalancer.reactive.LoadBalancedExchangeFilterFunction import org.springframework.web.client.RestClient class CoApiContextTest { private val loadBalancedExchangeFilterName = ClientProperties.FilterDefinition(names = listOf("loadBalancerExchangeFilterFunction")) private val loadBalancedExchangeFilterType = ClientProperties.FilterDefinition(types = listOf(LoadBalancedExchangeFilterFunction::class.java)) private val loadBalancedExchangeInterceptorName = ClientProperties.InterceptorDefinition(names = listOf("loadBalancerInterceptor")) private val loadBalancedExchangeInterceptorType = ClientProperties.InterceptorDefinition(types = listOf(LoadBalancerInterceptor::class.java)) @Test fun `should create Reactive CoApi bean`() { ApplicationContextRunner() .withPropertyValues("github.url=https://api.github.com") .withBean("loadBalancerExchangeFilterFunction", LoadBalancedExchangeFilterFunction::class.java, { mockk() }) .withBean(WebClientBuilderCustomizer::class.java, { WebClientBuilderCustomizer.NoOp }) .withBean("clientProperties", ClientProperties::class.java, { MockClientProperties( filter = mapOf( "ServiceApiClientUseFilterBeanName" to loadBalancedExchangeFilterName, "ServiceApiClientUseFilterType" to loadBalancedExchangeFilterType ) ) }) .withUserConfiguration(WebClientAutoConfiguration::class.java) .withUserConfiguration(EnableCoApiConfiguration::class.java) .run { context -> AssertionsForInterfaceTypes.assertThat(context) .hasSingleBean(ReactiveHttpExchangeAdapterFactory::class.java) .hasSingleBean(GitHubApiClient::class.java) .hasSingleBean(ServiceApiClient::class.java) context.getBean(GitHubApiClient::class.java) context.getBean(ServiceApiClient::class.java) context.getBean(ServiceApiClientUseFilterBeanName::class.java) context.getBean(ServiceApiClientUseFilterType::class.java) } } @Test fun `should create Sync CoApi bean`() { ApplicationContextRunner() .withPropertyValues("${ClientMode.COAPI_CLIENT_MODE_PROPERTY}=SYNC") .withPropertyValues("github.url=https://api.github.com") .withBean("loadBalancerInterceptor", LoadBalancerInterceptor::class.java, { mockk() }) .withBean(RestClientBuilderCustomizer::class.java, { RestClientBuilderCustomizer.NoOp }) .withBean(RestClient.Builder::class.java, { RestClient.builder() }) .withBean("clientProperties", ClientProperties::class.java, { MockClientProperties( interceptor = mapOf( "ServiceApiClientUseFilterBeanName" to loadBalancedExchangeInterceptorName, "ServiceApiClientUseFilterType" to loadBalancedExchangeInterceptorType ) ) }) .withUserConfiguration(EnableCoApiConfiguration::class.java) .run { context -> AssertionsForInterfaceTypes.assertThat(context) .hasSingleBean(SyncHttpExchangeAdapterFactory::class.java) .hasSingleBean(GitHubApiClient::class.java) .hasSingleBean(ServiceApiClient::class.java) context.getBean(GitHubApiClient::class.java) context.getBean(ServiceApiClient::class.java) context.getBean(ServiceApiClientUseFilterBeanName::class.java) context.getBean(ServiceApiClientUseFilterType::class.java) } } } @EnableCoApi( clients = [ GitHubApiClient::class, ServiceApiClient::class, ServiceApiClientUseFilterBeanName::class, ServiceApiClientUseFilterType::class, TodoClient::class ] ) class EnableCoApiConfiguration data class MockClientProperties( val filter: Map<String, ClientProperties.FilterDefinition> = emptyMap(), val interceptor: Map<String, ClientProperties.InterceptorDefinition> = emptyMap(), ) : ClientProperties { override fun getFilter(coApiName: String): ClientProperties.FilterDefinition { return filter[coApiName] ?: ClientProperties.FilterDefinition() } override fun getInterceptor(coApiName: String): ClientProperties.InterceptorDefinition { return interceptor[coApiName] ?: ClientProperties.InterceptorDefinition() } }
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/EnableCoApi.kt
4095773428
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring import org.springframework.context.annotation.Import import kotlin.reflect.KClass @Import(EnableCoApiRegistrar::class) @Target(AnnotationTarget.CLASS) annotation class EnableCoApi( val clients: Array<KClass<*>> = [] )
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/CoApiRegistrar.kt
683385004
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring import me.ahoo.coapi.spring.client.reactive.LoadBalancedWebClientFactoryBean import me.ahoo.coapi.spring.client.reactive.WebClientFactoryBean import me.ahoo.coapi.spring.client.sync.LoadBalancedRestClientFactoryBean import me.ahoo.coapi.spring.client.sync.RestClientFactoryBean import org.slf4j.LoggerFactory import org.springframework.beans.factory.support.BeanDefinitionBuilder import org.springframework.beans.factory.support.BeanDefinitionRegistry class CoApiRegistrar(private val registry: BeanDefinitionRegistry, private val clientMode: ClientMode) { companion object { private val log = LoggerFactory.getLogger(CoApiRegistrar::class.java) } fun register(coApiDefinitions: Set<CoApiDefinition>) { coApiDefinitions.forEach { register(it) } } fun register(coApiDefinition: CoApiDefinition) { if (clientMode == ClientMode.SYNC) { registerRestClient(registry, coApiDefinition) } else { registerWebClient(registry, coApiDefinition) } registerApiClient(registry, coApiDefinition) } private fun registerRestClient(registry: BeanDefinitionRegistry, coApiDefinition: CoApiDefinition) { if (log.isInfoEnabled) { log.info("Register RestClient [{}].", coApiDefinition.httpClientBeanName) } if (registry.containsBeanDefinition(coApiDefinition.httpClientBeanName)) { if (log.isWarnEnabled) { log.warn( "RestClient [{}] already exists - Ignore.", coApiDefinition.httpClientBeanName ) } return } val clientFactoryBeanClass = if (coApiDefinition.loadBalanced) { LoadBalancedRestClientFactoryBean::class.java } else { RestClientFactoryBean::class.java } val beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clientFactoryBeanClass) beanDefinitionBuilder.addConstructorArgValue(coApiDefinition) registry.registerBeanDefinition(coApiDefinition.httpClientBeanName, beanDefinitionBuilder.beanDefinition) } private fun registerWebClient(registry: BeanDefinitionRegistry, coApiDefinition: CoApiDefinition) { if (log.isInfoEnabled) { log.info("Register WebClient [{}].", coApiDefinition.httpClientBeanName) } if (registry.containsBeanDefinition(coApiDefinition.httpClientBeanName)) { if (log.isWarnEnabled) { log.warn( "WebClient [{}] already exists - Ignore.", coApiDefinition.httpClientBeanName ) } return } val clientFactoryBeanClass = if (coApiDefinition.loadBalanced) { LoadBalancedWebClientFactoryBean::class.java } else { WebClientFactoryBean::class.java } val beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clientFactoryBeanClass) beanDefinitionBuilder.addConstructorArgValue(coApiDefinition) registry.registerBeanDefinition(coApiDefinition.httpClientBeanName, beanDefinitionBuilder.beanDefinition) } private fun registerApiClient(registry: BeanDefinitionRegistry, coApiDefinition: CoApiDefinition) { if (log.isInfoEnabled) { log.info("Register CoApi [{}].", coApiDefinition.coApiBeanName) } if (registry.containsBeanDefinition(coApiDefinition.coApiBeanName)) { if (log.isWarnEnabled) { log.warn( "CoApi [{}] already exists - Ignore.", coApiDefinition.coApiBeanName ) } return } val beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(CoApiFactoryBean::class.java) beanDefinitionBuilder.addConstructorArgValue(coApiDefinition) registry.registerBeanDefinition(coApiDefinition.coApiBeanName, beanDefinitionBuilder.beanDefinition) } }
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/CoApiDefinition.kt
2504447409
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring import me.ahoo.coapi.api.CoApi import org.springframework.core.env.Environment data class CoApiDefinition( val name: String, val apiType: Class<*>, val baseUrl: String, val loadBalanced: Boolean ) { companion object { private const val CLIENT_BEAN_NAME_SUFFIX = ".HttpClient" private const val COAPI_BEAN_NAME_SUFFIX = ".CoApi" private const val LB_SCHEME_PREFIX = "http://" fun Class<*>.toCoApiDefinition(environment: Environment): CoApiDefinition { val coApi = getAnnotation(CoApi::class.java) ?: throw IllegalArgumentException("The class must be annotated by @CoApi.") val baseUrl = coApi.resolveBaseUrl(environment) return CoApiDefinition( name = resolveClientName(coApi), apiType = this, baseUrl = baseUrl, loadBalanced = coApi.serviceId.isNotBlank() ) } private fun CoApi.resolveBaseUrl(environment: Environment): String { if (serviceId.isNotBlank()) { return LB_SCHEME_PREFIX + serviceId } return environment.resolvePlaceholders(baseUrl) } private fun Class<*>.resolveClientName(coApi: CoApi): String { if (coApi.name.isNotBlank()) { return coApi.name } return simpleName } } val httpClientBeanName: String by lazy { name + CLIENT_BEAN_NAME_SUFFIX } val coApiBeanName: String by lazy { name + COAPI_BEAN_NAME_SUFFIX } }
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/AbstractCoApiRegistrar.kt
3624136649
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring import me.ahoo.coapi.spring.ClientMode.Companion.inferClientMode import me.ahoo.coapi.spring.client.reactive.ReactiveHttpExchangeAdapterFactory import me.ahoo.coapi.spring.client.sync.SyncHttpExchangeAdapterFactory import org.springframework.beans.factory.BeanFactory import org.springframework.beans.factory.BeanFactoryAware import org.springframework.beans.factory.support.BeanDefinitionBuilder import org.springframework.beans.factory.support.BeanDefinitionRegistry import org.springframework.context.EnvironmentAware import org.springframework.context.annotation.ImportBeanDefinitionRegistrar import org.springframework.core.env.Environment import org.springframework.core.type.AnnotationMetadata abstract class AbstractCoApiRegistrar : ImportBeanDefinitionRegistrar, EnvironmentAware, BeanFactoryAware { protected lateinit var env: Environment protected lateinit var appContext: BeanFactory override fun setEnvironment(environment: Environment) { this.env = environment } override fun setBeanFactory(beanFactory: BeanFactory) { this.appContext = beanFactory } abstract fun getCoApiDefinitions(importingClassMetadata: AnnotationMetadata): Set<CoApiDefinition> override fun registerBeanDefinitions(importingClassMetadata: AnnotationMetadata, registry: BeanDefinitionRegistry) { val clientMode = inferClientMode { env.getProperty(it) } registerHttpExchangeAdapterFactory(clientMode, registry) val coApiRegistrar = CoApiRegistrar(registry, clientMode) val apiDefinitions = getCoApiDefinitions(importingClassMetadata) coApiRegistrar.register(apiDefinitions) } private fun registerHttpExchangeAdapterFactory(clientMode: ClientMode, registry: BeanDefinitionRegistry) { if (registry.containsBeanDefinition(HttpExchangeAdapterFactory.BEAN_NAME)) { return } val httpExchangeAdapterFactoryClass = if (clientMode == ClientMode.SYNC) { SyncHttpExchangeAdapterFactory::class.java } else { ReactiveHttpExchangeAdapterFactory::class.java } val beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(httpExchangeAdapterFactoryClass) registry.registerBeanDefinition(HttpExchangeAdapterFactory.BEAN_NAME, beanDefinitionBuilder.beanDefinition) } }
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/CoApiFactoryBean.kt
3774352017
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring import org.springframework.beans.factory.FactoryBean import org.springframework.context.ApplicationContext import org.springframework.context.ApplicationContextAware import org.springframework.web.service.invoker.HttpServiceProxyFactory class CoApiFactoryBean( private val coApiDefinition: CoApiDefinition ) : FactoryBean<Any>, ApplicationContextAware { private lateinit var applicationContext: ApplicationContext override fun getObject(): Any { val httpExchangeAdapterFactory = applicationContext.getBean(HttpExchangeAdapterFactory::class.java) val httpExchangeAdapter = httpExchangeAdapterFactory.create( beanFactory = applicationContext, httpClientName = coApiDefinition.httpClientBeanName ) val httpServiceProxyFactory = HttpServiceProxyFactory.builderFor(httpExchangeAdapter).build() return httpServiceProxyFactory.createClient(coApiDefinition.apiType) } override fun getObjectType(): Class<*> { return coApiDefinition.apiType } override fun setApplicationContext(applicationContext: ApplicationContext) { this.applicationContext = applicationContext } }
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/ClientMode.kt
539227127
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring enum class ClientMode { REACTIVE, SYNC, AUTO; companion object { const val COAPI_CLIENT_MODE_PROPERTY = "coapi.mode" private const val REACTIVE_WEB_APPLICATION_CLASS = "org.springframework.web.reactive.HandlerResult" private val INFERRED_MODE_BASED_ON_CLASS: ClientMode by lazy { try { Class.forName(REACTIVE_WEB_APPLICATION_CLASS) REACTIVE } catch (ignore: ClassNotFoundException) { SYNC } } fun inferClientMode(getProperty: (propertyKey: String) -> String?): ClientMode { val propertyValue = getProperty(COAPI_CLIENT_MODE_PROPERTY) ?: AUTO.name val mode = ClientMode.valueOf(propertyValue.uppercase()) if (mode == AUTO) { return INFERRED_MODE_BASED_ON_CLASS } return mode } } }
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/EnableCoApiRegistrar.kt
251416930
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring import me.ahoo.coapi.spring.CoApiDefinition.Companion.toCoApiDefinition import org.springframework.core.type.AnnotationMetadata class EnableCoApiRegistrar : AbstractCoApiRegistrar() { @Suppress("UNCHECKED_CAST") override fun getCoApiDefinitions(importingClassMetadata: AnnotationMetadata): Set<CoApiDefinition> { val enableCoApi = importingClassMetadata.getAnnotationAttributes(EnableCoApi::class.java.name) ?: return emptySet() val clients = enableCoApi[EnableCoApi::clients.name] as Array<Class<*>> return clients.map { clientType -> clientType.toCoApiDefinition(env) }.toSet() } }
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/HttpExchangeAdapterFactory.kt
822668056
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring import org.springframework.beans.factory.BeanFactory import org.springframework.web.service.invoker.HttpExchangeAdapter fun interface HttpExchangeAdapterFactory { companion object { const val BEAN_NAME = "CoApi.HttpExchangeAdapterFactory" } fun create(beanFactory: BeanFactory, httpClientName: String): HttpExchangeAdapter }
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/reactive/ReactiveHttpExchangeAdapterFactory.kt
756097217
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring.client.reactive import me.ahoo.coapi.spring.HttpExchangeAdapterFactory import org.springframework.beans.factory.BeanFactory import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.support.WebClientAdapter import org.springframework.web.service.invoker.HttpExchangeAdapter class ReactiveHttpExchangeAdapterFactory : HttpExchangeAdapterFactory { override fun create(beanFactory: BeanFactory, httpClientName: String): HttpExchangeAdapter { val httpClient = beanFactory.getBean(httpClientName, WebClient::class.java) return WebClientAdapter.create(httpClient) } }
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/reactive/WebClientBuilderCustomizer.kt
3699614830
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring.client.reactive import me.ahoo.coapi.spring.CoApiDefinition import me.ahoo.coapi.spring.client.HttpClientBuilderCustomizer import org.springframework.web.reactive.function.client.WebClient fun interface WebClientBuilderCustomizer : HttpClientBuilderCustomizer<WebClient.Builder> { object NoOp : WebClientBuilderCustomizer { override fun customize(coApiDefinition: CoApiDefinition, builder: WebClient.Builder) = Unit } }
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/reactive/auth/HeaderSetFilter.kt
2549461439
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring.client.reactive.auth import org.springframework.web.reactive.function.client.ClientRequest import org.springframework.web.reactive.function.client.ClientResponse import org.springframework.web.reactive.function.client.ExchangeFilterFunction import org.springframework.web.reactive.function.client.ExchangeFunction import reactor.core.publisher.Mono open class HeaderSetFilter( private val headerName: String, private val headerValueProvider: HeaderValueProvider, private val headerValueMapper: HeaderValueMapper = HeaderValueMapper.IDENTITY ) : ExchangeFilterFunction { override fun filter(request: ClientRequest, next: ExchangeFunction): Mono<ClientResponse> { if (request.headers().containsKey(headerName)) { return next.exchange(request) } return headerValueProvider.getHeaderValue() .map { headerValue -> ClientRequest.from(request) .headers { headers -> headers[headerName] = headerValueMapper.map(headerValue) } .build() } .flatMap { next.exchange(it) } } } fun interface HeaderValueProvider { fun getHeaderValue(): Mono<String> } fun interface HeaderValueMapper { companion object { val IDENTITY = HeaderValueMapper { it } } fun map(headerValue: String): String }
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/reactive/auth/CachedExpirableTokenProvider.kt
4139103619
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring.client.reactive.auth import org.slf4j.LoggerFactory import reactor.core.publisher.Mono class CachedExpirableTokenProvider(tokenProvider: ExpirableTokenProvider) : ExpirableTokenProvider { companion object { private val log = LoggerFactory.getLogger(CachedExpirableTokenProvider::class.java) } private val tokenCache: Mono<ExpirableToken> = tokenProvider.getToken() .cacheInvalidateIf { if (log.isDebugEnabled) { log.debug("CacheInvalidateIf - isExpired:${it.isExpired}") } it.isExpired } override fun getToken(): Mono<ExpirableToken> { return tokenCache } }
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/reactive/auth/ExpirableTokenProvider.kt
3872968533
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring.client.reactive.auth import com.auth0.jwt.JWT import reactor.core.publisher.Mono data class ExpirableToken(val token: String, val expireAt: Long) { val isExpired: Boolean get() = System.currentTimeMillis() > expireAt companion object { private val jwtParser = JWT() fun String.jwtToExpirableToken(): ExpirableToken { val decodedJWT = jwtParser.decodeJwt(this) val expiresAt = checkNotNull(decodedJWT.expiresAt) return ExpirableToken(this, expiresAt.time) } } } interface ExpirableTokenProvider : HeaderValueProvider { fun getToken(): Mono<ExpirableToken> override fun getHeaderValue(): Mono<String> { return getToken().map { it.token } } }
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/reactive/auth/BearerTokenFilter.kt
89704242
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring.client.reactive.auth import org.springframework.http.HttpHeaders class BearerTokenFilter(tokenProvider: ExpirableTokenProvider) : HeaderSetFilter( headerName = HttpHeaders.AUTHORIZATION, headerValueProvider = tokenProvider, headerValueMapper = BearerHeaderValueMapper ) object BearerHeaderValueMapper : HeaderValueMapper { private const val BEARER_TOKEN_PREFIX = "Bearer " fun String.withBearerPrefix(): String { return "$BEARER_TOKEN_PREFIX$this" } override fun map(headerValue: String): String { return headerValue.withBearerPrefix() } }
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/reactive/AbstractWebClientFactoryBean.kt
2218482063
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring.client.reactive import me.ahoo.coapi.spring.CoApiDefinition import me.ahoo.coapi.spring.client.ClientProperties import org.springframework.beans.factory.FactoryBean import org.springframework.context.ApplicationContext import org.springframework.context.ApplicationContextAware import org.springframework.web.reactive.function.client.ExchangeFilterFunction import org.springframework.web.reactive.function.client.WebClient abstract class AbstractWebClientFactoryBean(private val definition: CoApiDefinition) : FactoryBean<WebClient>, ApplicationContextAware { protected lateinit var appContext: ApplicationContext protected open val builderCustomizer: WebClientBuilderCustomizer = WebClientBuilderCustomizer.NoOp override fun getObjectType(): Class<*> { return WebClient::class.java } override fun getObject(): WebClient { val clientBuilder = appContext .getBean(WebClient.Builder::class.java) clientBuilder.baseUrl(definition.baseUrl) val clientProperties = appContext.getBean(ClientProperties::class.java) val filterDefinition = clientProperties.getFilter(definition.name) clientBuilder.filters { filterDefinition.initFilters(it) } builderCustomizer.customize(definition, clientBuilder) appContext.getBeanProvider(WebClientBuilderCustomizer::class.java) .orderedStream() .forEach { customizer -> customizer.customize(definition, clientBuilder) } return clientBuilder.build() } private fun ClientProperties.FilterDefinition.initFilters(filters: MutableList<ExchangeFilterFunction>) { names.forEach { filterName -> val filter = appContext.getBean(filterName, ExchangeFilterFunction::class.java) filters.add(filter) } types.forEach { filterType -> val filter = appContext.getBean(filterType) filters.add(filter) } } override fun setApplicationContext(applicationContext: ApplicationContext) { this.appContext = applicationContext } }
CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/reactive/LoadBalancedWebClientFactoryBean.kt
646420195
/* * Copyright [2022-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 * http://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 me.ahoo.coapi.spring.client.reactive import me.ahoo.coapi.spring.CoApiDefinition import org.springframework.cloud.client.loadbalancer.reactive.LoadBalancedExchangeFilterFunction import org.springframework.web.reactive.function.client.WebClient class LoadBalancedWebClientFactoryBean(definition: CoApiDefinition) : AbstractWebClientFactoryBean(definition) { companion object { private val loadBalancedFilterClass = LoadBalancedExchangeFilterFunction::class.java } override val builderCustomizer: WebClientBuilderCustomizer = LoadBalancedWebClientBuilderCustomizer() inner class LoadBalancedWebClientBuilderCustomizer : WebClientBuilderCustomizer { override fun customize(coApiDefinition: CoApiDefinition, builder: WebClient.Builder) { builder.filters { val hasLoadBalancedFilter = it.any { filter -> filter is LoadBalancedExchangeFilterFunction } if (!hasLoadBalancedFilter) { val loadBalancedExchangeFilterFunction = appContext.getBean(loadBalancedFilterClass) it.add(loadBalancedExchangeFilterFunction) } } } } }