Package org.vertx.java.core.http

Examples of org.vertx.java.core.http.HttpServer


public class SocketIOServerTest {

  public static void main(String[] args) throws InterruptedException {
    int port = 9090;
    final Vertx vertx = new DefaultVertx();
    HttpServer httpServer = vertx.createHttpServer();

    SocketIOServer io = new DefaultSocketIOServer(vertx, httpServer);
    io.configure(new Configurer() {
      public void configure(JsonObject config) {
        config.putString("transports", "websocket,flashsocket,xhr-polling,jsonp-polling,htmlfile");
      }
    });

    io.sockets().onConnection(new Handler<SocketIOSocket>() {
      public void handle(final SocketIOSocket socket) {
        System.out.println(socket.getId() + " is connected.");

        socket.on("timer", new Handler<JsonObject>() {
          public void handle(JsonObject data) {
            socket.emit("timer", data);
          }
        });

        socket.onDisconnect(new Handler<JsonObject>() {
          public void handle(JsonObject event) {
            System.out.println(socket.getId() + " is disconnected.");
          }
        });
      }
    });

    httpServer.listen(port);
    System.out.println("Server is running on http://localhost:" + port);
    Thread.sleep(Long.MAX_VALUE);
  }
View Full Code Here


  }

  @Override
  public void start() {
    int port = 9191;
    HttpServer server = vertx.createHttpServer();
    final SocketIOServer io = new DefaultSocketIOServer(vertx, server);

    io.sockets().onConnection(new Handler<SocketIOSocket>() {
      @Override
      public void handle(SocketIOSocket socket) {
        socket.on("newchannel", new Handler<JsonObject>() {
          @Override
          public void handle(JsonObject event) {
            System.out.println(event);
            newChannel(event.getString("channel"));
          }


        });
      }

      private void newChannel(String channel) {
        final Namespace namespace = io.of("/" + channel);
        namespace.onConnection(new Handler<SocketIOSocket>() {
          @Override
          public void handle(SocketIOSocket socket) {
            socket.on("message", new Handler<JsonObject>() {
              @Override
              public void handle(JsonObject event) {
                System.out.println(event);
                namespace.emit("message", event.getString("data"));
              }
            });
          }
        });
      }
    });

    server.listen(port);
  }
View Full Code Here

  }

  @Override
  public void start() {
    int port = 9191;
    HttpServer server = vertx.createHttpServer();
    SocketIOServer io = new DefaultSocketIOServer(vertx, server);

    io.sockets().onConnection(new Handler<SocketIOSocket>() {
      public void handle(final SocketIOSocket socket) {
        socket.on("set nickname", new Handler<JsonObject>() {
          public void handle(JsonObject name) {
            System.out.println("name: " + name);
            socket.set("nickname", name, new Handler<Void>() {
              public void handle(Void event) {
                System.out.println("set name");
                socket.emit("ready");
              }
            });
          }
        });

        socket.on("get nickname", new Handler<JsonObject>() {
          public void handle(JsonObject event) {
            socket.get("nickname", new Handler<JsonObject>(){
              public void handle(JsonObject data) {
                System.out.println("Chat message by " + data);
                socket.emit("get", data.getString("data"));
              }
            });
          }
        });

        socket.on("has nickname", new Handler<JsonObject>() {
          public void handle(JsonObject event) {
            socket.has("nickname", new Handler<Boolean>() {
              public void handle(Boolean has) {
                System.out.println("has nickname? " + has);
                socket.emit("has", has.toString());
              }
            });
          }
        });

        socket.on("del nickname", new Handler<JsonObject>() {
          public void handle(JsonObject event) {
            socket.del("nickname", new Handler<Void>() {
              public void handle(Void event) {
                System.out.println("del nickname");
                socket.emit("del");
              }
            });
          }
        });

        socket.on("confirm nickname", new Handler<JsonObject>() {
          public void handle(JsonObject event) {
            socket.has("nickname", new Handler<Boolean>() {
              public void handle(Boolean event) {
                System.out.println("has nickname? " + event);
                socket.emit("confirm", event.toString());
              }
            });
          }
        });
      }
    });

    server.listen(port);
  }
View Full Code Here

    public void start() {
        final SimplePushServerConfig config = fromConfig(container.config());
        final DataStore datastore = new InMemoryDataStore();
        final byte[] privateKey = DefaultSimplePushServer.generateAndStorePrivateKey(datastore, config);
        final SimplePushServer simplePushServer = new DefaultSimplePushServer(datastore, config, privateKey);
        final HttpServer httpServer = vertx.createHttpServer();
        setupHttpNotificationHandler(httpServer, simplePushServer);
        setupSimplePushSockJSServer(httpServer, simplePushServer);
        startHttpServer(httpServer);
        setupUserAgentReaperJob(simplePushServer);
    }
View Full Code Here

  public void start(final Future<Void> result) {
    super.start();
    address = getOptionalStringConfig("address", Topic.STORE);
    JsonObject rest = getOptionalObjectConfig("rest", new JsonObject());
    String path = rest.getString("prefix", "/store");
    HttpServer server = vertx.createHttpServer().setCompressionSupported(true);
    RouteMatcher matcher = new RouteMatcher();

    String snapshot = path + "/:docType/:docId";
    String ops = path + "/:docType/:docId" + Topic.OPS;
    Handler<HttpServerRequest> handler = new Handler<HttpServerRequest>() {
      @Override
      public void handle(final HttpServerRequest req) {
        JsonObject message = parseRequest(req);
        eb.sendWithTimeout(address, message, StoreModule.REPLY_TIMEOUT,
            new Handler<AsyncResult<Message<Object>>>() {
              @Override
              public void handle(AsyncResult<Message<Object>> ar) {
                if (ar.failed()) {
                  req.response().setStatusCode(500).setStatusMessage(ar.cause().getMessage()).end();
                  return;
                }
                Object body = ar.result().body();
                if (body == null) {
                  req.response().setStatusCode(404).end();
                  return;
                }
                if ("HEAD".equals(req.method())) {
                  req.response().end(body.toString());
                } else {
                  req.response().headers().set("Content-Type", "application/json");
                  req.response().end(((JsonObject) body).encode());
                }
              }
            });
      }
    };
    matcher.get(snapshot, handler);
    matcher.head(snapshot, handler);
    matcher.post(snapshot, new Handler<HttpServerRequest>() {
      @Override
      public void handle(final HttpServerRequest req) {
        final JsonObject message = parseRequest(req);
        req.bodyHandler(new Handler<Buffer>() {
          @Override
          public void handle(Buffer body) {
            message.putObject(Key.OP_DATA, new JsonObject(body.toString()));
            eb.sendWithTimeout(address, message, StoreModule.REPLY_TIMEOUT,
                new Handler<AsyncResult<Message<JsonObject>>>() {
                  @Override
                  public void handle(AsyncResult<Message<JsonObject>> ar) {
                    if (ar.failed()) {
                      req.response().setStatusCode(500).setStatusMessage(ar.cause().getMessage())
                          .end();
                      return;
                    }
                    JsonObject body = ar.result().body();
                    req.response().headers().set("Content-Type", "application/json");
                    req.response().end(body.encode());
                  }
                });
          }
        });
      }
    });

    matcher.get(ops, new Handler<HttpServerRequest>() {
      @Override
      public void handle(final HttpServerRequest req) {
        final JsonObject message = parseRequest(req);
        Long from = null;
        Long to = null;
        if (req.params().contains("from")) {
          from = Long.valueOf(req.params().get("from"));
        }
        if (req.params().contains("to")) {
          to = Long.valueOf(req.params().get("to"));
        }
        if (req.params().contains(Key.VERSION)) {
          from = Long.valueOf(req.params().get(Key.VERSION));
          to = from + 1;
        }
        message.putNumber("from", from).putNumber("to", to);
        eb.sendWithTimeout(address + Topic.OPS, message, StoreModule.REPLY_TIMEOUT,
            new Handler<AsyncResult<Message<JsonArray>>>() {
              @Override
              public void handle(AsyncResult<Message<JsonArray>> ar) {
                if (ar.failed()) {
                  req.response().setStatusCode(500).setStatusMessage(ar.cause().getMessage()).end();
                  return;
                }
                req.response().headers().set("Content-Type", "application/json");
                req.response().end(ar.result().body().encode());
              }
            });
      }
    });

    server.requestHandler(matcher).listen(rest.getInteger("port", 1987),
        rest.getString("host", "0.0.0.0"), new AsyncResultHandler<HttpServer>() {
          @Override
          public void handle(AsyncResult<HttpServer> ar) {
            if (!ar.succeeded()) {
              result.setFailure(ar.cause());
View Full Code Here

    @Override
    public void start() {
        JRubyVerticleFactory.vertx = vertx;
        JRubyVerticleFactory.container = container;
        JsonObject config = container.config();
        HttpServer httpServer = vertx.createHttpServer();
        String root = config.getString("root", ".");
        this.runtime = createRuntime(root, config);
        String expandedRoot = this.runtime.evalScriptlet("File.expand_path(%q(" + root + "))").asJavaString();
        this.runtime.setCurrentDirectory(expandedRoot);
        IRubyObject rackApplication = initRackApplication(config);
        final RackApplication app;
        boolean ssl = config.getBoolean("ssl");
        try {
            app = new RackApplication((WrappedVertx) vertx, runtime.getCurrentContext(), rackApplication, config);
            httpServer.setAcceptBacklog(10000);
            httpServer.requestHandler(new Handler<HttpServerRequest>() {
                public void handle(final HttpServerRequest req) {
                    app.call(req);
                }
            });
            if (config.containsField("event_bus")) {
                JsonArray allowAll = new JsonArray();
                allowAll.add(new JsonObject());
                JsonObject ebconf = new JsonObject();
                ebconf.putString("prefix", config.getString("event_bus"));
                vertx.createSockJSServer(httpServer).bridge(ebconf, allowAll, allowAll);
            }
            if (ssl) httpServer.setSSL(true).setKeyStorePath(config.getString("keystore_path"))
                    .setKeyStorePassword(config.getString("keystore_password"));
            httpServer.listen(config.getInteger("port"), config.getString("host"));
        } catch (IOException e) {
            container.logger().fatal("Failed to create RackApplication");
        }
    }
View Full Code Here

    public void init(
            final JerseyConfigurator configurator,
            final Handler<AsyncResult<HttpServer>> doneHandler) {

        // Create http server
        HttpServer server = configurator.getVertx().createHttpServer();

        // Performance tweak
        server.setAcceptBacklog(configurator.getAcceptBacklog());

        Integer receiveBufferSize = configurator.getReceiveBufferSize();
        if (receiveBufferSize != null && receiveBufferSize > 0) {
            // TODO: This doesn't seem to actually affect buffer size for dataHandler.  Is this being used correctly or is it a Vertx bug?
            server.setReceiveBufferSize(receiveBufferSize);
        }

        // Init jersey handler
        jerseyHandler.init(configurator);

        // Set request handler, use route matcher if a route handler is provided.
        if (routeMatcherHandler == null) {
            server.requestHandler(jerseyHandler);
        } else {
            RouteMatcher rm = new RouteMatcher();
            String pattern = jerseyHandler.getBaseUri().getPath() + "*";
            rm.all(pattern, jerseyHandler);
            routeMatcherHandler.handle(rm);
        }

        final String host = configurator.getHost();
        final int port = configurator.getPort();
        final Container container = configurator.getContainer();

        // Start listening and log success/failure
        server.listen(port, host, new Handler<AsyncResult<HttpServer>>() {
            @Override
            public void handle(AsyncResult<HttpServer> result) {
                final String listenPath = "http://" + host + ":" + port;
                if (result.succeeded()) {
                    container.logger().info("Http server listening for " + listenPath);
View Full Code Here

        final String host = getOptionalStringConfig(CONFIG_HOST, "0.0.0.0");
        final int port = getOptionalIntConfig(CONFIG_PORT, 80);
        int receiveBufferSize = getOptionalIntConfig(CONFIG_RECEIVE_BUFFER_SIZE, 0);

        // Create http server
        HttpServer server = vertx.createHttpServer();

        // Create jersey handler and set as request handler
        JerseyHandler handler = jerseyHandlerProvider.get();
        if (handler == null) {
            throw new IllegalStateException("A JerseyHandlerProvider has not been configured");
        }
        handler.init(vertx, container);
        server.requestHandler(handler);

        if (receiveBufferSize > 0) {
            // TODO: This doesn't seem to actually affect buffer size for dataHandler.  Is this being used correctly or is it a Vertx bug?
            server.setReceiveBufferSize(receiveBufferSize);
        }

        // Start listening and log success/failure
        server.listen(port, host, new Handler<AsyncResult<HttpServer>>() {
            @Override
            public void handle(AsyncResult<HttpServer> result) {
                final String listenPath = "http://" + host + ":" + port;
                if (result.succeeded()) {
                    container.logger().info("Http server listening for " + listenPath);
View Full Code Here

* @author <a href="http://tfox.org">Tim Fox</a>
*/
public class BridgeServer extends Verticle {

  public void start() throws Exception {
    HttpServer server = vertx.createHttpServer();

    // Also serve the static resources. In real life this would probably be done by a CDN
    server.requestHandler(new Handler<HttpServerRequest>() {
      public void handle(HttpServerRequest req) {
        if (req.path.equals("/")) req.response.sendFile("eventbusbridge/index.html"); // Serve the index.html
        if (req.path.endsWith("vertxbus.js")) req.response.sendFile("eventbusbridge/vertxbus.js"); // Serve the js
      }
    });

    JsonArray permitted = new JsonArray();
    permitted.add(new JsonObject()); // Let everything through
    SockJSServer sockJSServer = vertx.createSockJSServer(server);
    sockJSServer.bridge(new JsonObject().putString("prefix", "/eventbus"), permitted, permitted);

    server.listen(8080);
  }
View Full Code Here

import org.vertx.java.deploy.Verticle;

public class SockJSExample extends Verticle {

  public void start() {
    HttpServer server = vertx.createHttpServer();

    server.requestHandler(new Handler<HttpServerRequest>() {
      public void handle(HttpServerRequest req) {
        if (req.path.equals("/")) req.response.sendFile("sockjs/index.html"); // Serve the html
      }
    });

    SockJSServer sockServer = vertx.createSockJSServer(server);

    sockServer.installApp(new JsonObject().putString("prefix", "/testapp"), new Handler<SockJSSocket>() {
      public void handle(final SockJSSocket sock) {
        sock.dataHandler(new Handler<Buffer>() {
          public void handle(Buffer data) {
            sock.writeBuffer(data); // Echo it back
          }
        });
      }
    });

    server.listen(8080);
  }
View Full Code Here

TOP

Related Classes of org.vertx.java.core.http.HttpServer

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.