package com.aincc.lib.network.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.mime.MultipartEntity;
import android.net.http.AndroidHttpClient;
import com.aincc.lib.network.NetHttpProcessor;
import com.aincc.lib.network.common.BaseParam;
import com.aincc.lib.network.common.BaseTask;
import com.aincc.lib.network.common.BaseTrans;
import com.aincc.lib.network.common.BaseTransEx;
import com.aincc.lib.network.common.NetworkErrorType;
/**
*
* <h3><b>HttpTask</b></h3></br>
*
* @author aincc@barusoft.com
* @version 1.0.0
* @since 1.0.0
* @param <T>
* transaction class
* @param <E>
* exception class
*/
public abstract class HttpTask<T, E> extends BaseTask<T>
{
/**
* default buffer size
*
* @since 1.0.0
*/
private static final int DEFAULT_BUFFERREADER_SIZE = 8192;
/**
* uri
*
* @since 1.0.0
*/
protected String uri = null;
/**
* HTTP client
*
* @since 1.0.0
*/
protected AndroidHttpClient httpClient = null;
/**
* @since 1.0.0
*/
protected HttpUriRequest method = null;
@SuppressWarnings("unchecked")
@Override
protected T doInBackground(Void... params)
{
if (isCancelled())
{
return null;
}
HttpEntity entity = null;
InputStream inputStream = null;
BufferedReader bufferedReader = null;
try
{
HttpTrans tr = (HttpTrans) this.tr;
HttpParam param = (HttpParam) tr.getParam();
HttpResponse response = this.httpClient.execute(this.method);
final StatusLine status = response.getStatusLine();
if (status.getStatusCode() != HttpStatus.SC_OK)
{
return null;
}
entity = response.getEntity();
String encoding = param.getEncoding();
if (null != entity)
{
if (null == encoding)
{
bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()), DEFAULT_BUFFERREADER_SIZE);
}
else
{
bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(), encoding), DEFAULT_BUFFERREADER_SIZE);
}
StringBuffer data = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null)
{
data.append(line);
}
bufferedReader.close();
return parse(data, (Class<? extends HttpTrans>) this.tr.getClass(), ((BaseTrans) this.tr).getParam());
}
}
catch (Exception e)
{
e.printStackTrace();
if (null != this.method)
{
this.method.abort();
}
}
finally
{
cleanup(inputStream, bufferedReader, entity);
if (null != this.httpClient)
{
this.httpClient.close();
}
}
return null;
}
@Override
protected void onCancelled()
{
if (null != this.httpClient)
{
this.httpClient.close();
}
super.onCancelled();
}
@Override
protected void onPostExecute(T result)
{
if (isCancelled())
{
try
{
getListener().iNetListenedError(new BaseTransEx(NetHttpProcessor.getErrorMessage(NetworkErrorType.ERROR_RECEIVE).toString(), ((BaseTrans) tr).getParam()));
}
catch (Exception e1)
{
e1.printStackTrace();
}
try
{
getListener().iNetEnabled();
}
catch (Exception e1)
{
e1.printStackTrace();
}
this.processor.nextTask(taskSeq);
return;
}
if (null == result)
{
try
{
getListener().iNetListenedError(new BaseTransEx(NetHttpProcessor.getErrorMessage(NetworkErrorType.ERROR_RECEIVE).toString(), ((BaseTrans) tr).getParam()));
}
catch (Exception e1)
{
e1.printStackTrace();
}
try
{
getListener().iNetEnabled();
}
catch (Exception e1)
{
e1.printStackTrace();
}
this.processor.nextTask(taskSeq);
return;
}
((BaseTrans) result).setParam(((BaseTrans) tr).getParam());
this.tr = result;
try
{
getListener().iNetListenedTransaction((BaseTrans) tr);
getListener().iNetDisconnected();
getListener().iNetDisconnected(uri);
getListener().iNetEnabled();
}
catch (Exception e1)
{
e1.printStackTrace();
try
{
getListener().iNetListenedError(new BaseTransEx(NetHttpProcessor.getErrorMessage(NetworkErrorType.ERROR_RECEIVE).toString(), ((BaseTrans) tr).getParam()));
}
catch (Exception e2)
{
e2.printStackTrace();
}
try
{
getListener().iNetEnabled();
}
catch (Exception e2)
{
e2.printStackTrace();
}
}
this.processor.nextTask(taskSeq);
super.onPostExecute(result);
}
@Override
protected void onPreExecute()
{
try
{
getListener().iNetDisabled();
}
catch (Exception e)
{
e.printStackTrace();
}
this.httpClient = AndroidHttpClient.newInstance("HttpTask");
prepare();
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
/**
*
* @since 1.0.0
* @param inputStream
* @param bufferedReader
* @param entity
*/
private void cleanup(InputStream inputStream, BufferedReader bufferedReader, HttpEntity entity)
{
if (null != bufferedReader)
{
try
{
bufferedReader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
bufferedReader = null;
}
if (null != inputStream)
{
try
{
inputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
inputStream = null;
}
if (null != entity)
{
try
{
entity.consumeContent();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
/**
*
* @since 1.0.0
* @param buffer
* @param transactionClass
* @param param
* @return T transaction object
* @throws Exception
*/
protected abstract T parse(StringBuffer buffer, Class<? extends HttpTrans> transactionClass, BaseParam param) throws Exception;
/**
* prepare Http Task
*
* @since 1.0.0
* @throws Exception
*/
protected void prepare()
{
HttpTrans tr = (HttpTrans) this.tr;
HttpParam param = (HttpParam) tr.getParam();
if (param.isPostMethod())
{
this.uri = tr.getServiceUri() + tr.getCommandUri();
this.method = new HttpPost(this.uri);
if (param.isExistMultipart())
{
setMultipartParams((HttpPost) this.method);
}
else
{
setPostParams((HttpPost) this.method);
}
}
else
{
this.uri = tr.getServiceUri() + tr.getCommandUri();
this.uri = this.uri + setGetParams();
this.method = new HttpGet(this.uri);
}
setHeader();
}
/**
* set Header parameter
*
* @since 1.0.0
*/
protected void setHeader()
{
HttpTrans tr = (HttpTrans) this.tr;
HttpParam param = (HttpParam) tr.getParam();
LinkedHashMap<String, String> header = param.getHeader();
if (null != header && !header.isEmpty())
{
Set<Entry<String, String>> hashSet = header.entrySet();
final Iterator<Entry<String, String>> it = hashSet.iterator();
while (it.hasNext())
{
Map.Entry<String, String> me = (Map.Entry<String, String>) it.next();
this.method.setHeader(me.getKey(), me.getValue());
}
}
}
/**
* generate GET parameter string
*
* @since 1.0.0
* @return GET parameter string
*/
protected String setGetParams()
{
StringBuilder sb = new StringBuilder();
sb.append("");
HttpTrans tr = (HttpTrans) this.tr;
HttpParam param = (HttpParam) tr.getParam();
String queryString = param.getGetParams();
if (null != queryString)
{
sb.append("?");
sb.append(queryString);
}
return sb.toString();
}
/**
* set POST parameter
*
* @since 1.0.0
* @param method
*/
protected void setPostParams(HttpPost method)
{
HttpTrans tr = (HttpTrans) this.tr;
HttpParam param = (HttpParam) tr.getParam();
UrlEncodedFormEntity entity = param.getPostParams();
if (null != entity)
{
method.setEntity(entity);
}
}
/**
* set Multipart parameter
*
* @since 1.0.0
* @param method
*/
protected void setMultipartParams(HttpPost method)
{
HttpTrans tr = (HttpTrans) this.tr;
HttpParam param = (HttpParam) tr.getParam();
MultipartEntity entity = param.getMultipartParams();
if (null != entity)
{
method.setEntity(entity);
}
}
}