com.clearcenter.mobile_demo.mdRest.java Source code

Java tutorial

Introduction

Here is the source code for com.clearcenter.mobile_demo.mdRest.java

Source

// ClearOS Mobile Demo: Example Android Application
// Copyright (C) 2012 ClearFoundation <http://www.clearfoundation.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package com.clearcenter.mobile_demo;

import android.os.Bundle;
import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;

import org.apache.http.auth.AuthenticationException;
import org.apache.http.ParseException;

import org.json.JSONException;
import org.json.JSONObject;

public class mdRest {
    // The tag used to log to adb console.
    private static final String TAG = "mdRest";

    // Login URL
    private static final String URL_LOGIN = "/app/mobile_demo/rest";

    // System Info URL
    private static final String URL_SYSINFO = "/app/mobile_demo/rest/system_info";

    // Mobile Demo REST result codes
    // Taken from: mobile_demo/libraries/Mobile_Demo.php
    public static final int RESULT_EXCEPTION = -1;
    public static final int RESULT_SUCCESS = 0;
    public static final int RESULT_UNKNOWN = 1;
    public static final int RESULT_ACCESS_DENIED = 2;

    static private HttpsURLConnection CreateConnection(URL url) throws IOException {
        System.setProperty("http.keepAlive", "false");

        HttpsURLConnection http = (HttpsURLConnection) url.openConnection();

        http.setConnectTimeout(30 * 1000);
        http.setReadTimeout(30 * 1000);
        http.setUseCaches(false);
        http.setDoInput(true);
        http.setDoOutput(true);
        http.setUseCaches(false);

        return http;
    }

    static private StringBuffer ProcessRequest(HttpsURLConnection http) throws IOException {
        http.connect();

        Log.d(TAG, "Result code: " + http.getResponseCode() + ", content type: " + http.getContentType()
                + ", content length: " + http.getContentLength());

        // Read response, 8K buffer
        BufferedReader buffer = new BufferedReader(new InputStreamReader(http.getInputStream()), 8192);

        String data;
        StringBuffer response = new StringBuffer();
        while ((data = buffer.readLine()) != null)
            response.append(data);

        Log.d(TAG, "Response buffer length: " + response.length());

        buffer.close();
        http.disconnect();

        return response;
    }

    static public String Login(String host, String username, String password, String token) throws JSONException {
        if (password == null)
            Log.i(TAG, "Login by cookie, host: " + host + ", username: " + username);
        else
            Log.i(TAG, "Login by password, host: " + host + ", username: " + username);

        try {
            URL url = new URL("https://" + host + URL_LOGIN);

            HttpsURLConnection http = CreateConnection(url);

            if (password != null) {
                // Setup HTTPS POST request
                String urlParams = "username=" + URLEncoder.encode(username, "UTF-8") + "&password="
                        + URLEncoder.encode(password, "UTF-8") + "&submit=submit";

                http.setRequestMethod("POST");
                http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                http.setRequestProperty("Content-Length", Integer.toString(urlParams.getBytes().length));

                // Write request
                DataOutputStream outputStream = new DataOutputStream(http.getOutputStream());
                outputStream.writeBytes(urlParams);
                outputStream.flush();
                outputStream.close();
            } else {
                http.setRequestMethod("GET");
                http.setRequestProperty("Cookie", token);
            }

            final StringBuffer response = ProcessRequest(http);

            // Process response
            JSONObject json_data = null;
            try {
                Log.i(TAG, "response: " + response.toString());
                json_data = new JSONObject(response.toString());
            } catch (JSONException e) {
                Log.e(TAG, "JSONException", e);
                return "";
            }
            if (json_data.has("result")) {
                final String cookie = http.getHeaderField("Set-Cookie");
                Integer result = RESULT_UNKNOWN;
                try {
                    result = Integer.valueOf(json_data.getString("result"));
                } catch (NumberFormatException e) {
                }

                Log.i(TAG, "result: " + result.toString() + ", cookie: " + cookie);

                if (result == RESULT_SUCCESS) {
                    if (cookie != null)
                        return cookie;
                    else
                        return token;
                }

                // All other results are failures...
                return "";
            }
        } catch (Exception e) {
            Log.e(TAG, "Exception", e);
        }

        Log.i(TAG, "Malformed result");
        return "";
    }

    static public String GetSystemInfo(String host, String token, long last_sample)
            throws JSONException, ParseException, IOException, AuthenticationException {
        try {
            URL url = new URL("https://" + host + URL_SYSINFO + "/" + last_sample);
            Log.v(TAG, "GetSystemInfo: host: " + host + ", token: " + token + ", URL: " + url);

            HttpsURLConnection http = CreateConnection(url);

            http.setRequestMethod("GET");
            http.setRequestProperty("Cookie", token);

            final StringBuffer response = ProcessRequest(http);

            // Process response
            JSONObject json_data = null;
            try {
                //Log.i(TAG, "response: " + response.toString());
                json_data = new JSONObject(response.toString());
            } catch (JSONException e) {
                Log.e(TAG, "JSONException", e);
                return "";
            }
            if (json_data.has("result")) {
                Integer result = RESULT_UNKNOWN;
                try {
                    result = Integer.valueOf(json_data.getString("result"));
                } catch (NumberFormatException e) {
                }

                Log.d(TAG, "result: " + result.toString());

                if (result == RESULT_SUCCESS && json_data.has("data")) {
                    //Log.i(TAG, "data: " + json_data.getString("data"));
                    return json_data.getString("data");
                }

                if (result == RESULT_ACCESS_DENIED)
                    throw new AuthenticationException();

                // New cookies?
                final String cookie = http.getHeaderField("Set-Cookie");
                if (cookie != null) {
                    Log.d(TAG, "New cookie!");
                }

                // All other results are failures...
                throw new IOException();
            }
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException", e);
            throw new ParseException();
        }

        Log.i(TAG, "Malformed result");
        throw new IOException();
    }
}

// vi: expandtab shiftwidth=4 softtabstop=4 tabstop=4