StaticController.java 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package com.provectus.kafka.ui.controller;
  2. import com.provectus.kafka.ui.util.ResourceUtil;
  3. import java.util.concurrent.atomic.AtomicReference;
  4. import lombok.RequiredArgsConstructor;
  5. import lombok.SneakyThrows;
  6. import lombok.extern.log4j.Log4j2;
  7. import org.springframework.beans.factory.annotation.Value;
  8. import org.springframework.boot.autoconfigure.web.ServerProperties;
  9. import org.springframework.core.io.Resource;
  10. import org.springframework.http.ResponseEntity;
  11. import org.springframework.web.bind.annotation.GetMapping;
  12. import org.springframework.web.bind.annotation.RestController;
  13. import reactor.core.publisher.Mono;
  14. @RestController
  15. @RequiredArgsConstructor
  16. @Log4j2
  17. public class StaticController {
  18. private final ServerProperties serverProperties;
  19. @Value("classpath:static/index.html")
  20. private Resource indexFile;
  21. private final AtomicReference<String> renderedIndexFile = new AtomicReference<>();
  22. @GetMapping(value = "/index.html", produces = { "text/html" })
  23. public Mono<ResponseEntity<String>> getIndex() {
  24. return Mono.just(ResponseEntity.ok(getRenderedIndexFile()));
  25. }
  26. public String getRenderedIndexFile() {
  27. String rendered = renderedIndexFile.get();
  28. if (rendered == null) {
  29. rendered = buildIndexFile();
  30. if (renderedIndexFile.compareAndSet(null, rendered)) {
  31. return rendered;
  32. } else {
  33. return renderedIndexFile.get();
  34. }
  35. } else {
  36. return rendered;
  37. }
  38. }
  39. @SneakyThrows
  40. private String buildIndexFile() {
  41. final String contextPath = serverProperties.getServlet().getContextPath() != null
  42. ? serverProperties.getServlet().getContextPath() : "";
  43. final String staticPath = contextPath + "/static";
  44. return ResourceUtil.readAsString(indexFile)
  45. .replace("href=\"./static", "href=\"" + staticPath)
  46. .replace("src=\"./static", "src=\"" + staticPath)
  47. .replace("window.basePath=\"/\"", "window.basePath=\"" + contextPath + "\"");
  48. }
  49. }