content: /*
   * Copyright 2018-2024 adorsys GmbH & Co KG
   *
   * This program is free software: you can redistribute it and/or modify it
   * under the terms of the GNU Affero General Public License as published
   * by the Free Software Foundation, either version 3 of the License, or (at
   * your option) any later version. This program is distributed in the hope that
   * it will be useful, but WITHOUT ANY WARRANTY; without even the implied
   * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
   * See the GNU Affero General Public License for more details.
   *
   * You should have received a copy of the GNU Affero General Public License
   * along with this program. If not, see https://www.gnu.org/licenses/.
   *
   * This project is also available under a separate commercial license. You can
   * contact us at sales@adorsys.com.
   */
  
  package de.adorsys.psd2.xs2a.web.advice;
  
  import lombok.RequiredArgsConstructor;
  import org.jetbrains.annotations.NotNull;
  import org.springframework.core.MethodParameter;
  import org.springframework.http.MediaType;
  import org.springframework.http.converter.HttpMessageConverter;
  import org.springframework.http.server.ServerHttpRequest;
  import org.springframework.http.server.ServerHttpResponse;
  import org.springframework.web.bind.annotation.ControllerAdvice;
  import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
  
  import java.util.Optional;
  
  @RequiredArgsConstructor
  @ControllerAdvice(basePackages = "de.adorsys.psd2.xs2a.web.controller")
  public class CommonHeaderModifierAdvice implements ResponseBodyAdvice<Object> {
  
      @Override
      public boolean supports(@NotNull MethodParameter returnType, @NotNull Class<? extends HttpMessageConverter<?>> converterType) {
          return true;
      }
  
      @Override
      public Object beforeBodyWrite(Object body, @NotNull MethodParameter returnType, @NotNull MediaType selectedContentType, @NotNull Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
          response.getHeaders().add("X-Request-Id", request.getHeaders().getFirst("X-Request-Id"));
          return body;
      }
  
      protected boolean hasError(Object body, Class expectedClass) {
          return Optional.ofNullable(body).isPresent() && !body.getClass()
                                                               .isAssignableFrom(expectedClass);
      }
  }
  