/*
 * Copyright 2020 Global Biodiversity Information Facility (GBIF)
 *
 * 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 org.gbif.ws.server.advice;

import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
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.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * Response filter that converts response status to 204 NO_CONTENT if response body is null.
 */
@SuppressWarnings("NullableProblems")
@ControllerAdvice
public class NoContentResponseFilter implements ResponseBodyAdvice<Object> {

  @Override
  public boolean supports(
      MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
    return true;
  }

  @Override
  public Object beforeBodyWrite(
      Object body,
      MethodParameter returnType,
      MediaType selectedContentType,
      Class<? extends HttpMessageConverter<?>> selectedConverterType,
      ServerHttpRequest request,
      ServerHttpResponse response) {
    final int intStatus = ((ServletServerHttpResponse) response).getServletResponse().getStatus();
    final HttpStatus httpStatus = HttpStatus.resolve(intStatus);

    if (body == null && httpStatus == HttpStatus.OK) {
      response.setStatusCode(HttpStatus.NO_CONTENT);
    }

    return body;
  }
}

@@ -2057,12 +2057,20 @@
 tus 
-== H
+!= null && h
 ttpS
@@ -2079,10 +2079,25 @@
 tus.
-OK
+is2xxSuccessful()
 ) %7B%0A

change NoContentResponseFilter to avoid race condition with CreatedResponseFilter