content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
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/fragment/OfferListFragment.kt | 1867984000 |
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/Location.kt | 1503829551 |
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/Offer.kt | 872707810 |
package com.example.aviatickets.model.entity
data class OfferResponse(
val offers: List<Offer>
)
| AndroidMidka/app/src/main/java/com/example/aviatickets/model/entity/OfferResponse.kt | 4049189158 |
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/Airline.kt | 1976328334 |
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/ApiService.kt | 3630993577 |
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/entity/Flight.kt | 3657800238 |
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/network/ApiClient.kt | 1709923541 |
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
)
)
)
}
| AndroidMidka/app/src/main/java/com/example/aviatickets/model/service/FakeService.kt | 96052179 |
/*
* 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/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 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/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 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/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 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/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 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/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 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/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 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/spring-boot-starter/src/main/kotlin/me/ahoo/coapi/spring/boot/starter/CoApiProperties.kt | 300603511 |
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/test/kotlin/me/ahoo/coapi/example/sync/ExampleServerTest.kt | 954994990 |
/*
* 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/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 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-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.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/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 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/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(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/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(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/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")
interface ServiceApiClientUseFilterType {
@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.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/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 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/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 org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class ProviderServer
fun main(args: Array<String>) {
runApplication<ProviderServer>(*args)
}
| 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.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/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.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/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.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/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.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-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.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/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.client
import me.ahoo.coapi.api.CoApi
import me.ahoo.coapi.example.provider.api.TodoApi
@CoApi(serviceId = "provider-service")
interface TodoClient : TodoApi | 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.api
import org.springframework.stereotype.Component
@Target(AnnotationTarget.CLASS)
@Component
annotation class CoApi(
val serviceId: String = "",
val baseUrl: String = "",
val name: String = ""
)
| CoApi/api/src/main/kotlin/me/ahoo/coapi/api/CoApi.kt | 953783909 |
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/ClientModeTest.kt | 2404528347 |
/*
* 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/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.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/JwtFixture.kt | 778747356 |
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/CachedExpirableTokenProviderTest.kt | 1013220009 |
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/client/reactive/auth/BearerTokenFilterTest.kt | 116512883 |
/*
* 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/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 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/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 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/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.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/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.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/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 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/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
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/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
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/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 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/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.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/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.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/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.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/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.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/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 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/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 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/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
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/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 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)
}
}
}
}
}
| 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
class WebClientFactoryBean(definition: CoApiDefinition) :
AbstractWebClientFactoryBean(definition)
| CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/reactive/WebClientFactoryBean.kt | 2873284723 |
/*
* 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
import org.springframework.http.client.ClientHttpRequestInterceptor
import org.springframework.web.reactive.function.client.ExchangeFilterFunction
interface ClientProperties {
fun getFilter(coApiName: String): FilterDefinition
fun getInterceptor(coApiName: String): InterceptorDefinition
data class FilterDefinition(
val names: List<String> = emptyList(),
val types: List<Class<out ExchangeFilterFunction>> = emptyList()
)
data class InterceptorDefinition(
val names: List<String> = emptyList(),
val types: List<Class<out ClientHttpRequestInterceptor>> = emptyList()
)
}
| CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/ClientProperties.kt | 907374280 |
/*
* 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
import me.ahoo.coapi.spring.CoApiDefinition
fun interface HttpClientBuilderCustomizer<Builder> {
fun customize(coApiDefinition: CoApiDefinition, builder: Builder)
}
| CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/HttpClientBuilderCustomizer.kt | 4181143062 |
/*
* 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.sync
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.http.client.ClientHttpRequestInterceptor
import org.springframework.web.client.RestClient
abstract class AbstractRestClientFactoryBean(private val definition: CoApiDefinition) :
FactoryBean<RestClient>,
ApplicationContextAware {
protected lateinit var appContext: ApplicationContext
protected open val builderCustomizer: RestClientBuilderCustomizer = RestClientBuilderCustomizer.NoOp
override fun getObject(): RestClient {
val clientBuilder = appContext
.getBean(RestClient.Builder::class.java)
clientBuilder.baseUrl(definition.baseUrl)
val clientProperties = appContext.getBean(ClientProperties::class.java)
val interceptorDefinition = clientProperties.getInterceptor(definition.name)
clientBuilder.requestInterceptors {
interceptorDefinition.initInterceptors(it)
}
builderCustomizer.customize(definition, clientBuilder)
appContext.getBeanProvider(RestClientBuilderCustomizer::class.java)
.orderedStream()
.forEach { customizer ->
customizer.customize(definition, clientBuilder)
}
return clientBuilder.build()
}
private fun ClientProperties.InterceptorDefinition.initInterceptors(
interceptors: MutableList<ClientHttpRequestInterceptor>
) {
names.forEach { filterName ->
val filter = appContext.getBean(filterName, ClientHttpRequestInterceptor::class.java)
interceptors.add(filter)
}
types.forEach { filterType ->
val filter = appContext.getBean(filterType)
interceptors.add(filter)
}
}
override fun getObjectType(): Class<*> {
return RestClient::class.java
}
override fun setApplicationContext(applicationContext: ApplicationContext) {
this.appContext = applicationContext
}
}
| CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/sync/AbstractRestClientFactoryBean.kt | 805856120 |
/*
* 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.sync
import me.ahoo.coapi.spring.HttpExchangeAdapterFactory
import org.springframework.beans.factory.BeanFactory
import org.springframework.web.client.RestClient
import org.springframework.web.client.support.RestClientAdapter
import org.springframework.web.service.invoker.HttpExchangeAdapter
class SyncHttpExchangeAdapterFactory : HttpExchangeAdapterFactory {
override fun create(beanFactory: BeanFactory, httpClientName: String): HttpExchangeAdapter {
val httpClient = beanFactory.getBean(httpClientName, RestClient::class.java)
return RestClientAdapter.create(httpClient)
}
}
| CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/sync/SyncHttpExchangeAdapterFactory.kt | 3393557943 |
/*
* 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.sync
import me.ahoo.coapi.spring.CoApiDefinition
class RestClientFactoryBean(definition: CoApiDefinition) : AbstractRestClientFactoryBean(definition)
| CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/sync/RestClientFactoryBean.kt | 2110079759 |
/*
* 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.sync
import me.ahoo.coapi.spring.CoApiDefinition
import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor
import org.springframework.cloud.client.loadbalancer.reactive.LoadBalancedExchangeFilterFunction
import org.springframework.web.client.RestClient
class LoadBalancedRestClientFactoryBean(definition: CoApiDefinition) : AbstractRestClientFactoryBean(definition) {
companion object {
private val loadBalancerInterceptorClass = LoadBalancerInterceptor::class.java
}
override val builderCustomizer: RestClientBuilderCustomizer = LoadBalancedRestClientBuilderCustomizer()
inner class LoadBalancedRestClientBuilderCustomizer : RestClientBuilderCustomizer {
override fun customize(coApiDefinition: CoApiDefinition, builder: RestClient.Builder) {
builder.requestInterceptors {
val hasLoadBalancedFilter = it.any { filter ->
filter is LoadBalancedExchangeFilterFunction
}
if (!hasLoadBalancedFilter) {
val loadBalancerInterceptor =
appContext.getBean(loadBalancerInterceptorClass)
it.add(loadBalancerInterceptor)
}
}
}
}
}
| CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/sync/LoadBalancedRestClientFactoryBean.kt | 2551711331 |
/*
* 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.sync
import me.ahoo.coapi.spring.CoApiDefinition
import me.ahoo.coapi.spring.client.HttpClientBuilderCustomizer
import org.springframework.web.client.RestClient
fun interface RestClientBuilderCustomizer : HttpClientBuilderCustomizer<RestClient.Builder> {
object NoOp : RestClientBuilderCustomizer {
override fun customize(coApiDefinition: CoApiDefinition, builder: RestClient.Builder) = Unit
}
}
| CoApi/spring/src/main/kotlin/me/ahoo/coapi/spring/client/sync/RestClientBuilderCustomizer.kt | 2210674534 |
package com.beyzaterzioglu.kotlininstagram
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.beyzaterzioglu.kotlininstagram", appContext.packageName)
}
} | mininsta/app/src/androidTest/java/com/beyzaterzioglu/kotlininstagram/ExampleInstrumentedTest.kt | 3835146727 |
package com.beyzaterzioglu.kotlininstagram
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)
}
} | mininsta/app/src/test/java/com/beyzaterzioglu/kotlininstagram/ExampleUnitTest.kt | 3714347917 |
package com.beyzaterzioglu.kotlininstagram.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.beyzaterzioglu.kotlininstagram.databinding.RecyclerRowBinding
import com.beyzaterzioglu.kotlininstagram.model.Post
import com.squareup.picasso.Picasso
class FeedRecyclerAdapter(val postList : ArrayList<Post>) : RecyclerView.Adapter<FeedRecyclerAdapter.PostHolder>() {
class PostHolder(val binding:RecyclerRowBinding): RecyclerView.ViewHolder(binding.root)
{
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostHolder {
val binding=RecyclerRowBinding.inflate(LayoutInflater.from(parent.context),parent,false)
return PostHolder(binding)
}
override fun getItemCount(): Int {
return postList.size
}
override fun onBindViewHolder(holder: PostHolder, position: Int) {
holder.binding.recyclerEmailText.text=postList.get(position).email
holder.binding.recyclerCommentText.text=postList.get(position).comment
if (postList.get(position).downloadUrl.isNotEmpty()) {
Picasso.get().load(postList.get(position).downloadUrl).into(holder.binding.recyclerImageView);
} else {
// Varsayılan bir resim yükleme veya hata durumunu ele alma
}
}
} | mininsta/app/src/main/java/com/beyzaterzioglu/kotlininstagram/adapter/FeedRecyclerAdapter.kt | 791329114 |
package com.beyzaterzioglu.kotlininstagram.model
data class Post (val email: String, val comment: String,val downloadUrl: String){
} | mininsta/app/src/main/java/com/beyzaterzioglu/kotlininstagram/model/Post.kt | 1008457718 |
package com.beyzaterzioglu.kotlininstagram.view
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.beyzaterzioglu.kotlininstagram.databinding.ActivityMainBinding
import com.google.firebase.Firebase
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.auth
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding=ActivityMainBinding.inflate(layoutInflater)
val view=binding.root
setContentView(view)
auth = Firebase.auth
val currentUser=auth.currentUser
if(currentUser!=null)
{ // geçerli bir kullanıcı var mı
val intent=Intent(this, FeedActivity::class.java)
startActivity(intent)
finish()
}
}
fun signinClick(view:View)
{
val email=binding.emailText.text.toString()
val password=binding.passwordText.text.toString()
if(email.equals("")|| password.equals(""))
{
Toast.makeText(this,"Enter email and password!!",Toast.LENGTH_LONG).show()
}
else
{
auth.signInWithEmailAndPassword(email,password)
.addOnSuccessListener {
val intent= Intent(this@MainActivity, FeedActivity::class.java)
startActivity(intent)
finish()
}
.addOnFailureListener { Toast.makeText(this@MainActivity,it.localizedMessage,Toast.LENGTH_LONG).show() }
}
}
fun signupClick(view:View)
{
val email=binding.emailText.text.toString()
val password=binding.passwordText.text.toString()
if(email.equals("")|| password.equals(""))
{
Toast.makeText(this,"Enter email and password!!",Toast.LENGTH_LONG).show()
}
else
{
// Bu kısımda yapılan doğrulama isteği atıldıktan sonra cevabın dönmesi daha uzun sürebilir kodlara göre.
// Bu sebeple bu işlem arkaplanda asenkron bir şekilde yapılmalıdır.
// Aşağıda yapılan islemler de cevabın dönmesi sonrasında yapılacak işlemlerdir.
auth.createUserWithEmailAndPassword(email,password)
.addOnSuccessListener {// success
val intent= Intent(this@MainActivity, FeedActivity::class.java)
startActivity(intent)
finish()
}
.addOnFailureListener {Toast.makeText(this@MainActivity,it.localizedMessage,Toast.LENGTH_LONG).show() }
}
}
} | mininsta/app/src/main/java/com/beyzaterzioglu/kotlininstagram/view/MainActivity.kt | 885047676 |
package com.beyzaterzioglu.kotlininstagram.view
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import com.beyzaterzioglu.kotlininstagram.databinding.ActivityUploadBinding
import android.Manifest
import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.Firebase
import com.google.firebase.Timestamp
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.auth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.firestore
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.storage
import java.util.UUID
class UploadActivity : AppCompatActivity() {
private lateinit var binding: ActivityUploadBinding
private lateinit var activityResultLauncher: ActivityResultLauncher<Intent>
private lateinit var permissionLauncher: ActivityResultLauncher<String> //izinler string
private lateinit var auth: FirebaseAuth
private lateinit var firestore: FirebaseFirestore
private lateinit var storage: FirebaseStorage
var selectedPicture: Uri? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityUploadBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
registerLauncher()
auth = Firebase.auth
firestore = Firebase.firestore
storage = Firebase.storage
}
fun selectImage(view: View) {
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.READ_EXTERNAL_STORAGE
) != PackageManager.PERMISSION_GRANTED
) {
// izin yok izin isteyeceğiz
if (ActivityCompat.shouldShowRequestPermissionRationale(
this,
Manifest.permission.READ_EXTERNAL_STORAGE
)
) {
//rasyoneli göstermeli miyiz?Evet
Snackbar.make(view, "Permisson neededfor gallery.", Snackbar.LENGTH_INDEFINITE)
.setAction("Give Permission") {
permissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
}.show()
} else {
//Hayır.
permissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
}
} else {
// izin zaten var
val intentToGallery =
Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
activityResultLauncher.launch(intentToGallery)
}
}
fun upload(view: View) {
//uuid, java sınıfındandır. Uydurma bir rakam veriyor. Böylece her kaydedilen resim benzersiz hale geliyor.
val uuid = UUID.randomUUID()
val imageName = "$uuid.jpg"
val reference = storage.reference
val imageReference = reference.child("images").child(imageName)
if (selectedPicture != null) {
imageReference.putFile(selectedPicture!!).addOnSuccessListener {
//download url alıp firestore'a kaydedeceğiz.
val uploadPictureReference = storage.reference.child("images").child(imageName)
uploadPictureReference.downloadUrl.addOnSuccessListener {
val downloadUrl = it.toString()
if (auth.currentUser != null) {
//Any, en kök veri tipidir. Her şey olabilir.
val postMap = hashMapOf<String, Any>()
postMap.put("downloadUrl", downloadUrl)
postMap.put("userEmail", auth.currentUser!!.email!!)
postMap.put("comment", binding.commentText.text.toString())
postMap.put("date", Timestamp.now())
firestore.collection("Posts").add(postMap).addOnSuccessListener {
finish()
}.addOnFailureListener {
Toast.makeText(
this@UploadActivity,
it.localizedMessage,
Toast.LENGTH_LONG
).show()
}
}
}.addOnFailureListener {
Toast.makeText(this, it.localizedMessage, Toast.LENGTH_LONG).show()
}
}
}
}
private fun registerLauncher() {//StartActivityForResult() bir sonuç için aktivite başlatacağımızı belirtir.Sonuç da alınacak verinin URI'dir.
activityResultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
//seçim sonrası ne olur?
result ->
if (result.resultCode == RESULT_OK) {// bir aktivite sonucudur.Kullanıcı resim seçti mi?
val intentFromResult = result.data
if (intentFromResult != null) {
selectedPicture = intentFromResult.data
selectedPicture?.let {//null olmaktan çıkarıyoruz
// farklı bir yöntem ise bitmap'e çevirmektir.
binding.imageView.setImageURI(it)
}
}
}
}
permissionLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) {
// izin istiyoruz.boolean dönecek
result ->
if (result) { //izin verildi
val intentToGallery =
Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
activityResultLauncher.launch(intentToGallery)
} else { //izin verilmedi
Toast.makeText(this@UploadActivity, "Permisson needed!", Toast.LENGTH_LONG)
.show()
}
}
}
}
| mininsta/app/src/main/java/com/beyzaterzioglu/kotlininstagram/view/UploadActivity.kt | 3524932176 |
package com.beyzaterzioglu.kotlininstagram.view
import android.content.AbstractThreadedSyncAdapter
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.beyzaterzioglu.kotlininstagram.R
import com.beyzaterzioglu.kotlininstagram.adapter.FeedRecyclerAdapter
import com.beyzaterzioglu.kotlininstagram.databinding.ActivityFeedBinding
import com.beyzaterzioglu.kotlininstagram.model.Post
import com.google.firebase.Firebase
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.auth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.Query
import com.google.firebase.firestore.firestore
class FeedActivity : AppCompatActivity() {
private lateinit var binding: ActivityFeedBinding
private lateinit var auth: FirebaseAuth
private lateinit var db: FirebaseFirestore
private lateinit var postArrayList: ArrayList<Post>
private lateinit var feedAdapter: FeedRecyclerAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding=ActivityFeedBinding.inflate(layoutInflater)
val view=binding.root
setContentView(view)
auth=Firebase.auth
db=Firebase.firestore
postArrayList=ArrayList<Post>()
getdata()
binding.recyclerView.layoutManager=LinearLayoutManager(this)
feedAdapter=FeedRecyclerAdapter(postArrayList)
binding.recyclerView.adapter=feedAdapter
}
private fun getdata()
{ // verileri db'den almak
//.addSnapshotListener { değerlerimizi verir., Alınan hata varsa hatayı verir. -> }
db.collection("Posts").orderBy("date",Query.Direction.DESCENDING).addSnapshotListener { value, error ->
if(error!=null)
{
Toast.makeText(this,error.localizedMessage,Toast.LENGTH_LONG).show()
}
else
{
if(value!=null)
{
if(!value.isEmpty){
val documents=value.documents
postArrayList.clear()
for (document in documents)
{
// casting işlemi, gelecek olan verinin tipi ne olursa olsun stringe çevirilir.
val comment=document.get("comment") as? String
val userEmail=document.get("userEmail") as? String
val downloadUrl = document.getString("downloadUrl") ?: ""
val post= Post(userEmail!!,comment!!,downloadUrl)
postArrayList.add(post)
}
feedAdapter.notifyDataSetChanged() // yeni verilerle güncelleme yap
}
}
}
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val menuInflater=menuInflater
menuInflater.inflate(R.menu.insta_menu,menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if(item.itemId== R.id.add_post)
{
val intent= Intent(this, UploadActivity::class.java)
startActivity(intent)
}
else if(item.itemId== R.id.signout)
{
auth.signOut()
val intent= Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}
return super.onOptionsItemSelected(item)
}
} | mininsta/app/src/main/java/com/beyzaterzioglu/kotlininstagram/view/FeedActivity.kt | 2977149342 |
package me._olios.itemcompressor
import org.bukkit.plugin.java.JavaPlugin
class ItemCompressor : JavaPlugin() {
override fun onEnable() {
// Plugin startup logic
}
override fun onDisable() {
// Plugin shutdown logic
}
} | ItemCompressor/src/main/java/me/_olios/itemcompressor/ItemCompressor.kt | 453806219 |
package com.example.basic_app_kyle
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.basic_app_kyle", appContext.packageName)
}
} | basic-app-kyle-android/app/src/androidTest/java/com/example/basic_app_kyle/ExampleInstrumentedTest.kt | 2472244452 |
package com.example.basic_app_kyle
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)
}
} | basic-app-kyle-android/app/src/test/java/com/example/basic_app_kyle/ExampleUnitTest.kt | 3494617650 |
package com.example.basic_app_kyle.ui.home
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class HomeViewModel : ViewModel() {
private val _text = MutableLiveData<String>().apply {
value = "This is home Fragment"
}
val text: LiveData<String> = _text
} | basic-app-kyle-android/app/src/main/java/com/example/basic_app_kyle/ui/home/HomeViewModel.kt | 679388821 |
package com.example.basic_app_kyle.ui.home
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.basic_app_kyle.databinding.FragmentHomeBinding
class HomeFragment : Fragment() {
private var _binding: FragmentHomeBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val homeViewModel =
ViewModelProvider(this).get(HomeViewModel::class.java)
_binding = FragmentHomeBinding.inflate(inflater, container, false)
val root: View = binding.root
val textView: TextView = binding.textHome
homeViewModel.text.observe(viewLifecycleOwner) {
textView.text = it
}
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | basic-app-kyle-android/app/src/main/java/com/example/basic_app_kyle/ui/home/HomeFragment.kt | 4258194111 |
package com.example.basic_app_kyle.ui.gallery
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class GalleryViewModel : ViewModel() {
private val _text = MutableLiveData<String>().apply {
value = "This is gallery Fragment"
}
val text: LiveData<String> = _text
} | basic-app-kyle-android/app/src/main/java/com/example/basic_app_kyle/ui/gallery/GalleryViewModel.kt | 567062627 |
package com.example.basic_app_kyle.ui.gallery
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.basic_app_kyle.databinding.FragmentGalleryBinding
class GalleryFragment : Fragment() {
private var _binding: FragmentGalleryBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val galleryViewModel =
ViewModelProvider(this).get(GalleryViewModel::class.java)
_binding = FragmentGalleryBinding.inflate(inflater, container, false)
val root: View = binding.root
val textView: TextView = binding.textGallery
galleryViewModel.text.observe(viewLifecycleOwner) {
textView.text = it
}
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | basic-app-kyle-android/app/src/main/java/com/example/basic_app_kyle/ui/gallery/GalleryFragment.kt | 2994070820 |
package com.example.basic_app_kyle.ui.slideshow
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class SlideshowViewModel : ViewModel() {
private val _text = MutableLiveData<String>().apply {
value = "This is slideshow Fragment"
}
val text: LiveData<String> = _text
} | basic-app-kyle-android/app/src/main/java/com/example/basic_app_kyle/ui/slideshow/SlideshowViewModel.kt | 1642141248 |
package com.example.basic_app_kyle.ui.slideshow
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.basic_app_kyle.databinding.FragmentSlideshowBinding
class SlideshowFragment : Fragment() {
private var _binding: FragmentSlideshowBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val slideshowViewModel =
ViewModelProvider(this).get(SlideshowViewModel::class.java)
_binding = FragmentSlideshowBinding.inflate(inflater, container, false)
val root: View = binding.root
val textView: TextView = binding.textSlideshow
slideshowViewModel.text.observe(viewLifecycleOwner) {
textView.text = it
}
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | basic-app-kyle-android/app/src/main/java/com/example/basic_app_kyle/ui/slideshow/SlideshowFragment.kt | 3404545204 |
package com.example.basic_app_kyle
import android.os.Bundle
import android.view.Menu
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.navigation.NavigationView
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import androidx.drawerlayout.widget.DrawerLayout
import androidx.appcompat.app.AppCompatActivity
import com.example.basic_app_kyle.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.appBarMain.toolbar)
binding.appBarMain.fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
val drawerLayout: DrawerLayout = binding.drawerLayout
val navView: NavigationView = binding.navView
val navController = findNavController(R.id.nav_host_fragment_content_main)
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
appBarConfiguration = AppBarConfiguration(
setOf(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow
), drawerLayout
)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.nav_host_fragment_content_main)
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
} | basic-app-kyle-android/app/src/main/java/com/example/basic_app_kyle/MainActivity.kt | 182618043 |
package com.example.androidsamples
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.androidsamples", appContext.packageName)
}
} | AndroidSamples/app/src/androidTest/java/com/example/androidsamples/ExampleInstrumentedTest.kt | 2936191759 |
package com.example.androidsamples
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)
}
} | AndroidSamples/app/src/test/java/com/example/androidsamples/ExampleUnitTest.kt | 3177318112 |
package com.example.androidsamples.viewmodel
import androidx.lifecycle.ViewModel
import com.example.androidsamples.Screen
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
class MainViewModel : ViewModel() {
val uiState: StateFlow<UiState> = MutableStateFlow(
UiState(
listOf(Screen.RichEditText)
)
)
data class UiState(val screens: List<Screen>)
} | AndroidSamples/app/src/main/java/com/example/androidsamples/viewmodel/MainViewModel.kt | 1364142007 |
package com.example.androidsamples.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | AndroidSamples/app/src/main/java/com/example/androidsamples/ui/theme/Color.kt | 2110625062 |
package com.example.androidsamples.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun AndroidSamplesTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | AndroidSamples/app/src/main/java/com/example/androidsamples/ui/theme/Theme.kt | 354852664 |
package com.example.androidsamples.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | AndroidSamples/app/src/main/java/com/example/androidsamples/ui/theme/Type.kt | 2972014825 |
package com.example.androidsamples.ui.screen
import android.content.Context
import android.content.Intent
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Divider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.androidsamples.Screen
import com.example.androidsamples.activity.RichEditTextActivity
import com.example.androidsamples.viewmodel.MainViewModel
@Composable
fun MainScreen(
modifier: Modifier = Modifier,
viewModel: MainViewModel = viewModel()
) {
val context = LocalContext.current
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
LazyColumn(
modifier = modifier,
) {
items(uiState.screens) {
Column(
modifier
.clickable(onClick = { click(context, it) })
.padding(start = 4.dp, end = 4.dp, top = 8.dp, bottom = 8.dp)
.fillMaxWidth()
)
{
Text(
text = it.name,
modifier = modifier,
)
}
Divider()
}
}
}
fun click(context: Context, screen: Screen) {
when (screen) {
Screen.RichEditText -> context.startActivity(
Intent(
context,
RichEditTextActivity::class.java
)
)
}
}
| AndroidSamples/app/src/main/java/com/example/androidsamples/ui/screen/MainScreen.kt | 3916137974 |
package com.example.androidsamples.activity
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import com.example.androidsamples.ui.screen.MainScreen
import com.example.androidsamples.ui.theme.AndroidSamplesTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
AndroidSamplesTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
MainScreen()
}
}
}
}
}
| AndroidSamples/app/src/main/java/com/example/androidsamples/activity/MainActivity.kt | 3714093518 |
package com.example.androidsamples.activity
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Typeface
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.method.LinkMovementMethod
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import android.text.style.ReplacementSpan
import android.text.style.StyleSpan
import android.text.style.URLSpan
import android.text.style.UnderlineSpan
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.text.clearSpans
import androidx.core.text.toSpannable
import com.example.androidsamples.R
private val list =
listOf(
"文字中",
"文字小",
"文字大",
"色変更",
"太字",
"下線",
"取り消し線",
"斜体",
"色変更",
"ハイパーリンク",
"太字かつ斜体"
)
private val exclude = listOf("太字かつ斜体", "斜体")
class RichEditTextActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_rich_edit_text)
findViewById<EditText>(R.id.rich_edit_text).apply {
val builder =
SpannableStringBuilder("文字大\n文字中\n文字小\n色変更\n太字\n下線\n取り消し線\n斜体\nハイパーリンク\n太字かつ斜体")
for (item in list) {
val first = this.text.indexOf(item)
val last = first + item.length
setSpan(builder, item, first, last)
}
this.text = builder
this.movementMethod = LinkMovementMethod.getInstance()
}
findViewById<EditText>(R.id.rich_edit_text_all).apply {
val builder = SpannableStringBuilder("全部")
for (item in list) {
if (exclude.contains(item)) continue
setSpan(builder, item, 0, this.text.length)
}
this.text = builder
this.movementMethod = LinkMovementMethod.getInstance()
}
findViewById<Button>(R.id.clearButton).setOnClickListener {
val allSpan = findViewById<TextView>(R.id.rich_edit_text_all).text.toSpannable()
allSpan.clearSpans()
findViewById<TextView>(R.id.rich_edit_text).text = allSpan
val textSpan = findViewById<TextView>(R.id.rich_edit_text).text.toSpannable()
textSpan.clearSpans()
findViewById<TextView>(R.id.rich_edit_text_all).text = textSpan
}
findViewById<EditText>(R.id.checkbox).apply {
val builder = SpannableStringBuilder("- [x]あいうえお")
builder.setSpan(CheckboxReplacementSpan(), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
this.text = builder
}
findViewById<EditText>(R.id.bold).apply {
val builder = SpannableStringBuilder("**あいうえお**")
builder.setSpan(GoneSpan(), 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
builder.setSpan(StyleSpan(Typeface.BOLD), 2, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
builder.setSpan(
GoneSpan(),
this.text.length - 2,
this.text.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
this.text = builder
}
}
private fun setSpan(builder: SpannableStringBuilder, item: String, start: Int, end: Int) {
val span = when (item) {
"文字大" -> RelativeSizeSpan(2f)
"文字中" -> RelativeSizeSpan(1.5f)
"文字小" -> RelativeSizeSpan(1f)
"色変更" -> ForegroundColorSpan(Color.RED)
"青変更" -> ForegroundColorSpan(Color.BLUE)
"太字" -> StyleSpan(Typeface.BOLD)
"下線" -> UnderlineSpan()
"取り消し線" -> android.text.style.StrikethroughSpan()
"斜体" -> StyleSpan(Typeface.ITALIC)
"ハイパーリンク" -> URLSpan("https://stackoverflow.com/questions/18621691/custom-sized-italic-font-using-spannable")
"太字かつ斜体" -> StyleSpan(Typeface.BOLD_ITALIC)
else -> throw IllegalStateException(item)
}
if (start < 0) return
builder.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
private inner class CheckboxReplacementSpan
constructor() : ReplacementSpan() {
override fun getSize(
paint: Paint,
text: CharSequence?,
start: Int,
end: Int,
fm: Paint.FontMetricsInt?
): Int {
return paint.measureText("✅", 0, 1).toInt()
}
override fun draw(
canvas: Canvas,
text: CharSequence?,
start: Int,
end: Int,
x: Float,
top: Int,
y: Int,
bottom: Int,
paint: Paint
) {
canvas.drawText("✅", 0, 1, x, y.toFloat(), paint);
}
}
class GoneSpan : ReplacementSpan() {
override fun getSize(
paint: Paint,
text: CharSequence?,
start: Int,
end: Int,
fm: Paint.FontMetricsInt?
): Int = 0
override fun draw(
canvas: Canvas,
text: CharSequence?,
start: Int,
end: Int,
x: Float,
top: Int,
y: Int,
bottom: Int,
paint: Paint
) {
}
}
} | AndroidSamples/app/src/main/java/com/example/androidsamples/activity/RichEditTextActivity.kt | 818701243 |
package com.example.androidsamples
enum class Screen {
RichEditText,
} | AndroidSamples/app/src/main/java/com/example/androidsamples/Screen.kt | 1591483952 |
package com.example.firepush
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.firepush", appContext.packageName)
}
} | demo-push-notifications/app/src/androidTest/java/com/example/firepush/ExampleInstrumentedTest.kt | 1836422527 |
package com.example.firepush
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)
}
} | demo-push-notifications/app/src/test/java/com/example/firepush/ExampleUnitTest.kt | 4005507136 |
package com.example.firepush.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | demo-push-notifications/app/src/main/java/com/example/firepush/ui/theme/Color.kt | 3412193677 |
package com.example.firepush.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun FirePushTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | demo-push-notifications/app/src/main/java/com/example/firepush/ui/theme/Theme.kt | 1837646401 |
package com.example.firepush.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | demo-push-notifications/app/src/main/java/com/example/firepush/ui/theme/Type.kt | 2770799836 |
package com.example.firepush
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.firepush.ui.theme.FirePushTheme
import com.google.firebase.messaging.FirebaseMessaging
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
FirePushTheme {
// A surface container using the 'background' color from the theme
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
Greeting("Mr. Wick")
}
}
}
FirebaseMessaging.getInstance().token.addOnCompleteListener {
task -> if (task.isSuccessful) {
var token = task.result
println("FCM Token: $token")
} else {
println("Failed to get FCM token: ${task.exception}")
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "Hello, $name!",
modifier = modifier
)
}
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
FirePushTheme {
Greeting("NexusCare User")
}
} | demo-push-notifications/app/src/main/java/com/example/firepush/MainActivity.kt | 2559449969 |
package com.example.firepush
import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
class MyFirebaseMessagingService: FirebaseMessagingService() {
private val TAG: String = String::class.java.simpleName
override fun onNewToken(token: String) {
super.onNewToken(token)
Log.d("R", token)
}
private fun sendRegistrationToServer(token: String) {
// send
}
override fun onMessageReceived(remoteMessage: RemoteMessage) {
Log.d(TAG, "From: ${remoteMessage?.from}")
remoteMessage?.data?.isNotEmpty()?.let {
Log.d(TAG, "message data payload" + remoteMessage.data)
if(!remoteMessage.data.isNullOrEmpty()) {
val msg: String = remoteMessage.data["message"].toString()
}
}
remoteMessage?.notification?.let{}
}
} | demo-push-notifications/app/src/main/java/com/example/firepush/MyFirebaseMessagingService.kt | 2373026714 |
package com.example.absolvetechassignment
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.absolvetechassignment", appContext.packageName)
}
} | AbsolveTechAssignment/app/src/androidTest/java/com/example/absolvetechassignment/ExampleInstrumentedTest.kt | 963583532 |
package com.example.absolvetechassignment
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)
}
} | AbsolveTechAssignment/app/src/test/java/com/example/absolvetechassignment/ExampleUnitTest.kt | 2665823350 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.