com.PAB.ibeaconreference.AppEngineSpatial.java Source code

Java tutorial

Introduction

Here is the source code for com.PAB.ibeaconreference.AppEngineSpatial.java

Source

package com.PAB.ibeaconreference;

/*
 * Copyright 2011 Google 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.textuality.aerc;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.UUID;

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

//import com.example.httpjson.MainActivity.anotherthread;

import android.accounts.Account;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Performs GET and POST operations against a Google App Engine app, authenticating with
 *  a Google account on the device.
 */
public class AppEngineSpatial {
    static String a12;
    //private Authenticator mAuthenticator;
    private Context mContext;
    private static String mErrorMessage;

    /**
     * Constructs a client, which may be used for multiple requests.  This constructor may be 
     *  called on the UI thread.
     * 
     * @param appURI The URI of the App Engine app you want to interact with, e.g. your-app.appspot.com
     * @param account The android.accounts.Account representing the Google account to authenticate with.
     * @param context Used, if necessary, to prompt user for authentication
     */
    //    public AppEngineSpatial(URL appURI, Account account, Context context) {
    //        // HTTP connection reuse which was buggy pre-froyo
    //        if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
    //            System.setProperty("http.keepAlive", "false");
    //        }
    //        mAuthenticator = Authenticator.appEngineAuthenticator(context, account, appURI);
    //        mContext = context;
    //    }

    /**
     * Constructs a client, which may be used for multiple requests, and which will never prompt
     *  the user for authentication input.  This constructor may be called on the UI thread but is 
     *  suitable for use on background threads with no access to an Activity. 
     * 
     * @param appURI The URI of the App Engine app you want to interact with, e.g. your-app.appspot.com
     * @param authToken AccountManager authtoken, e.g. from the token() method 
     * @param context Used to look up strings
     */
    //    public AppEngineSpatial(URL appURI, String authToken, Context context) {
    //        mAuthenticator = Authenticator.appEngineAuthenticator(context, appURI, authToken);
    //        mContext = context;
    //    }

    /**
     * Performs an HTTP GET request.  The request is performed inline and this method must not
     *  be called from the UI thread.
     *  
     * @param uri The URI you're sending the GET to
     * @param headers Any extra HTTP headers you want to send; may be null
     * @return a Response structure containing the status, headers, and body. Returns null if the request 
     *   could not be launched due to an IO error or authentication failure; in which case use errorMessage()
     *   to retrieve diagnostic information.
     */
    public static Response get(URL uri, Map<String, List<String>> headers) {
        AppEngineSpatial aec = new AppEngineSpatial();
        GET get = aec.new GET(uri, headers);
        return getOrPost(get);
    }

    /**       
     * Performs an HTTP POST request.  The request is performed inline and this method must not
     *  be called from the UI thread.
     *  
     * @param uri The URI you're sending the POST to
     * @param headers Any extra HTTP headers you want to send; may be null
     * @param body The request body to transmit
     * @return a Response structure containing the status, headers, and body. Returns null if the request 
     *   could not be launched due to an IO error or authentication failure; in which case use errorMessage()
     *   to retrieve diagnostic information.
     */
    public Response post(URL uri, Map<String, List<String>> headers, byte[] body) {
        POST post = new POST(uri, headers, body);
        return getOrPost(post);
    }

    public Response put(URL uri, Map<String, List<String>> headers, byte[] body) {
        PUT put = new PUT(uri, headers, body);

        return getOrPost(put);

    }

    public void delete(URL uri, Map<String, List<String>> headers) {

        //   DELETE delete = new DELETE(uri, headers);
        HttpURLConnection httpURLConnection = null;
        try {
            httpURLConnection = (HttpURLConnection) uri.openConnection();
            httpURLConnection.setRequestMethod("DELETE");
            //httpURLConnection.connect();
            int s = httpURLConnection.getResponseCode();

        } catch (IOException exception) {
            exception.printStackTrace();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
    }

    /**
     * Provides an error message should a get() or post() return null.
     * @return the message
     */
    public String errorMessage() {
        return mErrorMessage;
    }

    public static Response getOrPost(Request request) {
        mErrorMessage = null;
        HttpURLConnection conn = null;
        Response response = null;
        try {
            conn = (HttpURLConnection) request.uri.openConnection();
            //            if (!mAuthenticator.authenticate(conn)) {
            //                mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage();
            //            } else 
            {
                if (request.headers != null) {
                    for (String header : request.headers.keySet()) {
                        for (String value : request.headers.get(header)) {
                            conn.addRequestProperty(header, value);
                        }
                    }
                }

                if (request instanceof PUT) {
                    byte[] payload = ((PUT) request).body;
                    String s = new String(payload, "UTF-8");
                    conn.setDoOutput(true);
                    conn.setDoInput(true);

                    conn.setRequestMethod("PUT");
                    JSONObject jsonobj = getJSONObject(s);
                    conn.setRequestProperty("Content-Type", "application/json; charset=utf8");
                    OutputStream os = conn.getOutputStream();
                    os.write(jsonobj.toString().getBytes("UTF-8"));
                    os.close();
                }

                if (request instanceof POST) {
                    byte[] payload = ((POST) request).body;
                    String s = new String(payload, "UTF-8");
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setRequestMethod("POST");

                    JSONObject jsonobj = getJSONObject(s);

                    conn.setRequestProperty("Content-Type", "application/json; charset=utf8");

                    OutputStream os = conn.getOutputStream();
                    os.write(jsonobj.toString().getBytes("UTF-8"));
                    os.close();

                    //                    conn.setFixedLengthStreamingMode(payload.length);
                    //                    conn.getOutputStream().write(payload);
                    int status = conn.getResponseCode();
                    if (status / 100 != 2)
                        response = new Response(status, new Hashtable<String, List<String>>(),
                                conn.getResponseMessage().getBytes());
                }

                if (response == null) {
                    int a = conn.getResponseCode();
                    if (a == 401) {
                        response = new Response(a, conn.getHeaderFields(), new byte[] {});
                    }
                    InputStream a1 = conn.getErrorStream();
                    BufferedInputStream in = new BufferedInputStream(conn.getInputStream());

                    byte[] body = readStream(in);

                    a12 = new String(body, "US-ASCII");

                    response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body);
                    //   List<String> a = conn.getHeaderFields().get("aa");
                }
            }
        } catch (IOException e) {
            e.printStackTrace(System.err);

        } finally {
            if (conn != null)
                conn.disconnect();

        }
        return response;
    }

    // request structs
    public class Request {
        public URL uri;
        public Map<String, List<String>> headers;

        public Request(URL uri, Map<String, List<String>> headers) {
            this.uri = uri;
            this.headers = headers;
        }
    }

    public class POST extends Request {
        public byte[] body;

        public POST(URL uri, Map<String, List<String>> headers, byte[] body) {
            super(uri, headers);
            this.body = body;
        }
    }

    public class GET extends Request {
        public GET(URL uri, Map<String, List<String>> headers) {
            super(uri, headers);
        }
    }

    public class PUT extends Request {
        public byte[] body;

        public PUT(URL uri, Map<String, List<String>> headers, byte[] body) {
            super(uri, headers);
            this.body = body;
        }
    }

    public class DELETE extends Request {
        public DELETE(URL uri, Map<String, List<String>> headers) {
            super(uri, headers);
        }
    }

    // utilities
    private static byte[] readStream(InputStream in) throws IOException {
        byte[] buf = new byte[1024];
        int count = 0;
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
        while ((count = in.read(buf)) != -1)
            out.write(buf, 0, count);
        return out.toByteArray();
    }

    private static String str(int id) {
        //return mContext.getString(id);
        return "str method placeholder string!";
    }

    public static UUID getUUID() {
        return UUID.randomUUID();
    }

    // generates JSON object from given string

    public static JSONObject getJSONObject(String s) {

        JSONObject jsonObj = null;

        try {
            jsonObj = new JSONObject(s);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonObj;
    }

    class asyncclass extends AsyncTask<Request, Void, Response> {

        private Exception exception;

        protected Response doInBackground(Request... requests) {
            try {

                Response response = AppEngineSpatial.getOrPost(requests[0]);

                return response;
            } catch (Exception e) {
                this.exception = e;
                return null;
            }
        }

        protected void onPostExecute(Response response) {
            // TODO: check this.exception
            // TODO: do something with the feed

        }
    }

}