com.frublin.androidoauth2.FsDialog.java Source code

Java tutorial

Introduction

Here is the source code for com.frublin.androidoauth2.FsDialog.java

Source

/*
 * Copyright 2010 Foursquare, Inc.
 *
 * 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.
 */

package com.frublin.androidoauth2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

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

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Display;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.frublin.androidoauth2.AndroidOAuth.FSDialogListener;

public class FsDialog extends Dialog {

    static final int FS_BLUE = 0xFF6D84B4;
    static final float[] DIMENSIONS_LANDSCAPE = { 460, 260 };
    static final float[] DIMENSIONS_PORTRAIT = { 280, 420 };
    static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
            ViewGroup.LayoutParams.FILL_PARENT);
    static final int MARGIN = 4;
    static final int PADDING = 2;
    static final String DISPLAY_STRING = "touch";

    private String mUrl;
    private FSDialogListener mListener;
    private ProgressDialog mSpinner;
    private WebView mWebView;
    private LinearLayout mContent;
    private TextView mTitle;

    private String LOG_TAG = "Foursquare Dialog: ";

    private AndroidOAuth androidOAuth;
    private Context parentContext;

    public FsDialog(Context context, String url, FSDialogListener listener, AndroidOAuth mAndroidOAuth) {
        super(context);
        mUrl = url;
        mListener = listener;
        androidOAuth = mAndroidOAuth;
        parentContext = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSpinner = new ProgressDialog(getContext());
        mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mSpinner.setMessage("Loading...");

        mContent = new LinearLayout(getContext());
        mContent.setOrientation(LinearLayout.VERTICAL);
        setUpTitle();
        setUpWebView();
        Display display = getWindow().getWindowManager().getDefaultDisplay();
        final float scale = getContext().getResources().getDisplayMetrics().density;
        float[] dimensions = (display.getWidth() < display.getHeight()) ? DIMENSIONS_PORTRAIT
                : DIMENSIONS_LANDSCAPE;
        addContentView(mContent, new FrameLayout.LayoutParams((int) (dimensions[0] * scale + 0.5f),
                (int) (dimensions[1] * scale + 0.5f)));
    }

    private void setUpTitle() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        Drawable icon = getContext().getResources().getDrawable(R.drawable.foursquareicon);
        mTitle = new TextView(getContext());
        mTitle.setText("Foursquare");
        mTitle.setTextColor(Color.WHITE);
        mTitle.setTypeface(Typeface.DEFAULT_BOLD);
        mTitle.setBackgroundColor(FS_BLUE);
        mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
        mTitle.setCompoundDrawablePadding(MARGIN + PADDING);
        mTitle.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
        mContent.addView(mTitle);
    }

    private void setUpWebView() {
        mWebView = new WebView(getContext());
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.setWebViewClient(new FsDialog.FsWebViewClient());
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl(mUrl);
        mWebView.setLayoutParams(FILL);
        mContent.addView(mWebView);
    }

    private class FsWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d("Foursquare-WebView", "Redirect URL: " + url);
            if (url.startsWith(AndroidOAuth.REDIRECT_URI)) {

                String authorizedCode = (Uri.parse(url)).getQueryParameter("code");
                Log.d(LOG_TAG, "Auth code: " + authorizedCode);
                Log.d(LOG_TAG, "Auth URL : " + androidOAuth.getAccessTokenUrl(authorizedCode));
                HttpGet request = new HttpGet(androidOAuth.getAccessTokenUrl(authorizedCode));

                DefaultHttpClient client = new DefaultHttpClient();

                try {

                    HttpResponse resp = client.execute(request);
                    int responseCode = resp.getStatusLine().getStatusCode();
                    Log.d(LOG_TAG, "Reponse code: " + responseCode);

                    if (responseCode >= 200 && responseCode < 300) {

                        String response = responseToString(resp);
                        JSONObject jsonObj = new JSONObject(response);
                        androidOAuth.saveAccessToken(PreferenceManager.getDefaultSharedPreferences(parentContext),
                                jsonObj.getString("access_token"));

                    } else {
                        Log.e(LOG_TAG, "Foursquare error: " + responseToString(resp));
                        mListener.onFoursquareError(
                                new FoursquareError("Authentication Failed with Response Code: " + responseCode));
                    }
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                mListener.onComplete();

                FsDialog.this.dismiss();
                return true;
            } else if (url.startsWith(AndroidOAuth.CANCEL_URI)) {
                mListener.onCancel();
                FsDialog.this.dismiss();
                return true;
            } else if (url.contains(DISPLAY_STRING)) {
                return false;
            }
            // launch non-dialog URLs in a full browser
            getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        }

        private String responseToString(HttpResponse resp) throws IllegalStateException, IOException {
            BufferedReader in = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));

            StringBuffer sb = new StringBuffer();

            String line = "";

            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            in.close();

            return sb.toString();
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            mListener.onError(new DialogError(description, errorCode, failingUrl));
            FsDialog.this.dismiss();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.d("Foursquare-WebView", "Webview loading URL: " + url);
            super.onPageStarted(view, url, favicon);
            mSpinner.show();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            String title = mWebView.getTitle();
            if (title != null && title.length() > 0) {
                mTitle.setText(title);
            }
            mSpinner.dismiss();
        }

    }
}