001package io.freefair.spring.okhttp; 002 003import okhttp3.ResponseBody; 004import org.springframework.core.io.AbstractResource; 005import org.springframework.lang.Nullable; 006import java.io.Closeable; 007import java.io.FileNotFoundException; 008import java.io.IOException; 009import java.io.InputStream; 010import java.nio.charset.Charset; 011 012public class OkHttpResponseBodyResource extends AbstractResource implements Closeable { 013 @Nullable 014 private final ResponseBody responseBody; 015 private boolean closed = false; 016 017 @Override 018 public byte[] getContentAsByteArray() throws IOException { 019 if (responseBody == null) { 020 throw new FileNotFoundException("Response body is null"); 021 } 022 return responseBody.bytes(); 023 } 024 025 @Override 026 public String getContentAsString(Charset charset) throws IOException { 027 if (responseBody == null) { 028 throw new FileNotFoundException("Response body is null"); 029 } 030 return responseBody.string(); 031 } 032 033 @Override 034 public String getDescription() { 035 return "OkHttp ResponseBody " + responseBody; 036 } 037 038 @Override 039 public InputStream getInputStream() throws FileNotFoundException { 040 if (responseBody == null) { 041 throw new FileNotFoundException("Response body is null"); 042 } 043 return responseBody.byteStream(); 044 } 045 046 @Override 047 public long contentLength() throws FileNotFoundException { 048 if (responseBody == null) { 049 throw new FileNotFoundException("Response body is null"); 050 } 051 return responseBody.contentLength(); 052 } 053 054 @Override 055 public boolean exists() { 056 return responseBody != null; 057 } 058 059 @Override 060 public boolean isOpen() { 061 return exists() && !closed; 062 } 063 064 @Override 065 public boolean isReadable() { 066 return isOpen(); 067 } 068 069 @Override 070 public void close() { 071 if (responseBody != null) { 072 responseBody.close(); 073 } 074 closed = true; 075 } 076 077 public OkHttpResponseBodyResource(@Nullable final ResponseBody responseBody) { 078 this.responseBody = responseBody; 079 } 080 081 @Nullable 082 public ResponseBody getResponseBody() { 083 return this.responseBody; 084 } 085}