com.bybutter.sisyphus.starter.grpc.transcoding.codec.ProtobufEncoder.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of sisyphus-grpc-transcoding-starter Show documentation
Show all versions of sisyphus-grpc-transcoding-starter Show documentation
Starter for building gRPC server which with HTTP and gRPC Transcoding in Sisyphus Framework
package com.bybutter.sisyphus.starter.grpc.transcoding.codec
import com.bybutter.sisyphus.protobuf.Message
import java.io.IOException
import org.reactivestreams.Publisher
import org.springframework.core.ResolvableType
import org.springframework.core.codec.AbstractEncoder
import org.springframework.core.io.buffer.DataBuffer
import org.springframework.core.io.buffer.DataBufferFactory
import org.springframework.core.io.buffer.DataBufferUtils
import org.springframework.http.MediaType
import org.springframework.http.codec.HttpMessageEncoder
import org.springframework.util.MimeType
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
class ProtobufEncoder(vararg mimeTypes: MimeType) : AbstractEncoder>(*mimeTypes),
HttpMessageEncoder> {
override fun getStreamingMediaTypes(): List {
return ProtobufCodecCustomizer.STREAM_MIME_TYPES
}
override fun encode(
inputStream: Publisher>,
bufferFactory: DataBufferFactory,
elementType: ResolvableType,
mimeType: MimeType?,
hints: Map?
): Flux {
return Flux.from(inputStream).map {
encodeValue(it, bufferFactory, inputStream !is Mono<*>)
}
}
override fun encodeValue(
value: Message<*, *>,
bufferFactory: DataBufferFactory,
valueType: ResolvableType,
mimeType: MimeType?,
hints: MutableMap?
): DataBuffer {
return encodeValue(value, bufferFactory, false)
}
private fun encodeValue(message: Message<*, *>, bufferFactory: DataBufferFactory, delimited: Boolean): DataBuffer {
val buffer = bufferFactory.allocateBuffer()
var release = true
return try {
if (delimited) {
message.writeDelimitedTo(buffer.asOutputStream())
} else {
message.writeTo(buffer.asOutputStream())
}
release = false
buffer
} catch (ex: IOException) {
throw IllegalStateException("Unexpected I/O error while writing to data buffer", ex)
} finally {
if (release) {
DataBufferUtils.release(buffer)
}
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy