Android Open Source - unicef_gis_mobile Unicef Gis Api






From Project

Back to project page unicef_gis_mobile.

License

The source code is released under:

MIT License

If you think the Android project unicef_gis_mobile listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package org.unicef.gis.infrastructure;
//from  w  w w .j  ava 2 s .c o m
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.http.client.HttpResponseException;
import org.json.JSONArray;
import org.unicef.gis.model.Tag;

import android.accounts.Account;
import android.annotation.SuppressLint;
import android.content.Context;
import android.net.Credentials;
import android.util.Base64;
import android.util.Log;
import edu.mit.mobile.android.utils.StreamUtils;

public class UnicefGisApi {
  private static final String TAG = UnicefGisApi.class.getSimpleName();
  public final static String JSON_MIME_TYPE = "application/json";

  protected URI baseUrl;
  
  // one of the formats from ISO 8601
  @SuppressLint("SimpleDateFormat")
  public final static SimpleDateFormat dateFormat = new SimpleDateFormat(
      "yyyy-MM-dd'T'HH:mm:ss'Z'");

  //TODO: erased auth, accept-language and remove expectations interceptors, may need to implement an alternative
  public static final String PREF_LOCAST_SITE = "locast_site";

  private final RoutesResolver routes;
  
  /**
   * Create a new NetworkClient, authenticating with the given account.
   *
   * @param context
   * @param account
   * @throws MalformedURLException 
   */
  public UnicefGisApi(Context context, Account account) throws MalformedURLException {
    this(context);
  }

  /**
   * Create a new NetworkClient using the baseUrl. You will need to call
   * {@link #setCredentials(Credentials)} at some point if you want authentication.
   *
   * @param context
   * @param baseUrl
   */
  public UnicefGisApi(Context context) {
    super();
    this.routes = new RoutesResolver(context);
  }
  
  public String authenticate(final String email, final String password) {
    HttpURLConnection conn = null;
    try {
      URL url = routes.getUser();
      conn = (HttpURLConnection) url.openConnection();
      
      String token = email + ":" + password;
      String encodedAuthorization = Base64.encodeToString(token.getBytes(), Base64.NO_WRAP);
      conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
      
      if (conn.getResponseCode() == HttpURLConnection.HTTP_OK)
        return token;
      else
        return null;
    } catch (IOException e) {
      Log.e(TAG, "authenticate: " + e.getMessage());
      
      if (conn != null){
        try {
          String errors = StreamUtils.inputStreamToString(new BufferedInputStream(conn.getErrorStream()));
          Log.e(TAG, "authenticate: server response: " + errors);
        } catch (IOException e1) {
          Log.e(TAG, "authenticate: handle error stream: " + e1.getMessage());
          e1.printStackTrace();
        }
      }
      
      return null;    
    } catch (ServerUrlPreferenceNotSetException e) {
      e.printStackTrace();
      Log.e(TAG, "authenticate: failed because there's no Server URL set up");
      return null;
    } finally {
      if (conn != null) conn.disconnect();
    }
  }

  public List<Tag> getTags() throws ServerUrlPreferenceNotSetException {
    JSONArray tags = getArray(routes.getTags());
    
    if (tags == null) return null;
    
    return Tag.listFromJSON(tags);  
  }
  
  /**
   * Makes a GET request to the given url
   * @param url
   * @return a JSONObject containing the response if the request succeeded, null otherwise
   */
  private JSONArray getArray(final URL url) {
    HttpURLConnection conn = null;
    
    try {
      conn = (HttpURLConnection) url.openConnection();
      
      //Disable the requirement of GZIP to the server (it'd be nice to eventually reenable it)
      conn.setRequestProperty("Accept-Encoding", "identity");
      
      InputStream responseStream = conn.getInputStream();
      
      boolean requestSucceeded = conn.getResponseCode() == HttpURLConnection.HTTP_OK;
      if (!requestSucceeded) {

        Log.d("SyncAdapter", "Tags request failed with Http Code: " + conn.getResponseCode());
        
        handleRequestFailure(conn);
      } else {
        String response = StreamUtils.inputStreamToString(new BufferedInputStream(responseStream));
        
        Log.d("SyncAdapter", "Tags downloaded from server: " + response);
        
        return new JSONArray(response);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (conn != null) conn.disconnect();
    }
    
    return null;
  }

  private boolean handleRequestFailure(HttpURLConnection conn) throws IOException {
    int statusCode = conn.getResponseCode();
    String errorMessage = conn.getResponseMessage();
    
    if (conn.getContentType().equals("text/html") || conn.getContentLength() > 40)
      errorMessage = "Got long response body. Not showing.";        
    else if (errorMessage == null) errorMessage = "HTTP request failed";
    
    Log.d(TAG, "handleRequestFailure: " + errorMessage);
    throw new HttpResponseException(statusCode, errorMessage);
  }
}




Java Source Code List

com.couchbase.cblite.ektorp.CBLiteHttpClient.java
com.couchbase.cblite.ektorp.CBLiteHttpResponse.java
edu.mit.mobile.android.utils.StreamUtils.java
org.unicef.gis.auth.AuthenticatorService.java
org.unicef.gis.auth.Authenticator.java
org.unicef.gis.infrastructure.CompileTimeSettings.java
org.unicef.gis.infrastructure.ILocationServiceConsumer.java
org.unicef.gis.infrastructure.LocationService.java
org.unicef.gis.infrastructure.Network.java
org.unicef.gis.infrastructure.Notificator.java
org.unicef.gis.infrastructure.RoutesResolver.java
org.unicef.gis.infrastructure.ServerUrlPreferenceNotSetException.java
org.unicef.gis.infrastructure.UnicefGisApi.java
org.unicef.gis.infrastructure.data.CouchDbLiteStoreAdapter.java
org.unicef.gis.infrastructure.data.UnicefGisContentProvider.java
org.unicef.gis.infrastructure.data.UnicefGisStore.java
org.unicef.gis.infrastructure.image.AsyncDrawable.java
org.unicef.gis.infrastructure.image.BitmapWorkerTask.java
org.unicef.gis.infrastructure.image.Camera.java
org.unicef.gis.model.Report.java
org.unicef.gis.model.Tag.java
org.unicef.gis.model.couchdb.NullReduce.java
org.unicef.gis.model.couchdb.ReportLoader.java
org.unicef.gis.model.couchdb.views.AllReportsByTimestampDesc.java
org.unicef.gis.model.couchdb.views.PendingSyncReports.java
org.unicef.gis.model.couchdb.views.UnicefGisView.java
org.unicef.gis.model.couchdb.views.UploadedReports.java
org.unicef.gis.sync.SyncAdapter.java
org.unicef.gis.sync.SyncService.java
org.unicef.gis.ui.AlertDialogFragment.java
org.unicef.gis.ui.AuthenticatorActivity.java
org.unicef.gis.ui.ConfigureServerUrlActivity.java
org.unicef.gis.ui.DeleteUploadedReportsTask.java
org.unicef.gis.ui.FetchTagsActivity.java
org.unicef.gis.ui.FetchTagsTask.java
org.unicef.gis.ui.MyReportsActivity.java
org.unicef.gis.ui.SettingsActivity.java
org.unicef.gis.ui.SettingsFragment.java
org.unicef.gis.ui.report.ChooseTagsFragment.java
org.unicef.gis.ui.report.CreateReportActivityConstants.java
org.unicef.gis.ui.report.CreateReportActivity.java
org.unicef.gis.ui.report.GetTagsTaskFragment.java
org.unicef.gis.ui.report.GetTagsTask.java
org.unicef.gis.ui.report.IChooseTagsCallbacks.java
org.unicef.gis.ui.report.IGetTagsCallback.java
org.unicef.gis.ui.report.IGetTagsTaskFragmentCallbacks.java
org.unicef.gis.ui.report.IReportSummaryCallbacks.java
org.unicef.gis.ui.report.ReportRowAdapter.java
org.unicef.gis.ui.report.ReportSummaryFragment.java
org.unicef.gis.ui.report.ReportViewModel.java
org.unicef.gis.ui.report.ToggleTagAdapter.java