com.codemodlabs.coordinate.Token.java Source code

Java tutorial

Introduction

Here is the source code for com.codemodlabs.coordinate.Token.java

Source

/*
 * Copyright 2014 CodeModLabs LLC. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Created by nmelo on 8/14/14.
 */

package com.codemodlabs.coordinate;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.google.gson.Gson;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

class Token {
    public String access_token;
    public long expires_in;
    public String token_type;
    public String refresh_token;
    public String scope;

    Token() {
        // no-args constructor
    }
}

class Callback {
    public String key;
    public String access_code;
    public String state;

    Callback() {
        // no-args constructor
    }
}

public class BrowserActivity extends ActionBarActivity {

    private Token token;
    private Callback callback;

    private final String client_id = "CLbpYqzlE3y3zpJGHNUwQr7AbTyyX6go";
    private final String client_secret = "x2jhsocGxxCUSDQ3hByrIREF9j0TTDNQ9fjPNoBl";
    private final String redirect_url = "https://ubercoordinate.appspot.com/callback";

    private int BROWSER_ACTIVITY_RESULT = 1;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_browser);
        setTitle("Login");

        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        WebView webview = (WebView) findViewById(R.id.webView);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                progressBar.setVisibility(View.INVISIBLE);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith(redirect_url)) {
                    executeCallback(url);
                    return true;
                } else {
                    progressBar.setVisibility(View.INVISIBLE);
                    return false;
                }
            }
        });

        String code_endpoint = "https://login.uber.com/oauth/authorize?response_type=code&client_id=" + client_id;

        webview.loadUrl(code_endpoint);
    }

    private void executeCallback(String url) {
        class CallbackTask extends AsyncTask {
            @Override
            protected Object doInBackground(Object[] objects) {
                OkHttpClient client = new OkHttpClient();

                Request request = new Request.Builder().url((String) objects[0]).build();

                Response response = null;
                String body_string = "";
                try {
                    response = client.newCall(request).execute();
                    body_string = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Gson gson = new Gson();
                callback = gson.fromJson(body_string, Callback.class);
                return callback;
            }

            @Override
            protected void onPostExecute(Object result) {
                super.onPostExecute(result);
                try {
                    getTokenFromServer((Callback) result);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        new CallbackTask().execute(url);
    }

    private void getTokenFromServer(Callback callback) throws IOException {

        class GetTokenTask extends AsyncTask {

            @Override
            protected Object doInBackground(Object[] objects) {
                try {
                    final String access_code = ((Callback) objects[0]).access_code;
                    String url_string = "https://login.uber.com/oauth/token";

                    OkHttpClient client = new OkHttpClient();

                    // Ignore invalid SSL endpoints.
                    client.setHostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String s, SSLSession sslSession) {
                            return true;
                        }
                    });

                    RequestBody formBody = new FormEncodingBuilder().add("client_secret", client_secret)
                            .add("client_id", client_id).add("grant_type", "authorization_code")
                            .add("redirect_uri", redirect_url).add("code", access_code).build();
                    Request request = new Request.Builder().url(url_string).post(formBody).build();

                    Response response = client.newCall(request).execute();
                    String response_body = response.body().string();

                    Gson gson = new Gson();
                    token = gson.fromJson(response_body, Token.class);
                    return token;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Object result) {
                super.onPostExecute(result);
                Token token = (Token) result;

                Intent resultIntent = new Intent();
                resultIntent.putExtra("access_token", token.access_token);
                resultIntent.putExtra("expires_in", token.expires_in);
                resultIntent.putExtra("token_type", token.token_type);
                resultIntent.putExtra("refresh_token", token.refresh_token);
                resultIntent.putExtra("scope", token.scope);

                setResult(2, resultIntent);
                finish();
            }
        }
        new GetTokenTask().execute(callback);
    }
}