WebMvcConfig.java

package se.jobtechdev.personaldatagateway.api.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import jakarta.annotation.Nonnull;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

  private final String[] extraAllowedOrigins;

  WebMvcConfig(@Value("${pdg-api.extra-allowed-origins:#{null}}") String[] extraAllowedOrigins) {
    this.extraAllowedOrigins = extraAllowedOrigins;
  }

  @Override
  public void addCorsMappings(@Nonnull CorsRegistry registry) {
    if (extraAllowedOrigins != null) {
      registry
          .addMapping("/**")
          .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
          .allowedOrigins(extraAllowedOrigins);
    }
  }

  @Override
  public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.removeIf(
        converter -> {
          String converterName = converter.getClass().getSimpleName();
          return converterName.equals("MappingJackson2HttpMessageConverter");
        });

    final var converter = new MappingJackson2HttpMessageConverter();
    final var objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JavaTimeModule());
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    converter.setObjectMapper(objectMapper);
    converters.add(converter);
    WebMvcConfigurer.super.extendMessageConverters(converters);
  }
}