SvgDiagramController.kt
/*
Copyright (C) 2026 Sber
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 ru.sber.seaf.plantuml.plantumlserver.ws
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import ru.sber.seaf.plantuml.plantumlserver.helper.RequestBodyHelper
import ru.sber.seaf.plantuml.plantumlserver.rendering.PlantumlDecodingService
import ru.sber.seaf.plantuml.plantumlserver.rendering.SvgRenderingService
@RestController
@RequestMapping("/plantuml/svg")
class SvgDiagramController(
private val decoder: PlantumlDecodingService,
private val svg: SvgRenderingService
) {
@GetMapping("/{payload}")
fun getSvg(
@PathVariable payload: String,
response: HttpServletResponse
) {
val source = decoder.decodeUrlPayload(payload)
response.writeSvg { svg.render(source, it) }
}
@PostMapping("", "/", "/{mode}")
fun postSvg(
request: HttpServletRequest,
response: HttpServletResponse,
@PathVariable(required = false) mode: String?
) {
val source = decoder.decodeBodyPayload(mode, RequestBodyHelper(request))
response.writeSvg { svg.render(source, it) }
}
@ExceptionHandler(Exception::class)
fun badRequest(): ResponseEntity<String> =
ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Bad Request")
private fun HttpServletResponse.writeSvg(render: (java.io.OutputStream) -> Unit) {
characterEncoding = Charsets.UTF_8.name()
contentType = SVG_CONTENT_TYPE
render(outputStream)
flushBuffer()
}
private companion object {
const val SVG_CONTENT_TYPE = "image/svg+xml"
}
}