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.mock.web; 018 019import java.io.IOException; 020import java.io.InputStream; 021 022import javax.servlet.ReadListener; 023import javax.servlet.ServletInputStream; 024 025import org.springframework.util.Assert; 026 027/** 028 * Delegating implementation of {@link javax.servlet.ServletInputStream}. 029 * 030 * <p>Used by {@link MockHttpServletRequest}; typically not directly 031 * used for testing application controllers. 032 * 033 * @author Juergen Hoeller 034 * @since 1.0.2 035 * @see MockHttpServletRequest 036 */ 037public class DelegatingServletInputStream extends ServletInputStream { 038 039 private final InputStream sourceStream; 040 041 private boolean finished = false; 042 043 044 /** 045 * Create a DelegatingServletInputStream for the given source stream. 046 * @param sourceStream the source stream (never {@code null}) 047 */ 048 public DelegatingServletInputStream(InputStream sourceStream) { 049 Assert.notNull(sourceStream, "Source InputStream must not be null"); 050 this.sourceStream = sourceStream; 051 } 052 053 /** 054 * Return the underlying source stream (never {@code null}). 055 */ 056 public final InputStream getSourceStream() { 057 return this.sourceStream; 058 } 059 060 061 @Override 062 public int read() throws IOException { 063 int data = this.sourceStream.read(); 064 if (data == -1) { 065 this.finished = true; 066 } 067 return data; 068 } 069 070 @Override 071 public int available() throws IOException { 072 return this.sourceStream.available(); 073 } 074 075 @Override 076 public void close() throws IOException { 077 super.close(); 078 this.sourceStream.close(); 079 } 080 081 @Override 082 public boolean isFinished() { 083 return this.finished; 084 } 085 086 @Override 087 public boolean isReady() { 088 return true; 089 } 090 091 @Override 092 public void setReadListener(ReadListener readListener) { 093 throw new UnsupportedOperationException(); 094 } 095 096}