package com.uip.tatar.api;
import com.uip.tatar.APITatarException;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
/**
* Author: Khamidullin Kamil
* Date: 29.05.14
* Time: 12:29
*/
public class APITatarResponse {
private HttpResponse response;
private String data;
public APITatarResponse(HttpResponse response) throws APITatarException {
if(response == null) {
throw new IllegalArgumentException("http response may not be null");
}
this.response = response;
handleResponse(this.response);
}
public String getData() {
return data;
}
public HttpResponse getResponse() {
return response;
}
private void handleResponse(HttpResponse response) throws APITatarException {
try {
if(null != response.getEntity()) {
InputStream instream = response.getEntity().getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip"))
instream = new GZIPInputStream(instream);
loadData(instream);
}
} catch (IOException exception) {
throw new APITatarException(exception, response);
}
}
private void loadData(InputStream inputStream) throws APITatarException{
StringBuilder sb = new StringBuilder();
if(inputStream != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String line;
try {
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException exception) {
throw new APITatarException(exception, response);
} finally {
try {
br.close();
} catch (IOException ignore) {/*ignore*/}
}
}
data = sb.toString();
}
@Override
public String toString() {
return String.format("{'RESPONSE' : %s}", getData());
}
}