cn.edu.sdnu.i.util.xauth.Xauth.java Source code

Java tutorial

Introduction

Here is the source code for cn.edu.sdnu.i.util.xauth.Xauth.java

Source

package cn.edu.sdnu.i.util.xauth;

/*
 * XAuth.java
 *
 * Copyright (C) 2005-2010 Tommi Laukkanen
 * http://www.substanceofcode.com
 *
 * 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.
 */

import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Xml.Encoding;
import cn.edu.sdnu.i.LoginActivity;

/**
 * 
 * @author HennSun xAuth xAuth?????OAuth??
 *         ????xAuth?????????OAuth
 *         Access Token? xAuth???oauth/request_token?Request
 *         Token?oauth/authorize?Request
 *         Token????usernamepassword???oauth/access_token?Access
 *         Token
 */
public class Xauth extends Thread {

    private String xauthUsername;
    private String xauthPassword;

    private static String token;
    private static String tokenSecret;

    private static final String OAuthVersion = "1.0";
    private static String consumerKey = "53f48ec66af68087d85ff2610e451258";
    private static String consumerSecret = "7d164b452bcfebf627dbc7e393eabe0effc7ead6";
    private static final String XAuthMode = "client_auth";
    private static final String HMACSHA1SignatureType = "HMAC-SHA1";

    public static final String BASE_URL = "http://210.44.14.10/OAuth/";
    public static final String AUTH_URL = "AccessToken.ashx";
    public static final String REST_URL = "Rest.ashx";

    private static final int _fetchTimeout = 5000;

    public static HttpClient httpClient = new DefaultHttpClient();

    private Handler mHanlerGlobal;
    private String urlGlobal;
    private boolean flag = true;

    public Xauth(String username, String password) {
        this.xauthUsername = username;
        this.xauthPassword = password;

        doAccessToken();
    }

    //?? ? .
    public void setHandlerUrl(Handler mHandler, String url) {
        this.mHanlerGlobal = mHandler;
        this.urlGlobal = url;
    }

    @Override
    public void run() {
        Message message;
        if (flag) {
            doAccessToken(); //??.
            flag = false;
        }
        String result = doMethod(this.urlGlobal);
        if (result.length() > 0) {
            message = this.mHanlerGlobal.obtainMessage(1, result);
        } else {
            message = this.mHanlerGlobal.obtainMessage(0, result);
        }
        message.sendToTarget();

    }

    // ?token
    private void doAccessToken() {

        // ?TreeMapparameters?????url?
        TreeMap<String, String> parameters = new TreeMap<String, String>();

        // 1.consumerkeyapp???keykey??app?key
        parameters.put(Constants.ConsumerKeyParameter, consumerKey);
        Log.d("test", "1.consumerKey:" + consumerKey);

        // 2.UUID???????
        /*
         * ?GUID
         * 
         * 
         * ??GUID???????10GUID?
         * ??? FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF
         */

        UUID uuid = UUID.randomUUID();

        // ????ws?
        String guid = uuid.toString();

        // nonce
        parameters.put(Constants.NonceParameter, guid);
        Log.d("test", "2.guid:" + guid);

        // 3.?Hmacsha1
        parameters.put(Constants.SignatureMethodParameter, HMACSHA1SignatureType);
        Log.d("test", "3.SignatureMethodParameter:" + HMACSHA1SignatureType);

        // 4.
        /*
         * 
         * 
         * 
         * Unix???UTC??197011000??? ?2014/1/29
         * 16:56:58UTC+8UTC2014/1/29
         * 8:56:58?Unix160998565813909858181390985818
         * ??60?
         */
        parameters.put(Constants.TimestampParameter, Long.toString(System.currentTimeMillis() / 1000));
        Log.d("test", "4.TimestampParameter:" + Long.toString(System.currentTimeMillis() / 1000));

        // 5.XAuth??1.0?
        parameters.put(Constants.VersionParameter, OAuthVersion);
        Log.d("test", "5.VersionParameter:" + OAuthVersion);

        // 6."client_auth"
        parameters.put(Constants.AuthModeParameter, XAuthMode);
        Log.d("test", "6.AuthModeParameter:" + XAuthMode);

        // 7.?8.??
        parameters.put(Constants.AuthPasswordParameter, this.xauthPassword);
        parameters.put(Constants.AuthUsernameParameter, this.xauthUsername);
        Log.d("test", "7.AuthPasswordParameter:" + xauthPassword);
        Log.d("test", "8.AuthUsernameParameter:" + xauthUsername);

        // ????
        // ??StringBuffer?String??result
        StringBuffer resultBuffer = new StringBuffer("");

        // http?statusresult

        Boolean status = TryRequestRemote(BASE_URL + AUTH_URL, "", parameters, resultBuffer);

        // ?String
        /*
         * : oauth_token=88cd54bbf33a4ec79fe297cdd3ac5315 &
         * oauth_token_secret=a825b4ba2689a77b5cf5b3ee85b371141d3f77c2 &
         * user_id=111116 & user_type=2 & expires_in=604800
         */

        String result = resultBuffer.toString();
        Log.d("test", "17.result:" + result);

        if (status) {
            // HashTable pairs = new HashTable();
            Map<String, String> pairs = new HashMap<String, String>();
            // resultarr
            String[] arr = result.split("&");
            // ?,oauth_token=test_token_key?Map
            for (int i = 0; i < arr.length; i++) {
                // parts
                String[] parts = arr[i].split("=");

                if (parts.length == 2) {
                    pairs.put(parts[0], parts[1]);
                }
            }

            // MaptokenKeytokenSecret
            String tokenKey1 = pairs.get(Constants.TokenParameter);
            String tokenSecret1 = pairs.get(Constants.TokenSecretParameter);

            if ((tokenKey1 != null) && (tokenSecret1 != null)) {
                // tokenkeytokensecret?
                token = tokenKey1;
                tokenSecret = tokenSecret1;
                Log.d("test", "18.tokenKey:" + token);
                Log.d("test", "19.tokenSecret:" + tokenSecret);
            }
        }
    }

    // ??JSON?
    public static String doMethod(String url) {
        // ?TreeMapparameters?????url?
        TreeMap<String, String> parameters = new TreeMap<String, String>();

        // 1.consumerkeyapp???keykey??app?key
        parameters.put(Constants.ConsumerKeyParameter, consumerKey);
        Log.d("test1", "1.consumerKey:" + consumerKey);

        // 2.UUID???????
        /*
         * ?GUID
         * 
         * 
         * ??GUID???????10GUID?
         * ??? FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF
         */

        UUID uuid = UUID.randomUUID();

        // ????ws?
        String guid = uuid.toString();

        // nonce
        parameters.put(Constants.NonceParameter, guid);
        Log.d("test1", "2.guid:" + guid);

        // 3.?Hmacsha1
        parameters.put(Constants.SignatureMethodParameter, HMACSHA1SignatureType);
        Log.d("test1", "3.SignatureMethodParameter:" + HMACSHA1SignatureType);

        // 4.
        /*
         * 
         * 
         * 
         * Unix???UTC??197011000??? ?2014/1/29
         * 16:56:58UTC+8UTC2014/1/29
         * 8:56:58?Unix160998565813909858181390985818
         * ??60?
         */
        parameters.put(Constants.TimestampParameter, Long.toString(System.currentTimeMillis() / 1000));
        Log.d("test1", "4.TimestampParameter:" + Long.toString(System.currentTimeMillis() / 1000));

        // 5.TokenKey
        parameters.put(Constants.TokenParameter, token);
        Log.d("test", "5.TokenKey:" + token);

        // 6.XAuth??1.0?
        parameters.put(Constants.VersionParameter, OAuthVersion);
        Log.d("test1", "6.VersionParameter:" + OAuthVersion);

        // ????
        // ??StringBuffer?String??result
        StringBuffer resultBuffer = new StringBuffer("");

        // http?statusresult

        Boolean status = TryRequestRemote(url, tokenSecret, parameters, resultBuffer);
        Log.d("test1", "7.http?statusresult:" + resultBuffer.toString());
        return resultBuffer.toString();
    }

    // ???url??result
    private static Boolean TryRequestRemote(String url, String tokenSecret,
            final TreeMap<String, String> parameters, StringBuffer result) {

        try {

            // 9.Http
            String requestMethod = "GET";
            Log.d("test", "9.Http:" + requestMethod);

            // 10.URL?URL
            URL requestUri = new URL(url);
            Log.d("test", "10.requestUri" + requestUri);

            // 11.???
            String signatureBase = SignatureBaseBuilder.CreateSignatureBaseString(requestMethod, requestUri,
                    parameters);
            Log.d("test", "11.signatureBase" + signatureBase);

            // 12.???
            String signature = HMACSHA1Signer.CreateSignature(consumerSecret, tokenSecret, signatureBase);
            Log.d("test", "12.signature" + signature);

            // 13.?HTTP

            String header = XAuthRequestHeaderBuilder.CreateSignatureBaseString(requestMethod, requestUri,
                    consumerSecret, tokenSecret, parameters);

            Log.d("test", "13.header" + header);

            // 14.HTTPString?
            String urlPreview = String.format(
                    "[Request Url]\r\n%s\r\n\r\n[Signature Base]\r\n%s\r\n\r\n[Signature]\r\n%s\r\n\r\n[Header]\r\n%s",
                    requestUri.toString(), signatureBase, signature, header);
            Log.d("test", "14.urlPreview" + urlPreview);

            // 16.???
            String temp = HttpFetcher.GetRemoteContent(url, Encoding.UTF_8, _fetchTimeout, header);
            result.append(temp);
            Log.d("test", "16.result" + result);

            return true;

        } catch (Exception ex) {
            // this.txtResult.Text = String.Format("Error:\r\n{0}", ex.Message);
            return false;
        }
    }
}