/**
   * Constructor.
   *
   * @param listener The listener that created this connection.
   * @param remoteAddr The address of the remote end or null.
   * @param in InputStream to read request(s) from.
   * @param out OutputputStream to write response(s) to.
   * @param connection The underlying connection object, most likely a socket. This is not used by
   *     HttpConnection other than to make it available via getConnection().
   */
  public HttpConnection(
      HttpListener listener,
      InetAddress remoteAddr,
      InputStream in,
      OutputStream out,
      Object connection) {
    if (log.isDebugEnabled()) log.debug("new HttpConnection: " + connection);
    _listener = listener;
    _remoteInetAddress = remoteAddr;
    int bufferSize = listener == null ? 4096 : listener.getBufferSize();
    int reserveSize = listener == null ? 512 : listener.getBufferReserve();
    _inputStream = new HttpInputStream(in, bufferSize);
    _outputStream = new HttpOutputStream(out, bufferSize, reserveSize);
    _outputStream.addObserver(this);
    _firstWrite = false;
    if (_listener != null) _httpServer = _listener.getHttpServer();
    _connection = connection;

    _statsOn = _httpServer != null && _httpServer.getStatsOn();
    if (_statsOn) {
      _openTime = System.currentTimeMillis();
      _httpServer.statsOpenConnection();
    }
    _reqTime = 0;
    _requests = 0;

    _request = new HttpRequest(this);
    _response = new HttpResponse(this);

    _resolveRemoteHost =
        _listener != null
            && _listener.getHttpServer() != null
            && _listener.getHttpServer().getResolveRemoteHost();
  }
示例#2
0
  public DefaultSockJSServer(final VertxInternal vertx, final HttpServer httpServer) {
    this.vertx = vertx;
    this.sessions = vertx.sharedData().getMap("_vertx.sockjssessions");
    // Any previous request and websocket handlers will become default handlers
    // if nothing else matches
    rm.noMatch(httpServer.requestHandler());
    wsMatcher.noMatch(
        new Handler<WebSocketMatcher.Match>() {
          Handler<ServerWebSocket> wsHandler = httpServer.websocketHandler();

          public void handle(WebSocketMatcher.Match match) {
            if (wsHandler != null) {
              wsHandler.handle(match.ws);
            }
          }
        });
    httpServer.requestHandler(
        new Handler<HttpServerRequest>() {
          @Override
          public void handle(HttpServerRequest req) {
            if (log.isTraceEnabled()) {
              log.trace("Got request in sockjs server: " + req.uri);
            }
            rm.handle(req);
          }
        });
    httpServer.websocketHandler(wsMatcher);
  }
  /** Destroy the connection. called by handle when handleNext returns false. */
  protected void destroy() {
    try {
      close();
    } catch (IOException e) {
      LogSupport.ignore(log, e);
    } catch (Exception e) {
      log.warn(LogSupport.EXCEPTION, e);
    }

    // Destroy request and response
    if (_request != null) _request.destroy();
    if (_response != null) _response.destroy();
    if (_inputStream != null) _inputStream.destroy();
    if (_outputStream != null) _outputStream.destroy();
    _inputStream = null;
    _outputStream = null;
    _request = null;
    _response = null;
    _handlingThread = null;

    if (_statsOn) {
      _tmpTime = System.currentTimeMillis();
      if (_reqTime > 0) _httpServer.statsEndRequest(_tmpTime - _reqTime, false);
      _httpServer.statsCloseConnection(_tmpTime - _openTime, _requests);
    }
  }
  public HttpServerExample(QWidget parent) {
    server = new HttpServer(this);
    if (!server.start()) {
      QMessageBox.critical(
          this, tr("HTTP Server"), tr("Unable to start the server: ") + server.errorString());
      close();
    }

    QPushButton publishButton = new QPushButton(this);
    publishButton.setText("Publish");
    editor = new QTextEdit(this);

    editor.setPlainText(
        "<h1>Server is up and running!</h1>"
            + "You should be able to view it in a normal web browser."
            + " Try this address: http://localhost:"
            + server.serverPort());

    QGridLayout layout = new QGridLayout(this);
    setLayout(layout);
    layout.addWidget(publishButton);
    layout.addWidget(editor);

    publishButton.clicked.connect(this, "publish()");

    setWindowTitle(tr("Simple HTTP Server"));
    setWindowIcon(new QIcon("classpath:com/trolltech/images/qt-logo.png"));
  }
示例#5
0
 // For debug only
 public static void main(String[] args) throws Exception {
   Vertx vertx = Vertx.newVertx();
   HttpServer httpServer = vertx.createHttpServer();
   DefaultSockJSServer sjsServer = (DefaultSockJSServer) vertx.createSockJSServer(httpServer);
   sjsServer.installTestApplications();
   httpServer.listen(8081);
   Thread.sleep(Long.MAX_VALUE);
 }
示例#6
0
  protected HttpServer createHttpServer() throws IOException {
    HttpServer server = new HttpServer();

    SocketListener listener = new SocketListener();
    listener.setPort(SysConfig.getHttpPortAsInt());
    server.addListener(listener);

    return server;
  }
 public static void main(String args[]) {
   try {
     HttpServer server = new HttpServer(7896);
     server.start();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
示例#8
0
 @Test
 public void testStartAndStop() throws IOException, InterruptedException {
   final HttpServer server = new HttpServer().port(8085);
   server.start();
   assertEquals(404, client().newCall(request(8085).build()).execute().code());
   server.shutdown();
   Thread.sleep(5000L);
   try {
     assertEquals(404, client().newCall(request(8085).build()).execute().code());
     fail("Server should have stopped");
   } catch (final ConnectException ignore) {
   } catch (final InterruptedIOException ignored) {
   }
 }
 protected void setUp() throws Exception {
   super.setUp();
   HttpServerConfiguration config = new HttpServerConfiguration();
   config.setWebappsDir(null);
   config.setServerLogPath("build/test-server.log");
   config.setAccessLogPath("build/test-access.log");
   config.setPort(9000);
   HttpServerFactory factory = HttpServerFactory.getInstance();
   this.server = factory.create(config);
   ApplicationManager manager = server.getApplicationManager();
   Application application = manager.createApplication("test");
   application.addController(new TestAsyncController());
   manager.publish(application);
   server.start();
 }
 @Override
 protected void handlePost(HttpRequest request, String data) {
   String uri = request.getPath();
   if (uri.startsWith(JSCOVERAGE_STORE)) {
     File reportDir = configuration.getReportDir();
     if (uri.length() > JSCOVERAGE_STORE.length()) {
       reportDir = new File(reportDir, uri.substring(JSCOVERAGE_STORE.length()));
     }
     try {
       List<ScriptLinesAndSource> unloadJSData = null;
       if (configuration.isIncludeUnloadedJS())
         unloadJSData = unloadedSourceProcessor.getEmptyCoverageData(uris);
       jsonDataSaver.saveJSONData(reportDir, data, unloadJSData);
       ioService.generateJSCoverFilesForWebServer(reportDir, configuration.getVersion());
       sendResponse(HTTP_STATUS.HTTP_OK, MIME.TEXT_PLAIN, "Coverage data stored at " + reportDir);
     } catch (Throwable t) {
       t.printStackTrace();
       String message =
           format("Error saving coverage data. Try deleting JSON file at %s\n", reportDir);
       sendResponse(HTTP_STATUS.HTTP_OK, MIME.TEXT_PLAIN, message);
     }
   } else {
     if (configuration.isProxy()) proxyService.handleProxyPost(request, data, os);
     else super.handlePost(request, data);
   }
 }
示例#11
0
 @Before
 public void init() throws InterruptedException {
   counter = 0;
   random = new Random(DateTime.now().getMillis());
   gson = new Gson();
   httpServer = new HttpServer();
   httpServer.start();
 }
示例#12
0
 /* ------------------------------------------------------------ */
 protected void statsRequestStart() {
   if (_statsOn) {
     if (_reqTime > 0) statsRequestEnd();
     _requests++;
     _tmpTime = _request.getTimeStamp();
     _reqTime = _tmpTime;
     _httpServer.statsGotRequest();
   }
 }
示例#13
0
  public void stopHttpServer(HttpServer httpServer) {
    try {
      httpServer.stop(true);
    } catch (InterruptedException ie) {
      SysLog.logThrowable(ie);
    }

    SysLog.logInfo("http server was stopped");
  }
示例#14
0
 public static void main(String[] args) throws Exception {
   MyAuthenticator auth = new MyAuthenticator();
   Authenticator.setDefault(auth);
   try {
     server = new HttpServer(new AuthHeaderTest(), 1, 10, 0);
     System.out.println("Server: listening on port: " + server.getLocalPort());
     client("http://localhost:" + server.getLocalPort() + "/d1/foo.html");
   } catch (Exception e) {
     if (server != null) {
       server.terminate();
     }
     throw e;
   }
   int f = auth.getCount();
   if (f != 1) {
     except("Authenticator was called " + f + " times. Should be 1");
   }
   server.terminate();
 }
示例#15
0
  @Test
  public void should_log_request_and_response_into_file() throws Exception {
    File file = folder.newFile();
    HttpServer server = httpServer(port(), log(file.getAbsolutePath()));
    server.request(by("0XCAFE")).response("0XBABE");

    running(
        server,
        new Runnable() {
          @Override
          public void run() throws Exception {
            assertThat(helper.postContent(root(), "0XCAFE"), is("0XBABE"));
          }
        });

    String actual = Files.toString(file, Charset.defaultCharset());
    assertThat(actual, containsString("0XCAFE"));
    assertThat(actual, containsString("0XCAFE"));
  }
示例#16
0
  private HttpResponseSetting bindToSession(HttpServer server) {
    if (isMount()) {
      return server.mount(mount.getDir(), to(mount.getUri()), mount.getMountPredicates());
    }

    if (isProxy()) {
      if (proxy.hasUrl()) {
        throw new IllegalArgumentException("It's not allowed to have URL in proxy from server");
      }

      return server.proxy(proxy.getProxyConfig(), proxy.getFailover());
    }

    if (isAnyResponse()) {
      return server.response(getResponseHandler());
    }

    if (isRedirectResponse()) {
      return server.request(getRequestMatcher()).redirectTo(redirectTo);
    }

    return server.request(getRequestMatcher()).response(getResponseHandler());
  }
示例#17
0
  @Test
  public void should_log_request_and_response_with_exception() throws Exception {
    File file = folder.newFile();
    HttpServer server = httpServer(port(), log(file.getAbsolutePath()));
    ResponseHandler mock = mock(ResponseHandler.class);
    doThrow(RuntimeException.class).when(mock).writeToResponse(any(SessionContext.class));

    server.request(by("0XCAFE")).response(mock);

    running(
        server,
        new Runnable() {
          @Override
          public void run() throws Exception {
            try {
              helper.postContent(root(), "0XCAFE");
            } catch (IOException ignored) {
            }
          }
        });

    String actual = Files.toString(file, Charset.defaultCharset());
    assertThat(actual, containsString("RuntimeException"));
  }
 @Override
 protected void handleGet(HttpRequest request) throws IOException {
   String uri = request.getPath();
   try {
     if (uri.equals("/jscoverage.js")) {
       sendResponse(
           HTTP_STATUS.HTTP_OK, request.getMime(), ioService.generateJSCoverageServerJS());
     } else if (uri.startsWith("/jscoverage.html")) {
       String reportHTML = ioService.generateJSCoverageHtml(configuration.getVersion());
       sendResponse(HTTP_STATUS.HTTP_OK, request.getMime(), reportHTML);
     } else if (uri.startsWith("/jscoverage")) {
       sendResponse(HTTP_STATUS.HTTP_OK, request.getMime(), ioService.getResourceAsStream(uri));
     } else if (uri.endsWith(".js") && !configuration.skipInstrumentation(uri.substring(1))) {
       String jsInstrumented;
       if (configuration.isProxy()) {
         String originalJS = proxyService.getUrl(request.getUrl());
         jsInstrumented =
             instrumenterService.instrumentJSForWebServer(
                 configuration.getCompilerEnvirons(),
                 originalJS,
                 uri,
                 configuration.isIncludeBranch());
       } else {
         if (configuration.isIncludeUnloadedJS()) uris.add(uri.substring(1));
         jsInstrumented =
             instrumenterService.instrumentJSForWebServer(
                 configuration.getCompilerEnvirons(),
                 new File(wwwRoot, uri),
                 uri,
                 configuration.isIncludeBranch());
       }
       sendResponse(HTTP_STATUS.HTTP_OK, MIME.JS, jsInstrumented);
     } else {
       if (configuration.isProxy()) proxyService.handleProxyGet(request, os);
       else super.handleGet(request);
     }
   } catch (Throwable e) {
     StringWriter stringWriter = new StringWriter();
     e.printStackTrace(new PrintWriter(stringWriter));
     sendResponse(
         HTTP_STATUS.HTTP_INTERNAL_SERVER_ERROR, MIME.TEXT_PLAIN, stringWriter.toString());
   }
 }
示例#19
0
 /* ------------------------------------------------------------ */
 protected void statsRequestEnd() {
   if (_statsOn && _reqTime > 0) {
     _httpServer.statsEndRequest(System.currentTimeMillis() - _reqTime, (_response != null));
     _reqTime = 0;
   }
 }
示例#20
0
  protected void configureHttpServer(HttpServer server) {

    // Favicon hack

    HttpContext faviconContext = new HttpContext();
    faviconContext.setContextPath("/favicon.ico");
    server.addContext(faviconContext);

    ResourceHandler faviconHandler = new ResourceHandler();
    faviconContext.setResourceBase(SysConfig.getStaticDir().getRootPath());
    faviconContext.addHandler(faviconHandler);

    faviconContext.addHandler(new NotFoundHandler());

    // robots.txt hack

    HttpContext robotsContext = new HttpContext();
    robotsContext.setContextPath("/robots.txt");
    server.addContext(robotsContext);

    ResourceHandler robotsHandler = new ResourceHandler();
    robotsContext.setResourceBase(SysConfig.getStaticDir().getRootPath());
    robotsContext.addHandler(robotsHandler);

    robotsContext.addHandler(new NotFoundHandler());

    // Dynamic content

    HttpContext servletContext = new HttpContext();
    servletContext.setContextPath("/");
    server.addContext(servletContext);

    ServletHandler servlets = new ServletHandler();
    servletContext.addHandler(servlets);
    servlets.addServlet("/*", "org.wahlzeit.main.MainServlet");

    servletContext.addHandler(new NotFoundHandler());

    // Photos content

    HttpContext photosContext = new HttpContext();
    photosContext.setContextPath(SysConfig.getPhotosDirAsString());
    server.addContext(photosContext);

    ResourceHandler photosHandler = new ResourceHandler();
    photosContext.setResourceBase(SysConfig.getPhotosDirAsString());
    photosContext.addHandler(photosHandler);

    photosContext.addHandler(new NotFoundHandler());

    // Static content

    HttpContext staticContext = new HttpContext();
    staticContext.setContextPath(SysConfig.getStaticDir().getRootPath());
    server.addContext(staticContext);

    ResourceHandler staticHandler = new ResourceHandler();
    staticContext.setResourceBase(SysConfig.getStaticDir().getRootPath());
    staticContext.addHandler(staticHandler);

    staticContext.addHandler(new NotFoundHandler());
  }
示例#21
0
 public void startHttpServer(HttpServer httpServer) throws Exception {
   httpServer.start();
   SysLog.logInfo("http server was started");
 }
 protected void publish() {
   server.publish(editor.toPlainText());
 }
示例#23
0
 public YokeTester(Verticle verticle, boolean fakeSSL) {
   super(verticle);
   this.vertx = verticle.getVertx();
   fakeServer.setSSL(fakeSSL);
   listen(fakeServer);
 }
示例#24
0
 @After
 public void tearDown() {
   httpServer.stop();
 }
示例#25
0
  public void request(
      final String method,
      final String url,
      final MultiMap headers,
      final Buffer body,
      final Handler<Response> handler) {
    try {
      final URI uri = new URI(url);
      final boolean urlEncoded =
          "application/x-www-form-urlencoded".equalsIgnoreCase(headers.get("content-type"));

      final Response response = new Response(vertx, handler);

      // start yoke
      fakeServer
          .requestHandler()
          .handle(
              new HttpServerRequest() {

                MultiMap params = null;
                MultiMap attributes = null;

                @Override
                public HttpVersion version() {
                  return HttpVersion.HTTP_1_1;
                }

                @Override
                public String method() {
                  return method.toUpperCase();
                }

                @Override
                public String uri() {
                  return uri.getPath() + "?" + uri.getQuery() + "#" + uri.getFragment();
                }

                @Override
                public String path() {
                  return uri.getPath();
                }

                @Override
                public String query() {
                  return uri.getQuery();
                }

                @Override
                public HttpServerResponse response() {
                  return response;
                }

                @Override
                public MultiMap headers() {
                  return headers;
                }

                @Override
                public MultiMap params() {
                  if (params == null) {
                    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(uri());
                    Map<String, List<String>> prms = queryStringDecoder.parameters();
                    params = new CaseInsensitiveMultiMap();

                    if (!prms.isEmpty()) {
                      for (Map.Entry<String, List<String>> entry : prms.entrySet()) {
                        params.add(entry.getKey(), entry.getValue());
                      }
                    }
                  }
                  return params;
                }

                @Override
                public InetSocketAddress remoteAddress() {
                  return new InetSocketAddress("127.0.0.1", 80);
                }

                @Override
                public X509Certificate[] peerCertificateChain() throws SSLPeerUnverifiedException {
                  return null;
                }

                @Override
                public URI absoluteURI() {
                  return uri;
                }

                @Override
                public HttpServerRequest bodyHandler(Handler<Buffer> bodyHandler) {
                  bodyHandler.handle(body);
                  return this;
                }

                @Override
                public HttpServerRequest dataHandler(Handler<Buffer> handler) {
                  handler.handle(body);
                  return this;
                }

                @Override
                public HttpServerRequest pause() {
                  throw new UnsupportedOperationException("This mock does not support pause");
                }

                @Override
                public HttpServerRequest resume() {
                  throw new UnsupportedOperationException("This mock does not support resume");
                }

                @Override
                public HttpServerRequest endHandler(Handler<Void> endHandler) {
                  endHandler.handle(null);
                  return this;
                }

                @Override
                public NetSocket netSocket() {
                  throw new UnsupportedOperationException("This mock does not support netSocket");
                }

                @Override
                public HttpServerRequest expectMultiPart(boolean expect) {
                  // NOOP
                  return this;
                }

                @Override
                public HttpServerRequest uploadHandler(
                    Handler<HttpServerFileUpload> uploadHandler) {
                  throw new UnsupportedOperationException(
                      "This mock does not support uploadHandler");
                }

                @Override
                public MultiMap formAttributes() {
                  if (attributes == null) {
                    attributes = new CaseInsensitiveMultiMap();
                    if (urlEncoded) {
                      QueryStringDecoder queryStringDecoder =
                          new QueryStringDecoder(body.toString(), false);

                      Map<String, List<String>> prms = queryStringDecoder.parameters();

                      if (!prms.isEmpty()) {
                        for (Map.Entry<String, List<String>> entry : prms.entrySet()) {
                          attributes.add(entry.getKey(), entry.getValue());
                        }
                      }
                    }
                  }
                  return attributes;
                }

                @Override
                public HttpServerRequest exceptionHandler(Handler<Throwable> handler) {
                  throw new UnsupportedOperationException(
                      "This mock does not support exceptionHandler");
                }
              });
    } catch (URISyntaxException e) {
      throw new RuntimeException(e);
    }
  }
 @Override
 protected void handleHead(HttpRequest request) {
   if (configuration.isProxy()) proxyService.handleProxyHead(request, os);
   else super.handleHead(request);
 }
示例#27
0
 public static void except(String s) {
   server.terminate();
   throw new RuntimeException(s);
 }
示例#28
0
 /**
  * Service a Request. This implementation passes the request and response to the service method of
  * the HttpServer for this connections listener. If no HttpServer has been associated, the 503 is
  * returned. This method may be specialized to implement other ways of servicing a request.
  *
  * @param request The request
  * @param response The response
  * @return The HttpContext that completed handling of the request or null.
  * @exception HttpException
  * @exception IOException
  */
 protected HttpContext service(HttpRequest request, HttpResponse response)
     throws HttpException, IOException {
   if (_httpServer == null) throw new HttpException(HttpResponse.__503_Service_Unavailable);
   return _httpServer.service(request, response);
 }
示例#29
0
 @Override
 public InetSocketAddress getSocketAddress() {
   return httpServer == null ? null : httpServer.getSocketAddress();
 }
 protected void tearDown() throws Exception {
   if (this.server != null) {
     server.stop();
   }
 }