public void doReadLoop() {
      HttpContext context = new BasicHttpContext();
      context.setAttribute(CX_SOCKET, rawSocket);

      while (!Thread.interrupted() && this.htConn.isOpen() && HttpServer.this.shouldRun) {
        // Clear the context from any auth settings; since this is done
        // anew on each connection..
        context.removeAttribute(CX_AUTH);

        try {
          HttpServer.this.httpService.handleRequest(htConn, context);
        } catch (ConnectionClosedException ex_closed) {
          break;
        } catch (IOException ex) {
          if (!closeRequested) {
            ex.printStackTrace();
          }
          break;
        } catch (HttpException ex) {
          ex.printStackTrace();
          break;
        } catch (ResponseHandledException ex) {
          break;
        }
      }
      bail();
    }
 public static byte[] httpEntityToByteArray(final HttpEntity entity) throws IOException {
   if (entity == null) {
     throw new IllegalArgumentException("HTTP entity may not be null");
   }
   InputStream instream = entity.getContent();
   if (instream == null) {
     return new byte[] {};
   }
   if (entity.getContentLength() > Integer.MAX_VALUE) {
     throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
   }
   int i = (int) entity.getContentLength();
   if (i < 0) {
     i = 4096;
   }
   ByteArrayBuffer buffer = new ByteArrayBuffer(i);
   try {
     byte[] tmp = new byte[4096];
     int l;
     while ((l = instream.read(tmp)) != -1) {
       if (Thread.interrupted())
         throw new InterruptedIOException("File download process was canceled");
       buffer.append(tmp, 0, l);
     }
   } finally {
     instream.close();
   }
   return buffer.toByteArray();
 }
Beispiel #3
0
 public void run() {
   HttpPost httpPost =
       new HttpPost(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp));
   //
   httpPost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
   //
   HttpResponse response = null; // This is acting as keep alive.
   //
   while (isActive()) {
     try {
       Thread.sleep(KEEP_ALIVE_PERIOD);
       httpPost.setEntity(new UrlEncodedFormEntity(postParameters, HTTP.UTF_8));
       response = null;
       response = httpclient.execute(httpPost);
       int status = response.getStatusLine().getStatusCode();
       if (status != RestStreamHanlder.SUCCESS_200) {
         logger.error(
             "Cant register to the remote client, retrying in:"
                 + (KEEP_ALIVE_PERIOD / 1000)
                 + " seconds.");
         structure = registerAndGetStructure();
       }
     } catch (Exception e) {
       logger.warn(e.getMessage(), e);
     } finally {
       if (response != null) {
         try {
           response.getEntity().getContent().close();
         } catch (Exception e) {
           logger.warn(e.getMessage(), e);
         }
       }
     }
   }
 }
Beispiel #4
0
 public static void usleep(int msec) {
   try {
     Thread.sleep(msec);
   } catch (InterruptedException e) {
   }
 }
Beispiel #5
0
 @Override
 public Thread newThread(Runnable r) {
   Thread thread = new Thread(r, "HttpUtils #" + mCount.getAndIncrement());
   thread.setPriority(Thread.NORM_PRIORITY - 1);
   return thread;
 }
Beispiel #6
0
  public void connect() {
    if (mThread != null && mThread.isAlive()) {
      return;
    }

    mThread =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                try {
                  int port =
                      (mURI.getPort() != -1)
                          ? mURI.getPort()
                          : ((mURI.getScheme().equals("wss") || mURI.getScheme().equals("https"))
                              ? 443
                              : 80);

                  String path = TextUtils.isEmpty(mURI.getPath()) ? "/" : mURI.getPath();
                  if (!TextUtils.isEmpty(mURI.getQuery())) {
                    path += "?" + mURI.getQuery();
                  }

                  String originScheme = mURI.getScheme().equals("wss") ? "https" : "http";
                  URI origin = new URI(originScheme, "//" + mURI.getHost(), null);

                  SocketFactory factory =
                      (mURI.getScheme().equals("wss") || mURI.getScheme().equals("https"))
                          ? getSSLSocketFactory()
                          : SocketFactory.getDefault();
                  mSocket = factory.createSocket(mURI.getHost(), port);

                  PrintWriter out = new PrintWriter(mSocket.getOutputStream());
                  out.print("GET " + path + " HTTP/1.1\r\n");
                  out.print("Upgrade: websocket\r\n");
                  out.print("Connection: Upgrade\r\n");
                  out.print("Host: " + mURI.getHost() + "\r\n");
                  out.print("Origin: " + origin.toString() + "\r\n");
                  out.print("Sec-WebSocket-Key: " + createSecret() + "\r\n");
                  out.print("Sec-WebSocket-Version: 13\r\n");
                  if (mExtraHeaders != null) {
                    for (NameValuePair pair : mExtraHeaders) {
                      out.print(String.format("%s: %s\r\n", pair.getName(), pair.getValue()));
                    }
                  }
                  out.print("\r\n");
                  out.flush();

                  HybiParser.HappyDataInputStream stream =
                      new HybiParser.HappyDataInputStream(mSocket.getInputStream());

                  // Read HTTP response status line.
                  StatusLine statusLine = parseStatusLine(readLine(stream));
                  if (statusLine == null) {
                    throw new HttpException("Received no reply from server.");
                  } else if (statusLine.getStatusCode() != HttpStatus.SC_SWITCHING_PROTOCOLS) {
                    throw new HttpResponseException(
                        statusLine.getStatusCode(), statusLine.getReasonPhrase());
                  }

                  // Read HTTP response headers.
                  String line;
                  while (!TextUtils.isEmpty(line = readLine(stream))) {
                    Header header = parseHeader(line);
                    if (header.getName().equals("Sec-WebSocket-Accept")) {
                      // FIXME: Verify the response...
                    }
                  }
                  mConnected = true;
                  mListener.onConnect();
                  // Now decode websocket frames.
                  mParser.start(stream);

                } catch (EOFException ex) {
                  mListener.onDisconnect(0, "EOF");
                  mConnected = false;

                } catch (SSLException ex) {
                  // Connection reset by peer
                  mConnected = false;
                  mListener.onDisconnect(0, "SSL");

                } catch (Exception ex) {
                  mListener.onError(ex);
                }
              }
            });
    mThread.start();
  }