1 package org.oxerr.okcoin.rest.dto.valuereader; 2 3 import static org.apache.http.HttpStatus.SC_OK; 4 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.nio.charset.Charset; 8 9 import javax.annotation.Nonnull; 10 import javax.annotation.Nullable; 11 12 import org.apache.http.HttpEntity; 13 import org.apache.http.HttpResponse; 14 import org.apache.http.StatusLine; 15 import org.apache.http.entity.ContentType; 16 import org.apache.http.util.EntityUtils; 17 18 public interface ValueReader<T> { 19 20 default T read(@Nonnull HttpResponse response) throws IOException { 21 final StatusLine statusLine = response.getStatusLine(); 22 if (statusLine.getStatusCode() == SC_OK) { 23 HttpEntity entity = response.getEntity(); 24 return read(entity); 25 } else { 26 throw new IOException(statusLine.getReasonPhrase()); 27 } 28 } 29 30 default T read(@Nullable HttpEntity entity) throws IOException { 31 if (entity == null) { 32 return null; 33 } 34 35 final ContentType contentType = ContentType.get(entity); 36 try (InputStream content = entity.getContent()) { 37 return read(content, contentType); 38 } finally { 39 EntityUtils.consume(entity); 40 } 41 } 42 43 default T read(@Nonnull InputStream inputStream, 44 @Nullable ContentType contentType) throws IOException { 45 String mimeType = null; 46 Charset charset = null; 47 if (contentType != null) { 48 mimeType = contentType.getMimeType(); 49 charset = contentType.getCharset(); 50 } 51 return read(inputStream, mimeType, charset); 52 } 53 54 default T read(@Nonnull InputStream inputStream, 55 @Nullable String mimeType, @Nullable Charset charset) throws IOException { 56 return read(inputStream); 57 } 58 59 @Deprecated 60 default T read(@Nonnull InputStream inputStream) throws IOException { 61 return null; 62 } 63 64 }