Android Open Source - ubihelper Http Client Handler






From Project

Back to project page ubihelper.

License

The source code is released under:

GNU General Public License

If you think the Android project ubihelper listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/**
 * Copyright (c) 2012 The University of Nottingham
 * //  w w w  .ja v a  2 s  .c o m
 * This file is part of ubihelper
 *
 *  ubihelper is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  ubihelper 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 Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with ubihelper. If not, see <http://www.gnu.org/licenses/>.
 *  
 *  @author Chris Greenhalgh (cmg@cs.nott.ac.uk), The University of Nottingham
 */

package uk.ac.horizon.ubihelper.httpserver;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.HashMap;

import uk.ac.horizon.ubihelper.service.Service;

import android.util.Log;

/**
 * @author cmg
 *
 */
public class HttpClientHandler extends Thread {
  private static final String TAG = "ubihelper-httpclient";
  private Service service;
  private Socket s;
  private int mStatus = 0;
  private String mMessage = null;
  private String mResponseBody = null;

  public HttpClientHandler(Service service, Socket s) {
    this.service = service;
    this.s = s;
  }
  
  public void run() {
    try {
      // parse request
      BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
      //InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");
      // request line
      String request = readLine(bis);
      Log.d(TAG,"Request: "+request);
      String requestEls[] = request.split(" ");
      if (requestEls.length!=3) 
        throw HttpError.badRequest("Mal-formatted request line ("+requestEls.length+" elements)");
      if (!"GET".equals(requestEls[0]) && !"POST".equals(requestEls[0]))
        throw HttpError.badRequest("Unsupported operation ("+requestEls[0]+")");
      String path = requestEls[1];
      // header lines
      HashMap<String,String> headers = new HashMap<String,String>();
      while (true) {
        String header = readLine(bis);
        if (header.length()==0)
          break;
        Log.d(TAG,"Header line: "+header);
        int ix = header.indexOf(":");
        if (ix<0) 
          throw HttpError.badRequest("Mal-formed header line ("+header+")");
        String name = header.substring(0,ix).trim().toLowerCase();
        String value = header.substring(ix+1).trim();
        headers.put(name, value);
      }
      // content body
      int length = -1;
      String contentLength = headers.get("content-length");
      if (contentLength!=null)
        try {
          length = Integer.parseInt(contentLength);
        }
        catch (NumberFormatException nfe) {
          throw HttpError.badRequest("Invalid content-length ("+contentLength+")");
        }
      Log.d(TAG,"Read request body "+length+" bytes");
      byte buf[] = new byte[length>=0 ? length : 1000];
      int count = 0;
      while (length<0 || count<length) {
        int n = bis.read(buf, count, buf.length-count);
        if (n<0) {
          if (length<0)
            break;
          else
            throw HttpError.badRequest("Request body too short ("+count+"/"+length+")");
        }
        count += n;
        if (length<0 && count>=buf.length) {
          // grow buffer
          byte nbuf[] = new byte[buf.length*2];
          System.arraycopy(buf, 0, nbuf, 0, count);
          buf = nbuf;
        }
      }
      String requestBody = new String(buf,0,count,"UTF-8");
      Log.d(TAG,"get "+path+" with "+requestBody);
      
      synchronized (this) {
        service.postRequest(path, requestBody, new HttpContinuation() {

          public void done(int status, String message, String body) {
            mStatus = status;
            mMessage = message;
            mResponseBody = body;
            synchronized (HttpClientHandler.this) {
              HttpClientHandler.this.notify();
            }
          }
          
        });
        // timeout 10s?!
        try {
          wait(10000);
        } 
        catch (InterruptedException ie) {
          throw HttpError.badRequest("Handle request interrupted");
        }
      }
      if (mStatus==0)
        throw HttpError.badRequest("Handle request timed out");

      BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
      OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
      osw.write("HTTP/1.0 "+mStatus+" "+mMessage+"\r\n");
      byte resp [] = mResponseBody==null ? new byte[0] : mResponseBody.getBytes("UTF-8");
      osw.write("Content-Length: "+resp.length+"\r\n");
      osw.write("Content-Type: application/json\r\n");
      osw.write("\r\n");
      osw.flush();
      bos.write(resp);
      bos.close();
    }
    catch (IOException ie) {
      Log.d(TAG,"Error: "+ie.getMessage());
    } catch (HttpError e) {
      Log.d(TAG,"Sending error: "+e.getMessage());
      sendError(e.getStatus(), e.getMessage());
    }
    try {
      s.close();
    }
    catch (IOException e) {
      /* ignore */
    }
  }

  private void sendError(int status, String message) {
    try {
      BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
      OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
      osw.write("HTTP/1.0 "+status+" "+message+"\r\n");
      osw.write("\r\n");
      osw.close();
    } catch (Exception e) {
      Log.d(TAG,"Error sending error: "+e.getMessage());
      /* ignore */
    }
  }

  private String readLine(InputStreamReader isr) throws IOException {
    StringBuilder sb = new StringBuilder();
    while (true) {
      int c = isr.read();
      if (c<0)
        break;
      if (c=='\r')
        // skip
        continue;
      if (c=='\n')
        break;
      sb.append((char)c);
    }
    return sb.toString();
  }

  private String readLine(BufferedInputStream bis) throws IOException {
    StringBuilder sb = new StringBuilder();
    while (true) {
      int c = bis.read();
      if (c<0)
        break;
      if (c=='\r')
        // skip
        continue;
      if (c=='\n')
        break;
      sb.append((char)c);
    }
    return sb.toString();
  }

}




Java Source Code List

org.json.JSONArray.java
org.json.JSONException.java
org.json.JSONObject.java
org.json.JSONString.java
org.json.JSONStringer.java
org.json.JSONTokener.java
org.json.JSONWriter.java
uk.ac.horizon.ubihelper.channel.ChannelFactory.java
uk.ac.horizon.ubihelper.channel.ChannelListener.java
uk.ac.horizon.ubihelper.channel.ChannelManager.java
uk.ac.horizon.ubihelper.channel.ChannelValueEvent.java
uk.ac.horizon.ubihelper.channel.NamedChannel.java
uk.ac.horizon.ubihelper.channel.PullSubscription.java
uk.ac.horizon.ubihelper.channel.SharedVariableChannel.java
uk.ac.horizon.ubihelper.channel.Subscription.java
uk.ac.horizon.ubihelper.dns.DnsClient.java
uk.ac.horizon.ubihelper.dns.DnsProtocol.java
uk.ac.horizon.ubihelper.dns.DnsServer.java
uk.ac.horizon.ubihelper.dns.DnsUtils.java
uk.ac.horizon.ubihelper.httpserver.HttpClientHandler.java
uk.ac.horizon.ubihelper.httpserver.HttpContinuation.java
uk.ac.horizon.ubihelper.httpserver.HttpError.java
uk.ac.horizon.ubihelper.httpserver.HttpListener.java
uk.ac.horizon.ubihelper.j2se.Base64.java
uk.ac.horizon.ubihelper.j2se.Server.java
uk.ac.horizon.ubihelper.net.Fragment.java
uk.ac.horizon.ubihelper.net.Marshaller.java
uk.ac.horizon.ubihelper.net.Message.java
uk.ac.horizon.ubihelper.net.OnPeerConnectionListener.java
uk.ac.horizon.ubihelper.net.PeerConnectionScheduler.java
uk.ac.horizon.ubihelper.net.PeerConnection.java
uk.ac.horizon.ubihelper.protocol.ClientInfo.java
uk.ac.horizon.ubihelper.protocol.ClientState.java
uk.ac.horizon.ubihelper.protocol.MessageUtils.java
uk.ac.horizon.ubihelper.protocol.PeerInfo.java
uk.ac.horizon.ubihelper.protocol.ProtocolManager.java
uk.ac.horizon.ubihelper.service.BroadcastIntentSubscription.java
uk.ac.horizon.ubihelper.service.EnabledPeersChannel.java
uk.ac.horizon.ubihelper.service.LogManager.java
uk.ac.horizon.ubihelper.service.LogSubscription.java
uk.ac.horizon.ubihelper.service.PeerManager.java
uk.ac.horizon.ubihelper.service.PeersOpenHelper.java
uk.ac.horizon.ubihelper.service.Service.java
uk.ac.horizon.ubihelper.service.WifiDiscoveryManager.java
uk.ac.horizon.ubihelper.service.channel.BluetoothDiscoveryChannel.java
uk.ac.horizon.ubihelper.service.channel.CellLocationChannel.java
uk.ac.horizon.ubihelper.service.channel.CellStrengthChannel.java
uk.ac.horizon.ubihelper.service.channel.GpsStatusChannel.java
uk.ac.horizon.ubihelper.service.channel.LocationChannel.java
uk.ac.horizon.ubihelper.service.channel.MicChannel.java
uk.ac.horizon.ubihelper.service.channel.PollingChannel.java
uk.ac.horizon.ubihelper.service.channel.SensorChannel.java
uk.ac.horizon.ubihelper.service.channel.TimeChannel.java
uk.ac.horizon.ubihelper.service.channel.WifiScannerChannel.java
uk.ac.horizon.ubihelper.ui.AboutActivity.java
uk.ac.horizon.ubihelper.ui.ChannelListActivity.java
uk.ac.horizon.ubihelper.ui.ChannelPeerListActivity.java
uk.ac.horizon.ubihelper.ui.ChannelValueActivity.java
uk.ac.horizon.ubihelper.ui.ChannelViewActivity.java
uk.ac.horizon.ubihelper.ui.LoggingChannelListActivity.java
uk.ac.horizon.ubihelper.ui.LoggingPreferences.java
uk.ac.horizon.ubihelper.ui.MainPreferences.java
uk.ac.horizon.ubihelper.ui.ManagePeersActivity.java
uk.ac.horizon.ubihelper.ui.PeerInfoActivity.java
uk.ac.horizon.ubihelper.ui.PeerManualAddActivity.java
uk.ac.horizon.ubihelper.ui.PeerRequestActivity.java
uk.ac.horizon.ubihelper.ui.PeerRequestInfoActivity.java
uk.ac.horizon.ubihelper.ui.SearchPeersActivity.java
uk.ac.horizon.ubihelper.ui.TestActivity.java
uk.ac.horizon.ubihelper.ui.WifiStatusActivity.java
uk.ac.horizon.ubihelper.websocket.ClientWebsocket.java
uk.ac.horizon.ubihelper.websocket.ReadyState.java
uk.ac.horizon.ubihelper.websocket.SocketChannelWebsocket.java
uk.ac.horizon.ubihelper.websocket.WebsocketListener.java
uk.ac.horizon.ubihelper.websocket.Websocket.java