Home | History | Annotate | Download | only in mockwebserver
      1 /*
      2  * Copyright (C) 2013 Google Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.google.mockwebserver;
     18 
     19 import java.io.ByteArrayInputStream;
     20 import java.io.Closeable;
     21 import java.io.IOException;
     22 import java.io.InputStream;
     23 import java.io.OutputStream;
     24 
     25 /**
     26  * A scripted response to be replayed by {@link MockWebServer}. This specific
     27  * variant uses an {@link InputStream} as its data source. Each instance can
     28  * only be consumed once.
     29  */
     30 public class MockStreamResponse extends BaseMockResponse<MockStreamResponse> {
     31     private InputStream body;
     32 
     33     public MockStreamResponse() {
     34         body = new ByteArrayInputStream(new byte[0]);
     35         addHeader(CONTENT_LENGTH, 0);
     36     }
     37 
     38     public MockStreamResponse setBody(InputStream body, long bodyLength) {
     39         // Release any existing body
     40         if (this.body != null) {
     41             closeQuietly(this.body);
     42         }
     43 
     44         this.body = body;
     45         setHeader(CONTENT_LENGTH, bodyLength);
     46         return this;
     47     }
     48 
     49     @Override
     50     public void writeResponse(OutputStream out) throws IOException {
     51         if (body == null) {
     52             throw new IllegalStateException("Stream already consumed");
     53         }
     54 
     55         try {
     56             super.writeResponse(body, out);
     57         } finally {
     58             closeQuietly(body);
     59         }
     60         body = null;
     61     }
     62 
     63     @Override
     64     protected MockStreamResponse self() {
     65         return this;
     66     }
     67 
     68     private static void closeQuietly(Closeable closeable) {
     69         if (closeable != null) {
     70             try {
     71                 closeable.close();
     72             } catch (RuntimeException rethrown) {
     73                 throw rethrown;
     74             } catch (Exception ignored) {
     75             }
     76         }
     77     }
     78 }
     79