com.thecorpora.qbo.androidapk.rest.RESTClient.java Source code

Java tutorial

Introduction

Here is the source code for com.thecorpora.qbo.androidapk.rest.RESTClient.java

Source

/*
* Software License Agreement (GPLv2 License)
* 
* Copyright (c) 2011 Thecorpora, S.L.
*
* 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 2 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, write to the Free Software 
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 
* MA 02110-1301, USA.
*
* Author: Daniel Cuadrado Snchez <daniel.cuadrado@openqbo.com>
*/
package com.thecorpora.qbo.androidapk.rest;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpCookie;
import java.util.ArrayList;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import com.googlecode.androidannotations.annotations.AfterInject;
import com.googlecode.androidannotations.annotations.EBean;
import com.googlecode.androidannotations.annotations.rest.RestService;
import com.thecorpora.qbo.androidapk.utils.AESCipher;

import android.util.Log;

/**
 * 
 * This class is used for the comunication with the Server inside Qbo using HTTP protocol
 * 
 * @author Daniel Cuadrado Sanchez
 *
 */
@EBean
public class RESTClient {

    private final String TAG = getClass().getSimpleName();

    private static final int DEFAULT_PORT = 7070;

    public static final int IMAGE_LEFT_EYE = 0;
    public static final int IMAGE_RIGHT_EYE = 1;
    public static final int IMAGE_MONOCULAR = 2;
    public static final int IMAGE_OBJECT_TRACKING = 3;
    public static final int IMAGE_FACE_DETECTOR = 4;
    public static final int IMAGE_DISPARITY_IMAGE = 5;
    public static final int IMAGE_NEAREST_OBJECT_TRACKING = 6;
    public static final int IMAGE_THREEDIMENSIONNAL = 7;

    private int quality = 50;
    private int widthImg = 640;
    private int heightImg = 480;

    @RestService
    WebiRestInterface mRest;

    private HttpCookie mCookie;
    private String mHost;

    public class MyAuthInterceptor implements ClientHttpRequestInterceptor {

        public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
                throws IOException {
            HttpHeaders headers = request.getHeaders();
            if (mCookie != null)
                headers.add("Cookie", mCookie.toString());
            return execution.execute(request, body);
        }
    }

    @AfterInject
    protected void init() {
        ArrayList<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
        interceptors.add(new MyAuthInterceptor());
        mRest.getRestTemplate().setInterceptors(interceptors);
        setImgQuality(quality);
    }

    /**
     * 
     * Tell the robot the linear and angular speed for its movement
     * 
     * @param x linear speed
     * @param y angular speed
     */
    public void post_moveBody(double x, double y) {
        mRest.moveBody(x, y);
    }

    /**
     * Tell the robot the pan and tilt position for its head movement. So far the pan and tilt speed is defined to 300
     * 
     * @param x pan position (-1, 1)
     * @param y tilt position (-1, 1)
     */
    public void post_moveHead(double x, double y) {
        //FIXME: current Webi use 640x480 factors..
        mRest.moveHead(640 * x, 480 * y);
    }

    /**
     * Tell the robot what it is going to say
     * 
     * @param sentence text to speak by the robot
     */
    public void post_say(String sentence) {
        mRest.say(sentence);
    }

    /**
     * Tell the robot which mouth to put
     * 
     * @param mouth number of the mouth
     */
    public void post_mouth(int mouth) {
        mRest.mouth(mouth);
    }

    /**
     * Tell the robot to activate the stereoscopy
     * 
     * @param activate a String with "on" to activate or "off" to deactivate
     */
    public void post_activate_3D(String activate) {
        mRest.activate3D(activate);
    }

    /**
     * 
     * We send the user name and password parameters to the robot.
     * 
     * We will get true if the access is allowed, false otherwise
     * 
     * @param userName user name
     * @param pwd password
     * @param aes_string string to encrypt userName and pwd
     * @return true if the access is allowed, false if not.
     */
    public HttpCookie post_login(String userName, String pwd, String aes_string) {
        AESCipher aes = new AESCipher();

        byte[] bytesUserName = {};
        byte[] bytesPwd = {};
        try {
            bytesUserName = userName.getBytes("UTF-8");
            userName = aes.encrypt(bytesUserName, aes_string);

            bytesPwd = pwd.getBytes("UTF-8");
            pwd = aes.encrypt(bytesPwd, aes_string);

        } catch (UnsupportedEncodingException uee) {
            uee.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        ResponseEntity<String> response = mRest.login(userName, pwd);

        String cookie = response.getHeaders().getFirst("Set-Cookie");

        if (cookie == null)
            throw new HttpClientErrorException(response.getStatusCode(), "session cookie not found");

        mCookie = HttpCookie.parse(cookie).get(0);
        return mCookie;
    }

    /**
     * We give the IP to the robot
     * 
     * @param ip4Linphone The IP given by the user in the Login activity is sent to the robot in order to properly configurate Linphone
     */
    public int post_ip4sip(String ip4Linphone) {
        try {
            mRest.ip4sip(ip4Linphone);
            return 0;
        } catch (RestClientException e) {
            Log.e(TAG, e.getMessage(), e);
            return -1;
        }
    }

    /**
     * We get out user name created by the SIP server. 
     */
    public String getSipId() {
        return mRest.getSipId();
    }

    /**
     * We get the Linphone bot user name, so we know who we have to call
     */
    public String getBotSipId() {
        return mRest.getBotSipId();
    }

    /**
     * End call.
     */
    public String endCall() {
        return mRest.endCall();
    }

    /**
     * Start SIP Server
     */
    public int startSIPServer() {
        try {
            mRest.startSIPServer();
            return 0;
        } catch (RestClientException e) {
            Log.e(TAG, e.getMessage(), e);
            return -1;
        }
    }

    /**
     * Stop SIP Sever
     */
    public int stopSIPServer() {
        try {
            mRest.stopSIPServer();
            return 0;
        } catch (RestClientException e) {
            Log.e(TAG, e.getMessage(), e);
            return -1;
        }
    }

    public String getURL_IMG(int imageType) {

        switch (imageType) {
        case IMAGE_LEFT_EYE://left_eye
            return "http://" + mHost + "/image/stream?topic=/stereo/left/image_raw&quality=" + quality + "&width="
                    + widthImg + "&height=" + heightImg;

        case IMAGE_RIGHT_EYE://right eye      
            return "http://" + mHost + "/image/stream?topic=/stereo/right/image_raw&quality=" + quality + "&width="
                    + widthImg + "&height=" + heightImg;

        case IMAGE_MONOCULAR://monocular         
            return "http://" + mHost + "/image/stream?topic=/stereo/monocolular/image_raw&quality=" + quality
                    + "&width=" + widthImg + "&height=" + heightImg;

        case IMAGE_OBJECT_TRACKING://object_tracking         
            return "http://" + mHost + "/image/stream?topic=/stereo/stereo_selector/image_raw&quality=" + quality
                    + "&width=" + widthImg + "&height=" + heightImg;

        case IMAGE_FACE_DETECTOR://face_detector
            return "http://" + mHost + "/image/stream?topic=/qbo_face_tracking/viewer&quality=" + quality
                    + "&width=" + widthImg + "&height=" + heightImg;

        case IMAGE_DISPARITY_IMAGE://disparity_image         
            return "http://" + mHost + "/image/stream?topic=/stereo/stereo_follower/disparity&quality=" + quality
                    + "&width=" + widthImg + "&height=" + heightImg;

        case IMAGE_NEAREST_OBJECT_TRACKING://nearest_object_tracking         
            return "http://" + mHost + "/image/stream?topic=/Qbo/ObjectTraking/Viewer&quality=" + quality
                    + "&width=" + widthImg + "&height=" + heightImg;

        case IMAGE_THREEDIMENSIONNAL://three_d         
            return "http://" + mHost + "/image/stream?topic=/stereo_anaglyph&quality=" + quality + "&width="
                    + widthImg + "&height=" + heightImg;

        }
        return "";
    }

    public void stopVideo(String url) {
        url = url.replace("stream", "stop");
        RestTemplate restTemplate = mRest.getRestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        HttpEntity<Object> requestEntity = new HttpEntity<Object>(httpHeaders);
        restTemplate.exchange(url, HttpMethod.POST, requestEntity, null);
    }

    public void setHost(String host) {
        mHost = host + ":" + DEFAULT_PORT;
        mRest.setRootUrl("http://" + mHost);
    }

    public void setIp(String ip) {
        setHost(ip);
    }

    public void setImgQuality(int quality) {
        this.quality = quality;
    }

    public boolean hasCookie() {
        return mCookie != null;
    }

    public void setCookie(HttpCookie cookie) {
        if (cookie != null) {
            mCookie = cookie;
        } else {
            removeCookie();
        }
    }

    public void setCookie(String cookie) {
        if (cookie != null) {
            mCookie = HttpCookie.parse(cookie).get(0);
        } else {
            removeCookie();
        }
    }

    public HttpCookie getCookie() {
        return mCookie;
    }

    public void removeCookie() {
        mCookie = null;
    }
}