ca.ualberta.cmput301f12t05.ufill.Webservicer.java Source code

Java tutorial

Introduction

Here is the source code for ca.ualberta.cmput301f12t05.ufill.Webservicer.java

Source

/*
 * Copyright (C) 2012 Youssef Altherwy, Jeremy Unger, 
 * Tanner Rutgers, and Mobolaji Okubanjo
 *
 * 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 ca.ualberta.cmput301f12t05.ufill;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.os.StrictMode;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * CrowdSource Service Client (Teaser)
 * 
 * @author Victor Guana - guana[at]ualberta.ca University of Alberta, Department
 *         of Computing Science
 *         Editied by Jeremy Unger - jmunger@ualberta.ca
 */
public class Webservicer {

    // Http Connector
    private HttpClient httpclient = new DefaultHttpClient();

    // JSON Utilities
    private Gson gson = new Gson();

    // POST Request
    HttpPost httpPost = new HttpPost("http://crowdsourcer.softwareprocess.es/F12/CMPUT301F12T05/");

    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String. (c) public domain:
     * http://senior.ceng.metu.edu.tr/
     * 2009/praeda/2009/01/11/a-simple-restful-client-at-android/
     */
    private String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    /**
     * Consumes the LIST operation of the service
     * 
     * @return JSON representation of the Bin list
     * @throws Exception
     */
    public String listBins() throws Exception {

        String jsonStringVersion = new String();
        List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
        nvps.add(new BasicNameValuePair("action", "list"));
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        HttpResponse response = httpclient.execute(httpPost);

        String status = response.getStatusLine().toString();
        HttpEntity entity = response.getEntity();

        System.out.println(status);

        if (entity != null) {
            InputStream is = entity.getContent();
            jsonStringVersion = convertStreamToString(is);
        }

        // and ensure it is fully consumed
        entity.consumeContent();
        return jsonStringVersion;
    }

    /**
     * Consumes the GET operation of the service
     * 
     * @return Bin object given the id idP
     * @throws Exception
     */
    public CrowdSourcerBin getBin(String SourcerId) throws Exception {

        CrowdSourcerBin responseBin = null;
        List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
        nvps.add(new BasicNameValuePair("action", "get"));
        nvps.add(new BasicNameValuePair("id", SourcerId));

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        HttpResponse response = httpclient.execute(httpPost);

        String status = response.getStatusLine().toString();
        HttpEntity entity = response.getEntity();

        System.out.println(status);

        if (entity != null) {
            InputStream is = entity.getContent();
            String jsonStringVersion = convertStreamToString(is);
            Type BinType = CrowdSourcerBin.class;
            responseBin = gson.fromJson(jsonStringVersion, BinType);
        }
        entity.consumeContent();
        return responseBin;

    }

    /**
     * Consumes the POST/Insert operation of the service
     * 
     * @return Sourcer Id of placed bin
     * @throws Exception
     */
    public String insertBin(CrowdSourcerBin SBin) throws Exception {

        List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
        nvps.add(new BasicNameValuePair("action", "post"));
        nvps.add(new BasicNameValuePair("summary", (SBin.getcontent()).getTitle()));
        nvps.add(new BasicNameValuePair("content", gson.toJson(SBin.getcontent())));

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        //System.out.println(httpPost);

        HttpResponse response = httpclient.execute(httpPost);

        String status = response.getStatusLine().toString();
        HttpEntity entity = response.getEntity();

        System.out.println(status);

        CrowdSourcerBin newBin = null;
        if (entity != null) {
            InputStream is = entity.getContent();
            String jsonStringVersion = convertStreamToString(is);
            Type BinType = CrowdSourcerBin.class;
            newBin = gson.fromJson(jsonStringVersion, BinType);
            System.out.println(newBin);
        }
        entity.consumeContent();
        return newBin.getId();
    }

    /**
     * Consumes the UPDATE operation of the service
     * Increments the popularity of a bin when someone favorites it
     * 
     * @return void
     * @throws Exception
     */
    public void incrementFavorite(String SourcerId) throws Exception {
        List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
        nvps.add(new BasicNameValuePair("action", "update"));
        CrowdSourcerBin SBin = getBin(SourcerId);
        SBin.getcontent().incrementPopularity();
        nvps.add(new BasicNameValuePair("summary", (SBin.getcontent()).getTitle()));
        nvps.add(new BasicNameValuePair("content", gson.toJson(SBin.getcontent())));
        nvps.add(new BasicNameValuePair("id", SBin.getId()));

        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        System.out.println(convertStreamToString(httpPost.getEntity().getContent()));
        HttpResponse response = httpclient.execute(httpPost);

        String status = response.getStatusLine().toString();
        HttpEntity entity = response.getEntity();

        System.out.println(status);

        entity.consumeContent();
    }

    /**
     * Consumes the REMOVE operation of the service
     * Once a local bin has been deleted, it is removed from the webservice as well.
     * 
     * @return void
     * @throws Exception
     */
    public void removeBin(String SourcerId) throws Exception {
        List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
        nvps.add(new BasicNameValuePair("action", "remove"));
        nvps.add(new BasicNameValuePair("id", SourcerId));

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        HttpResponse response = httpclient.execute(httpPost);

        String status = response.getStatusLine().toString();
        HttpEntity entity = response.getEntity();

        System.out.println(status);

        entity.consumeContent();
    }

    /**
     * Pulls the array list of CrowdSourcerBins off of the network
     * to be displayed during search.
     * 
     * @return void
     * @throws Exception
     */
    public ArrayList<CrowdSourcerBin> getSourcerBins() throws Exception {
        List<Map<String, String>> listedEntryList = getBinList();
        ArrayList<CrowdSourcerBin> entryList = new ArrayList<CrowdSourcerBin>();
        for (Map<String, String> listedEntry : listedEntryList) {
            CrowdSourcerBin entry = getBin(listedEntry.get("id"));
            entryList.add(entry);
            System.out.print(entry);
        }
        return entryList;
    }

    /**
     * Consumes the REMOVE operation of the service
     * Once a local bin has been deleted, it is removed from the webservice as well.
     * 
     * @return void
     * @throws Exception
     */
    public List<Map<String, String>> getBinList() throws Exception {
        String jsonEntryList = listBins();
        Type listType = new TypeToken<List<Map<String, String>>>() {
        }.getType();
        List<Map<String, String>> BinList = gson.fromJson(jsonEntryList, listType);
        //System.out.println("The bin list " + BinList);
        return BinList;
    }

}