<commit_before>/*
 * ********************************************************************************************************************
 *  <p/>
 *  BACKENDLESS.COM CONFIDENTIAL
 *  <p/>
 *  ********************************************************************************************************************
 *  <p/>
 *  Copyright 2012 BACKENDLESS.COM. All Rights Reserved.
 *  <p/>
 *  NOTICE: All information contained herein is, and remains the property of Backendless.com and its suppliers,
 *  if any. The intellectual and technical concepts contained herein are proprietary to Backendless.com and its
 *  suppliers and may be covered by U.S. and Foreign Patents, patents in process, and are protected by trade secret
 *  or copyright law. Dissemination of this information or reproduction of this material is strictly forbidden
 *  unless prior written permission is obtained from Backendless.com.
 *  <p/>
 *  ********************************************************************************************************************
 */

package com.backendless.example.loginwithgoogleplussdk.app;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.ArrayAdapter;
import com.backendless.Backendless;
import com.backendless.BackendlessUser;
import com.backendless.async.callback.AsyncCallback;
import com.backendless.exceptions.BackendlessFault;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class LoginFragment extends Fragment implements GoogleApiClient.OnConnectionFailedListener
{
  static final String TAG = "LoginFragment";
  private static final int RC_SIGN_IN = 10001;
  private static final int RC_SIGN_OUT = 10002;
  private boolean logined = false;
  private static final String SERVER_CLIENT_ID = "395504112005-c6djad11b87f5jjm9gsb22s4ht6vdg0i.apps.googleusercontent.com";

  private GoogleSignInOptions gSignInOptions;
  private GoogleApiClient gApiClient;

  @Override
  public void onCreate( Bundle savedInstanceState )
  {
    super.onCreate( savedInstanceState );

    FragmentActivity fragmentActivity = (FragmentActivity)this.getActivity();

    gSignInOptions = new GoogleSignInOptions.Builder( GoogleSignInOptions.DEFAULT_SIGN_IN )
            .requestEmail().requestProfile().requestId().requestIdToken( SERVER_CLIENT_ID )
            .build();

    // Build a GoogleApiClient with access to GoogleSignIn.API and the options above.
    GoogleApiClient.Builder apiCliBuilder = new GoogleApiClient.Builder( fragmentActivity );
    gApiClient = apiCliBuilder
            .enableAutoManage( fragmentActivity, this )
            .addApi( Auth.GOOGLE_SIGN_IN_API, gSignInOptions ).build();
  }

  @Override
  public void onConnectionFailed( ConnectionResult connectionResult )
  {
    Log.d( TAG, "Connection failed" );
  }

  public void login_logout()
  {
    showProgressDialog();
    if (logined)
    {
      logoutFromBackendless();
      Auth.GoogleSignInApi.signOut( gApiClient ).setResultCallback( new ResultCallback<Status>()
      {
        @Override
        public void onResult( Status status )
        {
          handleSignOutResult( status );
        }
      } );
    }
    else
    {
      Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent( gApiClient );
      this.startActivityForResult( signInIntent, RC_SIGN_IN );
    }
  }

  @Override
  public void onActivityResult( int requestCode, int resultCode, Intent data )
  {
    super.onActivityResult(requestCode, resultCode, data);

    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
      GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
      handleSignInResult(result);
    }
  }

  private void handleSignInResult(GoogleSignInResult result) {
    Log.d( TAG, "handleSignInResult: success is " + result.isSuccess() );

    if (result.isSuccess()) {
      logined = true;
      refreshUIonLogin( this.getActivity(), result.getSignInAccount() );
      loginInBackendless( result.getSignInAccount() );
    } else
    {
      logined = false;
      refreshUIonLogout();
      // Signed out, show unauthenticated UI.
    }
    hideProgressDialog();
  }

  private void handleSignOutResult( Status status )
  {
    logined = false;
    refreshUIonLogout();
    hideProgressDialog();
  }

  private void loginInBackendless(final GoogleSignInAccount acct)
  {
    Log.d( TAG, "handleSignInResult: try login to backendless" );

    final MainActivity mainActivity = (MainActivity)this.getActivity();
    final String accountName = acct.getEmail();
    final String scopes = "oauth2:" + Scopes.PLUS_LOGIN + " " + Scopes.PLUS_ME + " " + Scopes.PROFILE + " " + Scopes.EMAIL;

    AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>(){
      @Override
      protected String doInBackground( Void... params )
      {
        String token = null;
        try
        {
          token = GoogleAuthUtil.getToken( mainActivity, accountName, scopes );
          GoogleAuthUtil.invalidateToken( mainActivity, token );
          handleAccessTokenInBackendless( acct.getIdToken(), token );
        }
        catch( Exception e )<commit_msg>updated google plus sample<commit_after>/*
 * ********************************************************************************************************************
 *  <p/>
 *  BACKENDLESS.COM CONFIDENTIAL
 *  <p/>
 *  ********************************************************************************************************************
 *  <p/>
 *  Copyright 2012 BACKENDLESS.COM. All Rights Reserved.
 *  <p/>
 *  NOTICE: All information contained herein is, and remains the property of Backendless.com and its suppliers,
 *  if any. The intellectual and technical concepts contained herein are proprietary to Backendless.com and its
 *  suppliers and may be covered by U.S. and Foreign Patents, patents in process, and are protected by trade secret
 *  or copyright law. Dissemination of this information or reproduction of this material is strictly forbidden
 *  unless prior written permission is obtained from Backendless.com.
 *  <p/>
 *  ********************************************************************************************************************
 */

package com.backendless.example.loginwithgoogleplussdk.app;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.ArrayAdapter;
import com.backendless.Backendless;
import com.backendless.BackendlessUser;
import com.backendless.async.callback.AsyncCallback;
import com.backendless.exceptions.BackendlessFault;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class LoginFragment extends Fragment implements GoogleApiClient.OnConnectionFailedListener
{
  static final String TAG = "LoginFragment";
  private static final int RC_SIGN_IN = 10001;
  private static final int RC_SIGN_OUT = 10002;
  private static final int REQUEST_AUTHORIZATION = 10003;
  private boolean logined = false;
  private static final String SERVER_CLIENT_ID = "395504112005-c6djad11b87f5jjm9gsb22s4ht6vdg0i.apps.googleusercontent.com";

  private GoogleSignInOptions gSignInOptions;
  private GoogleApiClient gApiClient;

  @Override
  public void onCreate( Bundle savedInstanceState )
  {
    super.onCreate( savedInstanceState );

    FragmentActivity fragmentActivity = (FragmentActivity)this.getActivity();

    gSignInOptions = new GoogleSignInOptions.Builder( GoogleSignInOptions.DEFAULT_SIGN_IN )
            .requestEmail().requestProfile().requestId().requestIdToken( SERVER_CLIENT_ID )
            .build();

    // Build a GoogleApiClient with access to GoogleSignIn.API and the options above.
    GoogleApiClient.Builder apiCliBuilder = new GoogleApiClient.Builder( fragmentActivity );
    gApiClient = apiCliBuilder
            .enableAutoManage( fragmentActivity, this )
            .addApi( Auth.GOOGLE_SIGN_IN_API, gSignInOptions ).build();
  }

  @Override
  public void onConnectionFailed( ConnectionResult connectionResult )
  {
    Log.d( TAG, "Connection failed" );
  }

  public void login_logout()
  {
    showProgressDialog();
    if (logined)
    {
      logoutFromBackendless();
      Auth.GoogleSignInApi.signOut( gApiClient ).setResultCallback( new ResultCallback<Status>()
      {
        @Override
        public void onResult( Status status )
        {
          handleSignOutResult( status );
        }
      } );
    }
    else
    {
      Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent( gApiClient );
      this.startActivityForResult( signInIntent, RC_SIGN_IN );
    }
  }

  @Override
  public void onActivityResult( int requestCode, int resultCode, Intent data )
  {
    super.onActivityResult(requestCode, resultCode, data);

    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
      GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
      handleSignInResult(result);
    }
  }

  private void handleSignInResult(GoogleSignInResult result) {
    Log.d( TAG, "handleSignInResult: success is " + result.isSuccess() );

    if (result.isSuccess()) {
      logined = true;
      refreshUIonLogin( this.getActivity(), result.getSignInAccount() );
      loginInBackendless( result.getSignInAccount() );
    } else
    {
      logined = false;
      refreshUIonLogout();
      // Signed out, show unauthenticated UI.
    }
    hideProgressDialog();
  }

  private void handleSignOutResult( Status status )
  {
    logined = false;
    refreshUIonLogout();
    hideProgressDialog();
  }

  private void loginInBackendless(final GoogleSignInAccount acct)
  {
    Log.d( TAG, "handleSignInResult: try login to backendless" );

    final MainActivity mainActivity = (MainActivity)this.getActivity();
    final String accountName = acct.getEmail();
    final String scopes = "oauth2:" + Scopes.PLUS_LOGIN + " " + Scopes.PLUS_ME + " " + Scopes.PROFILE + " " + Scopes.EMAIL;

    AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>(){
      @Override
      protected String doInBackground( Void... params )
      {
        String token = null;
        try
        {
          token = GoogleAuthUtil.getToken( mainActivity, accountName, scopes );
          GoogleAuthUtil.invalidateToken( mainActivity, token );
          handleAccessTokenInBackendless( acct.getIdToken(), token );
        }
        catch ( UserRecoverableAuthException e )
        {
          startActivityForResult( e.getIntent(), REQUEST_AUTHORIZATION );
        }
        catch( Exception e )
{'fraction_non_alphanumeric': 0.14415363422737218, 'fraction_numerical': 0.006887610404343246, 'mean_word_length': 4.0252442996742674, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6083552', 'n_tokens_mistral': 3537, 'n_tokens_neox': 3416, 'n_words': 805}