Certainly! Below is the Kotlin translation of your PHP HTTP client using Spring Boot and Feign Client. I've omitted the PingableTrackingPlatformClientInterface and its methods (doHealthCheck and getTrackingPlatformName) as per your request.
We'll proceed with the following steps:
- Define Custom Exceptions:
AftershipException and AftershipResponseException.
- Create a Feign Client Interface:
AftershipFeignClient.
- Implement an Error Decoder:
AftershipErrorDecoder to handle exceptions.
- Create the Service Class:
AftershipHttpClient that uses the Feign client.
- Handle Logging: Use SLF4J for logging, similar to the
LoggerAwareTrait in PHP.
Here's the complete code:
// Custom Exceptions
class AftershipException(message: String, cause: Throwable? = null) : RuntimeException(message, cause)
class AftershipResponseException(
val response: Map<String, Any?>,
message: String = "Aftership API response error",
cause: Throwable? = null
) : AftershipException(message, cause)
// Feign Client Interface
import org.springframework.cloud.openfeign.FeignClient
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
@FeignClient(
name = "aftershipClient",
url = "\${aftership.api.url}",
configuration = [AftershipFeignConfig::class]
)
interface AftershipFeignClient {
@PostMapping("/trackings")
fun createTracking(@RequestBody trackingData: Map<String, Any?>): ResponseEntity<Map<String, Any?>>
@GetMapping("/trackings/{slug}/{trackingNumber}")
fun getTrackingBySlugAndTrackingNumber(
@PathVariable slug: String,
@PathVariable trackingNumber: String,
@RequestParam params: Map<String, String>? = null
): ResponseEntity<Map<String, Any?>>
@GetMapping("/trackings/{id}")
fun getTracking(@PathVariable id: String): ResponseEntity<Map<String, Any?>>
@GetMapping("/couriers")
fun getCouriers(): ResponseEntity<Map<String, Any?>>
@GetMapping("/couriers/all")
fun getAllCouriers(): ResponseEntity<Map<String, Any?>>
}
// Error Decoder
import com.fasterxml.jackson.databind.ObjectMapper
import feign.Response
import feign.codec.ErrorDecoder
import org.slf4j.LoggerFactory
class AftershipErrorDecoder : ErrorDecoder {
private val logger = LoggerFactory.getLogger(AftershipErrorDecoder::class.java)
private val objectMapper = ObjectMapper()
override fun decode(methodKey: String, response: Response): Exception {
val responseBody = response.body()?.asInputStream()?.bufferedReader()?.use { it.readText() } ?: ""
val statusCode = response.status()
var responseContent: Map<String, Any?>? = null
try {
responseContent = objectMapper.readValue(responseBody, Map::class.java) as Map<String, Any?>
} catch (e: Exception) {
// Ignore parsing exceptions
}
if (responseContent == null) {
val message = "Aftership API response is empty, received HTTP error code \"$statusCode\""
logger.debug(message)
return AftershipException(message)
}
val meta = responseContent["meta"] as? Map<*, *>
val errorMessage = meta?.get("message") as? String ?: "Aftership API response error"
val exception = AftershipResponseException(responseContent, errorMessage)
logger.debug("[AftershipErrorDecoder] $errorMessage", exception)
return exception
}
}
// Feign Configuration
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
class AftershipFeignConfig {
@Bean
fun errorDecoder(): ErrorDecoder {
return AftershipErrorDecoder()
}
}
// Service Class
import com.fasterxml.jackson.databind.ObjectMapper
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import org.springframework.http.ResponseEntity
@Service
class AftershipHttpClient(
private val aftershipFeignClient: AftershipFeignClient
) {
private val logger = LoggerFactory.getLogger(AftershipHttpClient::class.java)
private val objectMapper = ObjectMapper()
fun createTracking(trackingData: Map<String, Any?>): Map<String, Any?> {
val sanitizedData = trackingData.mapValues { (_, value) ->
if (value is String) value.trim() else value
}
return try {
val response = aftershipFeignClient.createTracking(sanitizedData)
getTrackingContent(response)
} catch (e: AftershipException) {
throw e
} catch (e: Exception) {
logger.debug("[AftershipHttpClient] Error while requesting API: \"${e.message}\"", e)
throw AftershipException("Aftership API request failed: \"${e.message}\"", e)
}
}
fun getTrackingBySlugAndTrackingNumber(
slug: String,
trackingNumber: String,
optionalParameters: Map<String, String>? = null
): Map<String, Any?> {
return try {
val response = aftershipFeignClient.getTrackingBySlugAndTrackingNumber(slug, trackingNumber, optionalParameters)
getTrackingContent(response)
} catch (e: AftershipException) {
throw e
} catch (e: Exception) {
logger.debug("[AftershipHttpClient] Error while requesting API: \"${e.message}\"", e)
throw AftershipException("Aftership API request failed: \"${e.message}\"", e)
}
}
fun getTracking(id: String): Map<String, Any?> {
return try {
val response = aftershipFeignClient.getTracking(id)
getTrackingContent(response)
} catch (e: AftershipException) {
throw e
} catch (e: Exception) {
logger.debug("[AftershipHttpClient] Error while requesting API: \"${e.message}\"", e)
throw AftershipException("Aftership API request failed: \"${e.message}\"", e)
}
}
fun getCouriers(): List<Map<String, Any?>> {
return try {
val response = aftershipFeignClient.getCouriers()
getCouriersContent(response)
} catch (e: AftershipException) {
throw e
} catch (e: Exception) {
logger.debug("[AftershipHttpClient] Error while requesting API: \"${e.message}\"", e)
throw AftershipException("Aftership API request failed: \"${e.message}\"", e)
}
}
fun getAllCouriers(): List<Map<String, Any?>> {
return try {
val response = aftershipFeignClient.getAllCouriers()
getCouriersContent(response)
} catch (e: AftershipException) {
throw e
} catch (e: Exception) {
logger.debug("[AftershipHttpClient] Error while requesting API: \"${e.message}\"", e)
throw AftershipException("Aftership API request failed: \"${e.message}\"", e)
}
}
private fun getTrackingContent(response: ResponseEntity<Map<String, Any?>>): Map<String, Any?> {
val body = response.body
return if (body != null && body["data"] is Map<*, *>) {
body["data"] as Map<String, Any?>
} else {
emptyMap()
}
}
private fun getCouriersContent(response: ResponseEntity<Map<String, Any?>>): List<Map<String, Any?>> {
val body = response.body
return if (body != null && body["data"] is Map<*, *>) {
val data = body["data"] as Map<*, *>
data["couriers"] as? List<Map<String, Any?>> ?: emptyList()
} else {
emptyList()
}
}
}
Explanation:
-
Custom Exceptions: We've created AftershipException and AftershipResponseException to handle exceptions similarly to your PHP code.
-
Feign Client Interface (AftershipFeignClient): This interface maps to the Aftership API endpoints using Spring's annotations. The methods correspond to the ones in your PHP client.
-
Error Decoder (AftershipErrorDecoder): This class implements Feign's ErrorDecoder to parse error responses and throw our custom exceptions. It logs the errors similarly to your PHP code.
-
Feign Configuration (AftershipFeignConfig): We register our custom ErrorDecoder here, so Feign uses it when handling errors.
-
Service Class (AftershipHttpClient): This class uses the Feign client to make API calls. It sanitizes inputs (trims strings) and handles exceptions and logging, mirroring the logic in your PHP client.
Notes:
-
Logging: We use SLF4J (LoggerFactory) for logging, which is standard in Spring Boot applications.
-
Response Handling: We parse the response bodies to extract the required data, similar to how you parse JSON in the PHP code.
-
Exceptions: We catch AftershipException to rethrow our custom exceptions and catch generic Exception to handle unexpected errors, logging them appropriately.
-
Optional Parameters: In getTrackingBySlugAndTrackingNumber, optional parameters are handled using @RequestParam, which maps query parameters.
-
Data Types: Since the PHP code uses arrays, we've used Map<String, Any?> and List<Map<String, Any?>> to represent JSON objects and arrays in Kotlin.
Configuration Properties:
Make sure to define aftership.api.url in your application's configuration (e.g., application.properties or application.yml):
aftership.api.url=https://api.aftership.com/v4
Dependencies:
Ensure you have the following dependencies in your build.gradle or pom.xml:
- Spring Cloud OpenFeign
- Jackson (for JSON parsing)
- SLF4J (usually included with Spring Boot)
Usage Example:
You can autowire AftershipHttpClient in your services or controllers and use the methods as needed.
@Service
class TrackingService(private val aftershipHttpClient: AftershipHttpClient) {
fun createNewTracking(trackingData: Map<String, Any?>) {
val result = aftershipHttpClient.createTracking(trackingData)
// Handle result
}
}
This should provide a complete translation of your PHP client into Kotlin using Spring Boot and Feign Client, respecting the original logic and structure.