/*
BPAPI Android Library, auxiliary class for accessing BPAPI with BPAPI_Android.java
See http://api.connome.com/
Copyright (C) 2014 Connome AS, Norway
Version 1.0, september 2014
Licensing terms not decided as of September 2014 (A permissive license is most probable).
Please enquire as necessary to bjorn@connome.com
*/
package com.connome.connomeapp;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Base64;
import org.apache.http.NameValuePair;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
/**
* Created by pavelarteev on 18/01/14.
*/
public class NetworkModule extends AsyncTask{
public interface NetworkHandler {
void serverError(int code);
void serverEstablished(int code);
void dataReceived(String data);
void networkError();
}
public static final String WRONG_PASSWORD = "WRONG_PASSWORD";
private String urlString = null;
private NetworkHandler networkHandler = null;
private String responseData = "";
private int responseCode = -1;
//auth data
private String login = null;
private String password = null;
private boolean post = false;
private List paramsPost = null;
public NetworkModule(String urlString, NetworkHandler networkHandler){
this.networkHandler = networkHandler;
this.urlString = urlString;
}
public NetworkModule(String login, String password, String urlString, NetworkHandler networkHandler){
this.networkHandler = networkHandler;
this.urlString = urlString;
this.login = login;
this.password = password;
this.post = false;
}
public NetworkModule(String login, String password, String urlString, NetworkHandler networkHandler, List paramsPost){
this.networkHandler = networkHandler;
this.urlString = urlString;
this.login = login;
this.password = password;
this.post = true;
this.paramsPost = paramsPost;
}
private String bufferInputStreamToString(BufferedInputStream bin) throws IOException {
// byte array to store input
byte[] contents = new byte[1024];
int bytesRead=0;
String s;
String resultString = "";
while ((bytesRead = bin.read(contents)) != -1) {
s = new String(contents, 0, bytesRead);
if(s!=null){
resultString += s;
}
}
return resultString;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB) // API 11
public void startTask(String ...params) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
this.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
else
this.execute(params);
}
private String getQuery(List params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
private String bufferedReaderToString(BufferedReader br) throws IOException {
StringBuilder sb= new StringBuilder();
String line;
while ((line=br.readLine())!=null)
{
sb.append(line);
}
return sb.toString();
}
@Override
protected Integer doInBackground(String... params) {
URL url = null;
try {
url = new URL(this.urlString);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//AUTH
if(login!=null && password!=null){ //using auth
String authString = login + ":" + password;
String basicAuth = "Basic " + new String(Base64.encode(authString.getBytes(),Base64.NO_WRAP ));
urlConnection.setRequestProperty ("Authorization", basicAuth);
}
// Post request
if(post){
urlConnection.setRequestMethod("POST");
if(params!=null){
urlConnection.setDoOutput(true);
OutputStream os = urlConnection.getOutputStream();
BufferedWriter wr = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
wr.write(getQuery(paramsPost));
wr.flush();
wr.close();
os.close();
}
}
try{
try{
responseCode = urlConnection.getResponseCode();
if(responseCode==401){
urlConnection.disconnect();
return 401;
}
}catch(Exception e){
urlConnection.disconnect();
return -1;
}
// server replied
publishProgress(true);
// OLD not working good with encoding
//BufferedInputStream in = new BufferedInputStream(urlConnection.getInputStream());
//converting to String
//responseData = bufferInputStreamToString(in);
BufferedReader rd= new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
//converting to String
responseData = bufferedReaderToString(rd);
}catch (Exception e){
urlConnection.disconnect();
return 0;
}
urlConnection.disconnect();
}catch (Exception e){
e.printStackTrace();
return -1;
}
return 1;
}
@Override
protected void onProgressUpdate(Boolean... progress) {
if(networkHandler!=null) {
networkHandler.serverEstablished(responseCode);
}
}
@Override
protected void onPostExecute(Integer resultCode) {
if(networkHandler==null) {
return;
}
switch(resultCode){
case -1: // Network failure
networkHandler.networkError();
break;
case 200: // Server send error
networkHandler.dataReceived(responseData);
break;
default: // Server send error
networkHandler.serverError(responseCode);
break;
}
}
}