001/* 002 * Copyright 2002-2018 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.http.server.reactive; 018 019import java.util.concurrent.atomic.AtomicBoolean; 020 021import org.reactivestreams.Processor; 022import org.reactivestreams.Publisher; 023import reactor.core.publisher.Mono; 024 025import org.springframework.core.io.buffer.DataBuffer; 026import org.springframework.core.io.buffer.DataBufferFactory; 027import org.springframework.http.HttpHeaders; 028 029/** 030 * Abstract base class for listener-based server responses, e.g. Servlet 3.1 031 * and Undertow. 032 * 033 * @author Arjen Poutsma 034 * @since 5.0 035 */ 036public abstract class AbstractListenerServerHttpResponse extends AbstractServerHttpResponse { 037 038 private final AtomicBoolean writeCalled = new AtomicBoolean(); 039 040 041 public AbstractListenerServerHttpResponse(DataBufferFactory dataBufferFactory) { 042 super(dataBufferFactory); 043 } 044 045 public AbstractListenerServerHttpResponse(DataBufferFactory dataBufferFactory, HttpHeaders headers) { 046 super(dataBufferFactory, headers); 047 } 048 049 050 @Override 051 protected final Mono<Void> writeWithInternal(Publisher<? extends DataBuffer> body) { 052 return writeAndFlushWithInternal(Mono.just(body)); 053 } 054 055 @Override 056 protected final Mono<Void> writeAndFlushWithInternal( 057 Publisher<? extends Publisher<? extends DataBuffer>> body) { 058 059 if (this.writeCalled.compareAndSet(false, true)) { 060 Processor<? super Publisher<? extends DataBuffer>, Void> processor = createBodyFlushProcessor(); 061 return Mono.from(subscriber -> { 062 body.subscribe(processor); 063 processor.subscribe(subscriber); 064 }); 065 } 066 return Mono.error(new IllegalStateException( 067 "writeWith() or writeAndFlushWith() has already been called")); 068 } 069 070 /** 071 * Abstract template method to create a {@code Processor<Publisher<DataBuffer>, Void>} 072 * that will write the response body with flushes to the underlying output. Called from 073 * {@link #writeAndFlushWithInternal(Publisher)}. 074 */ 075 protected abstract Processor<? super Publisher<? extends DataBuffer>, Void> createBodyFlushProcessor(); 076 077}