Package almonds

Source Code of almonds.ParseUser$Logger

package almonds;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ParseUser extends ParseObject{

  private static ParseUser instance;
  private Object mutex = new Object();
  private String password;
  private String sessionToken;
  private boolean emailVerified = false;
  private boolean emailVerifiedChanged = false;

  public static ParseUser getCurrentUser(){
    return instance;
  }
 
  public static void becomeInBackground(final String sessionToken, final LogInCallback callback){
    new Thread(new Runnable() {
     
      @Override
      public void run() {
        ParseUser.become(sessionToken, callback);
      }
    }).start();
  }
 
  /**
   * if you maintain multithreading by your own
   * @param callback
   */
  public static void become(String sessionToken, LogInCallback callback) {
    instance = new ParseUser();
    instance.new Logger(sessionToken, callback);
  }

  /**
   * if you maintain multithreading by your own
   * @param callback
   */
  public static void logIn(String userName, String password, LogInCallback callback){
    instance = new ParseUser();
    instance.new Logger(userName, password, callback);
  }
 

  public static void logInBackground(final String userName, final String password, final LogInCallback callback){
    new Thread(new Runnable() {

      @Override
      public void run() {
        ParseUser.logIn(userName, password, callback);
      }
    }).start();
  }

  public ParseUser()   {
    super("_User");
    instance = this;
  }

  @Override
  protected void setSessionToken(String sessionToken){
    this.sessionToken = sessionToken;
  }

  @Override
  public String getSessionToken(){
    synchronized (this.mutex) {
      return this.sessionToken;
    }
  }

  public void setUsername(String userName){
    put("username", userName);
  }

  public String getUsername() {
    return getString("username");
  }

  public void setPassword(String password){
    synchronized (this.mutex){
      put("password", password);
      this.password = password;
    }   
  }

  public void setEmail(String email) {
    put("email", email);
  }

  public String getEmail() {
    return getString("email");
  }
 
  public boolean isEmailVerified() throws ParseException {
    if(emailVerifiedChanged == false)
      throw new ParseException(ParseException.OTHER_CAUSE, "You did not enable email verification in your app");
    return emailVerified;
  }

  /**
   * it doesn't work error 206 UserCannotBeAlteredWithoutSessionError
   */
  @Override
  public void delete() throws ParseException {
    try  {
      HttpClient httpclient = new DefaultHttpClient();

      HttpDelete httpdelete = new HttpDelete(Parse.getParseAPIUrlUsersDelete());
      httpdelete.addHeader("X-Parse-Application-Id", Parse.getApplicationId());
      httpdelete.addHeader("X-Parse-REST-API-Key", Parse.getRestAPIKey());
      httpdelete.addHeader("X-Parse-Session-Token", sessionToken);

      HttpResponse httpresponse = httpclient.execute(httpdelete);

      ParseResponse response = new ParseResponse(httpresponse);
      System.out.println(response.getJsonObject().toString());
      if (!response.isFailed()) {
        // delete was successful
      }
      else{
        throw response.getException();
      }
    }
    catch (ClientProtocolException e){
      throw ParseResponse.getConnectionFailedException(e.getMessage());
    }catch (IOException e)  {
      throw ParseResponse.getConnectionFailedException(e.getMessage());
    }
  }
 
  /**
   * it doesn't work error 206 UserCannotBeAlteredWithoutSessionError
   */
  @Override
  public void deleteInBackground(){
    this.deleteInBackground(null);
  }
 
  /**
   * it doesn't work error 206 UserCannotBeAlteredWithoutSessionError
   */
  @Override
  public void deleteInBackground(final DeleteCallback callback){
    new Thread(new Runnable() {
     
      @Override
      public void run() {
        ParseException e = null;
        try {
          delete();
        } catch (ParseException ee) {
          e = ee;
        }
        if(callback != null)
          callback.done(e);
      }
    }).start();
  }
 
  /**
   * if you maintain multithreading by your own
   * @param callback
   */
  public void signUp(final SignUpCallback callback){
    synchronized (mutex) {
      if ((getUsername() == null) || (getUsername().length() == 0)) {
        throw new IllegalArgumentException("Username cannot be missing or blank");
      }

      if (password == null) {
        throw new IllegalArgumentException("Password cannot be missing or blank");
      }

      if(getObjectId() == null){
        ParseException e = null;
        try {
          save();
        } catch (ParseException e1) {
          e = e1;
        }
        callback.done(e);
      }
    }
  } 

  public void signUpInBackground(final SignUpCallback callback){
    new Thread(new Runnable() {

      @Override
      public void run() {
        signUp(callback);
      }
    }).start();
  }
 
  private class Logger{
 
    public Logger(String sessionToken, LogInCallback callback) {
      ParseException e = null;
      try {
        log(prepareHttpGet(sessionToken));
      } catch (ParseException ee) {
        e = ee;
        instance = null;
      }
      callback.done(instance, e);
    }
   
    public Logger(String userName, String password, LogInCallback callback){
      ParseException ee = null;
      try {
        try {
          log(prepareHttpGet(userName, password));
        } catch (UnsupportedEncodingException e) {
          throw new ParseException(ParseException.INVALID_JSON, "Wrong in userName or password");
        }
      } catch (ParseException e) {
        ee = e;
      }
      if(ee == null){
        put("username", userName);
        put("password", password);

      }
      callback.done(instance, ee);
    }
   
    private HttpGet prepareHttpGet(String sessionToken){
      HttpGet httpget = new HttpGet(Parse.getParseAPIUrlSessionTokenValidation());
      httpget.addHeader("X-Parse-Application-Id", Parse.getApplicationId());
      httpget.addHeader("X-Parse-REST-API-Key", Parse.getRestAPIKey());
      httpget.addHeader("X-Parse-Session-Token", sessionToken);
      httpget.addHeader("Content-Type", "application/json");
      return httpget;
    }
   
    private HttpGet prepareHttpGet(String userName, String password) throws UnsupportedEncodingException{
      String userNameX = "?";
      userNameX += URLEncoder.encode("username="+userName, "UTF-8");
      userNameX += "&";
      userNameX += URLEncoder.encode("password="+password, "UTF-8");

      HttpGet httpget = new HttpGet(Parse.getParseAPIUrlLogin() + userNameX);
      httpget.addHeader("X-Parse-Application-Id", Parse.getApplicationId());
      httpget.addHeader("X-Parse-REST-API-Key", Parse.getRestAPIKey());
      httpget.addHeader("Content-Type", "application/json");
      return httpget;
    }
   
    private void log(HttpGet httpget) throws ParseException{
      try{
        HttpClient httpclient = new DefaultHttpClient();

        HttpResponse httpresponse = httpclient.execute(httpget);
        ParseResponse response = new ParseResponse(httpresponse);

        if (!response.isFailed()) {
          JSONObject jsonResponse = response.getJsonObject();

          if (jsonResponse == null) {
            throw response.getException();
          }
          try  {
            setObjectId(jsonResponse.getString("objectId"));
            setCreatedAt(jsonResponse.getString("createdAt"));
            setSessionToken(jsonResponse.getString("sessionToken"));
            setEmail(jsonResponse.getString("email"));
            setUsername(jsonResponse.getString("username"));
           
            try{
              emailVerified = jsonResponse.getBoolean("emailVerified");
              emailVerifiedChanged = true;
            } catch (Exception e) {
             
            } 
            addOtherNames(getOtherFieldNames(jsonResponse.names()), jsonResponse);
          }catch (JSONException e){
            throw new ParseException(
                ParseException.INVALID_JSON,
                "Although Parse reports object successfully saved, the response was invalid.",
                e);
          }
        }else{
          try {
            JSONObject object = response.getJsonObject();
            if(object.getString("error").equals("invalid session") &&
                object.getInt("code") == 101){
              throw new ParseException(ParseException.INVALID_JSON, "Wrong sessionToken. "
                  + "You do not have a user with this sessionToken.");
            }
          } catch (JSONException e) {
            throw response.getException();
          }
          throw response.getException();
        }
      }catch (ClientProtocolException e) {
        throw ParseResponse.getConnectionFailedException(e);
      } catch (IOException e) {
        throw ParseResponse.getConnectionFailedException(e);
      }
    }

    private void addOtherNames(ArrayList<String> otherFieldNames,
        JSONObject jsonResponse) throws JSONException {
      for(int i = 0; i < otherFieldNames.size(); i++)
        put(otherFieldNames.get(i), jsonResponse.get(otherFieldNames.get(i)));
    }

    private ArrayList<String> getOtherFieldNames(JSONArray names) throws JSONException {
      ArrayList<String> lista = new ArrayList<String>();
      for(int i = 0; i < names.length(); i++){
        String n = (String) names.get(i);
        if(!n.equals("updatedAt") && !n.equals("sessionToken") && !n.equals("username") && !n.equals("email")
            && !n.equals("objectId") && !n.equals("createdAt") && !n.equals("emailVerified")){
          lista.add(n);
        }
      }
      return lista;
    }
   
  }
}
TOP

Related Classes of almonds.ParseUser$Logger

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.