io.vertx.ext.web.handler.sockjs.SockJSHandler Java Examples

The following examples show how to use io.vertx.ext.web.handler.sockjs.SockJSHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebExamples.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
public void handleSocketIdle(Vertx vertx, PermittedOptions inboundPermitted) {
  Router router = Router.router(vertx);

  // Initialize SockJS handler
  SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
  SockJSBridgeOptions options = new SockJSBridgeOptions()
    .addInboundPermitted(inboundPermitted)
    .setPingTimeout(5000);

  // mount the bridge on the router
  router
    .mountSubRouter("/eventbus", sockJSHandler.bridge(options, be -> {
      if (be.type() == BridgeEventType.SOCKET_IDLE) {
        // Do some custom handling...
      }

      be.complete(true);
    }));
}
 
Example #2
Source File: VertxVaadin.java    From vertx-vaadin with MIT License 6 votes vote down vote up
private void initSockJS(Router vaadinRouter, SessionHandler sessionHandler) {
    if (this.config.supportsSockJS()) {
        SockJSHandlerOptions options = new SockJSHandlerOptions()
            .setSessionTimeout(config().sessionTimeout())
            .setHeartbeatInterval(service.getDeploymentConfiguration().getHeartbeatInterval() * 1000);
        SockJSHandler sockJSHandler = SockJSHandler.create(vertx, options);

        SockJSPushHandler pushHandler = new SockJSPushHandler(service, sessionHandler, sockJSHandler);

        String pushPath = config.pushURL().replaceFirst("/$", "") + "/*";
        logger.debug("Setup PUSH communication on {}", pushPath);

        vaadinRouter.route(pushPath).handler(rc -> {
            if (ApplicationConstants.REQUEST_TYPE_PUSH.equals(rc.request().getParam(ApplicationConstants.REQUEST_TYPE_PARAMETER))) {
                pushHandler.handle(rc);
            } else {
                rc.next();
            }
        });
    } else {
        logger.info("PUSH communication over SockJS is disabled");
    }
}
 
Example #3
Source File: SockJSVisitor.java    From nubes with Apache License 2.0 6 votes vote down vote up
public void visit() {
  sockJSHandler = SockJSHandler.create(config.getVertx(), config.getSockJSOptions());
  try {
    instance = clazz.newInstance();
    injectServices();
  } catch (Exception e) {
    throw new VertxException("Could not instanciate socket controller : " + clazz.getName(), e);
  }
  createHandlers();
  sockJSHandler.socketHandler(ws -> {
    openHandlers.forEach(handler -> tryToInvoke(instance, handler, ws, null));
    ws.handler(buff -> messageHandlers.forEach(messageHandler -> tryToInvoke(instance, messageHandler, ws, buff)));
    ws.endHandler(voidz -> closeHandlers.forEach(closeHandler -> tryToInvoke(instance, closeHandler, ws, null)));
  });
  normalizePath();
  router.route(path).handler(sockJSHandler);
}
 
Example #4
Source File: AppServer.java    From mpns with Apache License 2.0 6 votes vote down vote up
private void initWebSocket() {
    Router router = Router.router(vertx);
    SockJSHandlerOptions options = new SockJSHandlerOptions()
            .setHeartbeatInterval(1000 * 60);
    SockJSHandler sockJSHandler = SockJSHandler.create(vertx, options);

    PermittedOptions inboundPermitted = new PermittedOptions().setAddressRegex("server/.*");
    PermittedOptions outboundPermitted = new PermittedOptions().setAddressRegex("client/.*");

    BridgeOptions ops = new BridgeOptions()
            .addInboundPermitted(inboundPermitted)
            .addOutboundPermitted(outboundPermitted);

    sockJSHandler.bridge(ops);

    router.route("/eb/*").handler(sockJSHandler);
    mainRouter.mountSubRouter("/ws", router);
}
 
Example #5
Source File: ExampleChatSockjs.java    From vertxui with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void start() {
	// Chat with SockJS
	Router router = Router.router(vertx);
	List<String> ids = new ArrayList<>();
	router.route(Client.url + "/*").handler(SockJSHandler.create(vertx).socketHandler(socket -> {
		final String id = socket.writeHandlerID();
		ids.add(id); // entering
		socket.endHandler(data -> {
			ids.remove(id); // leaving
		});
		socket.handler(buffer -> { // receiving

			// extra: pojo example
			if (Pojofy.socket(socket, Client.urlPojo, buffer, Dto.class, this::serviceDoSomething)) {
				return;
			}

			ids.forEach(i -> vertx.eventBus().send(i, buffer)); // broadcasting
			// to reply to one: socket.write()

		});
	}));

	AllExamplesServer.start(Client.class, router);
}
 
Example #6
Source File: SockJsExample.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
public void init(@Observes Router router) {
    SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
    sockJSHandler.bridge(new BridgeOptions(new JsonObject())
            .addOutboundPermitted(new PermittedOptions().setAddress("ticks")));
    router.route("/eventbus/*").handler(sockJSHandler);

    AtomicInteger counter = new AtomicInteger();
    vertx.setPeriodic(1000,
        ignored -> vertx.eventBus().publish("ticks", counter.getAndIncrement()));
}
 
Example #7
Source File: WebExamples.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public void example49(Vertx vertx) {

    Router router = Router.router(vertx);

    // Let through any messages sent to 'demo.orderMgr' from the client
    PermittedOptions inboundPermitted = new PermittedOptions()
      .setAddress("demo.someService");

    SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
    SockJSBridgeOptions options = new SockJSBridgeOptions()
      .addInboundPermitted(inboundPermitted);

    // mount the bridge on the router
    router
      .mountSubRouter("/eventbus", sockJSHandler
        .bridge(options, be -> {
          if (be.type() == BridgeEventType.PUBLISH ||
            be.type() == BridgeEventType.RECEIVE) {

            if (be.getRawMessage().getString("body").equals("armadillos")) {
              // Reject it
              be.complete(false);
              return;
            }
          }
          be.complete(true);
        }));
  }
 
Example #8
Source File: WebExamples.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public void example48_1(Vertx vertx) {

    Router router = Router.router(vertx);

    // Let through any messages sent to 'demo.orderService' from the client
    PermittedOptions inboundPermitted = new PermittedOptions()
      .setAddress("demo.orderService");

    SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
    SockJSBridgeOptions options = new SockJSBridgeOptions()
      .addInboundPermitted(inboundPermitted);

    // mount the bridge on the router
    router.mountSubRouter(
      "/eventbus",
      sockJSHandler.bridge(options, be -> {
        if (
          be.type() == BridgeEventType.PUBLISH ||
            be.type() == BridgeEventType.SEND) {

          // Add some headers
          JsonObject headers = new JsonObject()
            .put("header1", "val")
            .put("header2", "val2");

          JsonObject rawMessage = be.getRawMessage();
          rawMessage.put("headers", headers);
          be.setRawMessage(rawMessage);
        }
        be.complete(true);
      }));
  }
 
Example #9
Source File: WebExamples.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public void example45(Vertx vertx) {

    Router router = Router.router(vertx);

    SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
    SockJSBridgeOptions options = new SockJSBridgeOptions();
    // mount the bridge on the router
    router.mountSubRouter("/eventbus", sockJSHandler.bridge(options));
  }
 
Example #10
Source File: ExampleChatEventbus.java    From vertxui with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void start() {
	// Initialize the router and a webserver with HTTP-compression
	Router router = Router.router(vertx);

	PermittedOptions freewayOK = new PermittedOptions().setAddress(Client.freeway);
	PermittedOptions myDtoOK = new PermittedOptions().setAddress(Client.addressPojo);
	BridgeOptions firewall = new BridgeOptions().addInboundPermitted(freewayOK).addOutboundPermitted(freewayOK)
			.addInboundPermitted(myDtoOK).addOutboundPermitted(myDtoOK);
	router.route(Client.url + "/*").handler(SockJSHandler.create(vertx).bridge(firewall
	// If you want to know the sender, add it as header:
	// , be -> {
	// if (be.type() == BridgeEventType.RECEIVE || be.type() ==
	// BridgeEventType.PUBLISH) {
	// JsonObject headers = be.getRawMessage().getJsonObject("headers");
	// if (headers == null) {
	// headers = new JsonObject();
	// be.getRawMessage().put("headers", headers); }
	// headers.put("sender", be.socket().writeHandlerID()); }
	// be.complete(true); }
	));

	// to broadcast: vertx.eventBus().publish(Client.freeway,"Bla");
	// to receive: vertx.eventBus().consumer(Client.freeway, m -> ... );
	// broadcasting to everyone is done automaticly by .publish()

	// extra: pojo example
	Pojofy.eventbus(Client.addressPojo, Dto.class, this::serviceDoSomething);

	AllExamplesServer.start(Client.class, router);
}
 
Example #11
Source File: MonitorDashboardVerticle.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
@Override
public void start() throws Exception {
  super.start();
  Router router = Router.router(vertx);

  // create Dropwizard metrics service
  MetricsService service = MetricsService.create(vertx);

  // event bus bridge
  SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
  BridgeOptions options = new BridgeOptions()
    .addOutboundPermitted(new PermittedOptions().setAddress("microservice.monitor.metrics"))
    .addOutboundPermitted(new PermittedOptions().setAddress("events.log"));

  sockJSHandler.bridge(options);
  router.route("/eventbus/*").handler(sockJSHandler);

  // discovery endpoint
  ServiceDiscoveryRestEndpoint.create(router, discovery);

  // static content
  router.route("/*").handler(StaticHandler.create());

  int port = config().getInteger("monitor.http.port", 9100);
  String host = config().getString("monitor.http.host", "0.0.0.0");
  int metricsInterval = config().getInteger("monitor.metrics.interval", 5000);

  vertx.createHttpServer()
    .requestHandler(router::accept)
    .listen(port, host);

  // send metrics message to the event bus
  vertx.setPeriodic(metricsInterval, t -> {
    JsonObject metrics = service.getMetricsSnapshot(vertx);
    vertx.eventBus().publish("microservice.monitor.metrics", metrics);
  });
}
 
Example #12
Source File: WebVerticle.java    From djl-demo with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
	HttpServer server = vertx.createHttpServer();
	Router router = Router.router(vertx);
	router.route().handler(BodyHandler.create());

	SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
	BridgeOptions options = new BridgeOptions();

	options.addInboundPermitted(new PermittedOptions().setAddress(ADDRESS_TRAINER_REQUEST));

	options.addOutboundPermitted(new PermittedOptions().setAddress(ADDRESS_TRAINER));

	// Event bus
	router.mountSubRouter("/api/eventbus", sockJSHandler.bridge(options));

	// Static content (UI)
	router.route("/*").handler(StaticHandler.create());
	router.route("/*").handler(rc -> {
		if (!rc.currentRoute().getPath().startsWith("/api")) {
			rc.reroute("/index.html");
		}
	});

	server.requestHandler(router).listen(port, http -> {
		if (http.succeeded()) {
			LOGGER.info("HTTP server started: http://localhost:{0}", String.valueOf(port));
		} else {
			LOGGER.info("HTTP server failed on port {0}", String.valueOf(port));
		}
	});
}
 
Example #13
Source File: VertxVaadin.java    From vertx-vaadin with MIT License 5 votes vote down vote up
private void initSockJS(Router vaadinRouter, SessionHandler sessionHandler) {
    logger.debug("Routing PUSH requests on /PUSH/* ");
    SockJSHandlerOptions options = new SockJSHandlerOptions()
        .setSessionTimeout(config().getLong("sessionTimeout", DEFAULT_SESSION_TIMEOUT))
        .setHeartbeatInterval(service.getDeploymentConfiguration().getHeartbeatInterval() * 1000);
    SockJSHandler sockJSHandler = SockJSHandler.create(vertx, options);
    SockJSPushHandler pushHandler = new SockJSPushHandler(service, sessionHandler, sockJSHandler);
    vaadinRouter.route("/PUSH/*").handler(pushHandler);
}
 
Example #14
Source File: SockJSPushHandler.java    From vertx-vaadin with MIT License 5 votes vote down vote up
public SockJSPushHandler(VertxVaadinService service, SessionHandler sessionHandler, SockJSHandler sockJSHandler) {
    this.service = service;
    this.sessionHandler = sessionHandler;
    this.sockJSHandler = sockJSHandler;
    this.connectedSocketsLocalMap = socketsMap(service.getVertx());
    this.sockJSHandler.socketHandler(this::onConnect);
}
 
Example #15
Source File: ShoppingUIVerticle.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Future<Void> future) throws Exception {
  super.start();
  Router router = Router.router(vertx);

  // event bus bridge
  SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
  router.route("/eventbus/*").handler(sockJSHandler);

  // static content
  router.route("/*").handler(StaticHandler.create());

  // get HTTP host and port from configuration, or use default value
  String host = config().getString("shopping.ui.http.address", "0.0.0.0");
  int port = config().getInteger("shopping.ui.http.port", 8080);

  // create HTTP server
  vertx.createHttpServer()
    .requestHandler(router::accept)
    .listen(port, ar -> {
      if (ar.succeeded()) {
        future.complete();
        logger.info(String.format("Shopping UI service is running at %d", port));
      } else {
        future.fail(ar.cause());
      }
    });
}
 
Example #16
Source File: DashboardVerticle.java    From vertx-microservices-workshop with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Future<Void> future) {
  super.start();
  Router router = Router.router(vertx);

  // Event bus bridge
  SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
  BridgeOptions options = new BridgeOptions();
  options
      .addOutboundPermitted(new PermittedOptions().setAddress("market"))
      .addOutboundPermitted(new PermittedOptions().setAddress("portfolio"))
      .addOutboundPermitted(new PermittedOptions().setAddress("service.portfolio"))
      .addInboundPermitted(new PermittedOptions().setAddress("service.portfolio"))
      .addOutboundPermitted(new PermittedOptions().setAddress("vertx.circuit-breaker"));

  sockJSHandler.bridge(options);
  router.route("/eventbus/*").handler(sockJSHandler);

  // Discovery endpoint
  ServiceDiscoveryRestEndpoint.create(router, discovery);

  // Last operations
  router.get("/operations").handler(this::callAuditServiceWithExceptionHandlerWithCircuitBreaker);

  // Static content
  router.route("/*").handler(StaticHandler.create());

  // Create a circuit breaker.
  circuit = CircuitBreaker.create("http-audit-service", vertx,
      new CircuitBreakerOptions()
          .setMaxFailures(2)
          .setFallbackOnFailure(true)
          .setResetTimeout(2000)
          .setTimeout(1000))
      .openHandler(v -> retrieveAuditService());

  vertx.createHttpServer()
      .requestHandler(router::accept)
      .listen(8080, ar -> {
        if (ar.failed()) {
          future.fail(ar.cause());
        } else {
          retrieveAuditService();
          future.complete();
        }
      });
}
 
Example #17
Source File: DashboardVerticle.java    From vertx-microservices-workshop with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Future<Void> future) {
  super.start();
  Router router = Router.router(vertx);

  // Event bus bridge
  SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
  BridgeOptions options = new BridgeOptions();
  options
      .addOutboundPermitted(new PermittedOptions().setAddress("market"))
      .addOutboundPermitted(new PermittedOptions().setAddress("portfolio"))
      .addOutboundPermitted(new PermittedOptions().setAddress("service.portfolio"))
      .addInboundPermitted(new PermittedOptions().setAddress("service.portfolio"))
      .addOutboundPermitted(new PermittedOptions().setAddress("vertx.circuit-breaker"));

  sockJSHandler.bridge(options);
  router.route("/eventbus/*").handler(sockJSHandler);

  // Discovery endpoint
  ServiceDiscoveryRestEndpoint.create(router, discovery);

  // Last operations
  router.get("/operations").handler(this::callAuditService);

  // Static content
  router.route("/*").handler(StaticHandler.create());

  // Create a circuit breaker.
  circuit = CircuitBreaker.create("http-audit-service", vertx,
      new CircuitBreakerOptions()
          .setMaxFailures(2)
          .setFallbackOnFailure(true)
          .setResetTimeout(2000)
          .setTimeout(1000))
      .openHandler(v -> retrieveAuditService());

  vertx.createHttpServer()
      .requestHandler(router::accept)
      .listen(8080, ar -> {
        if (ar.failed()) {
          future.fail(ar.cause());
        } else {
          retrieveAuditService();
          future.complete();
        }
      });
}
 
Example #18
Source File: LiveScoreVerticle.java    From camelinaction2 with Apache License 2.0 4 votes vote down vote up
@Override
public void start() throws Exception {

    // create a vertx router to setup websocket and http server
    Router router = Router.router(vertx);

    // configure allowed inbound and outbound traffics
    BridgeOptions options = new BridgeOptions()
            .addInboundPermitted(new PermittedOptions().setAddress("control"))
            .addOutboundPermitted(new PermittedOptions().setAddress("clock"))
            .addOutboundPermitted(new PermittedOptions().setAddress("games"))
            .addOutboundPermitted(new PermittedOptions().setAddress("goals"));

    // route websocket to vertx
    router.route("/eventbus/*").handler(SockJSHandler.create(vertx).bridge(options, event -> {
        if (event.type() == BridgeEventType.SOCKET_CREATED) {
            System.out.println("Websocket connection created");

            // a new client connected so setup its screen with the list of games
            vertx.setTimer(500, h -> initGames());

        } else if (event.type() == BridgeEventType.SOCKET_CLOSED) {
            System.out.println("Websocket connection closed");
        }

        event.complete(true);
    }));

    // serve the static resources (src/main/resources/webroot)
    router.route().handler(StaticHandler.create());

    // let router accept on port 8080
    System.out.println("Listening on http://localhost:8080");
    vertx.createHttpServer().requestHandler(router::accept).listen(8080);

    // init control buttons
    initControls();

    // start streaming live score
    streamLiveScore();
}
 
Example #19
Source File: LiveScoreVerticle.java    From camelinaction2 with Apache License 2.0 4 votes vote down vote up
@Override
public void start() throws Exception {

    // create a CamelContext
    camelContext = new DefaultCamelContext();
    // add the Camel routes which streams live scores
    camelContext.addRoutes(new LiveScoreRouteBuilder(vertx));
    // create a producer template which is used below when a new client connects
    template = camelContext.createFluentProducerTemplate();
    // start Camel
    camelContext.start();

    // create a vertx router to setup websocket and http server
    Router router = Router.router(vertx);

    // configure allowed inbound and outbound traffics
    BridgeOptions options = new BridgeOptions()
            .addInboundPermitted(new PermittedOptions().setAddress("control"))
            .addOutboundPermitted(new PermittedOptions().setAddress("clock"))
            .addOutboundPermitted(new PermittedOptions().setAddress("games"))
            .addOutboundPermitted(new PermittedOptions().setAddress("goals"));

    // route websocket to vertx
    router.route("/eventbus/*").handler(SockJSHandler.create(vertx).bridge(options, event -> {
        if (event.type() == BridgeEventType.SOCKET_CREATED) {
            System.out.println("Websocket connection created");

            // a new client connected so setup its screen with the list of games
            vertx.setTimer(100, h -> template.to("direct:init-games").send());

        } else if (event.type() == BridgeEventType.SOCKET_CLOSED) {
            System.out.println("Websocket connection closed");
        }

        event.complete(true);
    }));

    // serve the static resources (src/main/resources/webroot)
    router.route().handler(StaticHandler.create());

    // let router accept on port 8080
    System.out.println("Listening on http://localhost:8080");
    vertx.createHttpServer().requestHandler(router::accept).listen(8080);
}
 
Example #20
Source File: HttpTermServer.java    From vertx-shell with Apache License 2.0 4 votes vote down vote up
@Override
public TermServer listen(Handler<AsyncResult<Void>> listenHandler) {

  Charset charset = Charset.forName(options.getCharset());

  boolean createServer = false;
  if (router == null) {
    createServer = true;
    router = Router.router(vertx);
  }

  if (options.getAuthOptions() != null) {
    authProvider = ShellAuth.load(vertx, options.getAuthOptions());
  }

  if (options.getSockJSPath() != null && options.getSockJSHandlerOptions() != null) {
    if (authProvider != null) {
      AuthenticationHandler basicAuthHandler = BasicAuthHandler.create(authProvider);
      router.route(options.getSockJSPath()).handler(basicAuthHandler);
    }

    Buffer inputrc = Helper.loadResource(vertx.fileSystem(), options.getIntputrc());
    if (inputrc == null) {
      if (listenHandler != null) {
        listenHandler.handle(Future.failedFuture("Could not load inputrc from " + options.getIntputrc()));
      }
      return this;
    }
    Keymap keymap = new Keymap(new ByteArrayInputStream(inputrc.getBytes()));
    SockJSHandler sockJSHandler = SockJSHandler.create(vertx, options.getSockJSHandlerOptions());
    sockJSHandler.socketHandler(new SockJSTermHandlerImpl(vertx, charset, keymap).termHandler(termHandler));
    router.route(options.getSockJSPath()).handler(sockJSHandler);
  }

  if (options.getVertsShellJsResource() != null) {
    router.get("/vertxshell.js").handler(ctx -> ctx.response().putHeader("Content-Type", "application/javascript").end(options.getVertsShellJsResource()));
  }
  if (options.getTermJsResource() != null) {
    router.get("/term.js").handler(ctx -> ctx.response().putHeader("Content-Type", "application/javascript").end(options.getTermJsResource()));
  }
  if (options.getShellHtmlResource() != null) {
    router.get("/shell.html").handler(ctx -> ctx.response().putHeader("Content-Type", "text/html").end(options.getShellHtmlResource()));
  }

  if (createServer) {
    server = vertx.createHttpServer(options);
    server.requestHandler(router);
    server.listen(ar -> {
      if (listenHandler != null) {
        if (ar.succeeded()) {
          listenHandler.handle(Future.succeededFuture());
        } else {
          listenHandler.handle(Future.failedFuture(ar.cause()));
        }
      }
    });
  } else {
    if (listenHandler != null) {
      listenHandler.handle(Future.succeededFuture());
    }
  }
  return this;
}
 
Example #21
Source File: HttpServer.java    From Lealone-Plugins with Apache License 2.0 4 votes vote down vote up
private void setSockJSHandler(Router router) {
    SockJSHandlerOptions options = new SockJSHandlerOptions().setHeartbeatInterval(2000);
    SockJSHandler sockJSHandler = SockJSHandler.create(vertx, options);
    sockJSHandler.socketHandler(new ServiceHandler());
    router.route(apiPath).handler(sockJSHandler);
}
 
Example #22
Source File: DashboardVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 4 votes vote down vote up
@Override
public void start() throws Exception {

    Router router = Router.router(vertx);

    SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
    BridgeOptions options = new BridgeOptions();
    options
        .addOutboundPermitted(new PermittedOptions().setAddress("market"))
        .addOutboundPermitted(new PermittedOptions().setAddress("portfolio"))
        .addOutboundPermitted(new PermittedOptions().setAddress("service.portfolio"))
        .addInboundPermitted(new PermittedOptions().setAddress("service.portfolio"))
        .addOutboundPermitted(new PermittedOptions().setAddress("vertx.circuit-breaker"));

    sockJSHandler.bridge(options);
    router.route("/eventbus/*").handler(sockJSHandler);

    // Last operations
    router.get("/operations").handler(this::callAuditService);
    router.get("/health").handler(rc -> rc.response().end("OK"));


    MetricRegistry dropwizardRegistry = SharedMetricRegistries.getOrCreate(
        System.getProperty("vertx.metrics.options.registryName")
    );

    ServiceDiscovery.create(vertx, discovery -> {
        this.discovery = discovery;
        WebConsoleRegistry.create("/admin")
            // Add pages
            .addPage(MetricsConsolePage.create(dropwizardRegistry))
            .addPage(new TraderPage())
            .addPage(ServicesConsolePage.create(discovery))
            .addPage(CircuitBreakersConsolePage.create())
            .setCacheBusterEnabled(true) // Adds random query string to scripts
            // Mount to router
            .mount(vertx, router);

        retrieveAuditService();
        vertx.createHttpServer()
            .requestHandler(router::accept)
            .listen(8080);
    });

}
 
Example #23
Source File: WebExamples.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
public void example44(Vertx vertx) {

    Router router = Router.router(vertx);

    SockJSHandlerOptions options = new SockJSHandlerOptions()
      .setHeartbeatInterval(2000);

    SockJSHandler sockJSHandler = SockJSHandler.create(vertx, options);

    sockJSHandler.socketHandler(sockJSSocket -> {

      // Just echo the data back
      sockJSSocket.handler(sockJSSocket::write);
    });

    router.route("/myapp/*").handler(sockJSHandler);
  }
 
Example #24
Source File: PubSubSockJsServer.java    From slime with MIT License 4 votes vote down vote up
@Override
  public void start() throws Exception{

	if( VertxHolder.getVertx() == null ) VertxHolder.setVertx(vertx);
	logger.info("Pub/Sub SockJs Server started on port {}", serverPort);
	
	Router router = Router.router(vertx);
	SockJSHandler socketHandler = SockJSHandler.create(vertx)
		.bridge(new BridgeOptions()
				.addOutboundPermitted(new PermittedOptions().setAddressRegex("^topic/.*"))
				
				// use to set client ping timeout -> will result closing connection if no ping sent
				/*.setPingTimeout(60000)*/,
				new Handler<BridgeEvent>() {
					@Override
					public void handle(BridgeEvent event) {
						boolean isResult = true;
						String message = "Oops!";
						
						System.out.println(event.type());
						
						EventBridgeChainResponse processInChain = eventBridgeChain.processInChain(event);
						if(processInChain.isProcesssed()) {
							if(processInChain.getException() != null) {
								isResult = false;
								logger.error(processInChain.getException().getMessage(), 
										processInChain.getException());
								message = processInChain.getException().getMessage();
							}
						}
						
					
						
						if(isResult) {
							
							if(event.type().equals(BridgeEventType.REGISTER)){
								System.out.println(event.getRawMessage());
								RedisSockjsClient.REGISTER(event);
							}
							
							
							event.complete(isResult);
						}
						else {
							event.fail(new Exception(message));
						}
						
					}
				});
	
	
	router.route("/sockjs/*").handler(
    	socketHandler
	);

	/*
	 * subscribe published message
	 */
	vertx.deployVerticle(new MessageSubscribeVerticle(), new DeploymentOptions().setWorker(true).setMultiThreaded(true));
	vertx.deployVerticle(new MessageSubscribeVerticle(), new DeploymentOptions().setWorker(true).setMultiThreaded(true));
	vertx.deployVerticle(new MessageSubscribeVerticle(), new DeploymentOptions().setWorker(true).setMultiThreaded(true));

    HttpServer server = vertx.createHttpServer().requestHandler(router::accept);
    
    
    server.listen(serverPort);

}
 
Example #25
Source File: WebExamples.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
public void example46(Vertx vertx) {

    Router router = Router.router(vertx);

    SockJSHandler sockJSHandler = SockJSHandler.create(vertx);


    // Let through any messages sent to 'demo.orderMgr' from the client
    PermittedOptions inboundPermitted1 = new PermittedOptions()
      .setAddress("demo.orderMgr");

    // Allow calls to the address 'demo.persistor' from the client as
    // long as the messages have an action field with value 'find'
    // and a collection field with value 'albums'
    PermittedOptions inboundPermitted2 = new PermittedOptions()
      .setAddress("demo.persistor")
      .setMatch(new JsonObject().put("action", "find")
        .put("collection", "albums"));

    // Allow through any message with a field `wibble` with value `foo`.
    PermittedOptions inboundPermitted3 = new PermittedOptions()
      .setMatch(new JsonObject().put("wibble", "foo"));

    // First let's define what we're going to allow from server -> client

    // Let through any messages coming from address 'ticker.mystock'
    PermittedOptions outboundPermitted1 = new PermittedOptions()
      .setAddress("ticker.mystock");

    // Let through any messages from addresses starting with "news."
    // (e.g. news.europe, news.usa, etc)
    PermittedOptions outboundPermitted2 = new PermittedOptions()
      .setAddressRegex("news\\..+");

    // Let's define what we're going to allow from client -> server
    SockJSBridgeOptions options = new SockJSBridgeOptions().
      addInboundPermitted(inboundPermitted1).
      addInboundPermitted(inboundPermitted1).
      addInboundPermitted(inboundPermitted3).
      addOutboundPermitted(outboundPermitted1).
      addOutboundPermitted(outboundPermitted2);

    // mount the bridge on the router
    router.mountSubRouter("/eventbus", sockJSHandler.bridge(options));
  }
 
Example #26
Source File: DashboardVerticle.java    From microtrader with MIT License 4 votes vote down vote up
@Override
public void start(Future<Void> future) {
    // Get configuration
    config = ConfigFactory.load();

    discovery = ServiceDiscovery.create(vertx, new ServiceDiscoveryOptions().setBackendConfiguration(config()));
    Router router = Router.router(vertx);

    // Event bus bridge
    SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
    BridgeOptions options = new BridgeOptions();
    options
            .addOutboundPermitted(new PermittedOptions().setAddress(config.getString("market.address")))
            .addOutboundPermitted(new PermittedOptions().setAddress(config.getString("portfolio.address")))
            .addOutboundPermitted(new PermittedOptions().setAddress("service.portfolio"))
            .addInboundPermitted(new PermittedOptions().setAddress("service.portfolio"))
            .addOutboundPermitted(new PermittedOptions().setAddress("vertx.circuit-breaker"));

    sockJSHandler.bridge(options);
    router.route("/eventbus/*").handler(sockJSHandler);

    // Discovery endpoint
    ServiceDiscoveryRestEndpoint.create(router, discovery);

    // Last operations
    router.get("/operations").handler(this::callAuditServiceWithExceptionHandlerWithCircuitBreaker);

    // Static content
    router.route("/*").handler(StaticHandler.create());

    // Create a circuit breaker.
    circuit = CircuitBreaker.create("http-audit-service", vertx,
            new CircuitBreakerOptions()
                    .setMaxFailures(2)
                    .setFallbackOnFailure(true)
                    .setResetTimeout(2000)
                    .setTimeout(1000))
                    .openHandler(v -> retrieveAuditService());

    vertx.createHttpServer()
            .requestHandler(router::accept)
            .listen(config.getInt("http.port"), ar -> {
                if (ar.failed()) {
                    future.fail(ar.cause());
                } else {
                    retrieveAuditService();
                    future.complete();
                }
            });
}
 
Example #27
Source File: SockJSPushHandler.java    From vertx-vaadin with MIT License 4 votes vote down vote up
public SockJSPushHandler(VertxVaadinService service, SessionHandler sessionHandler, SockJSHandler sockJSHandler) {
    this.service = service;
    this.sessionHandler = sessionHandler;
    this.connectedSocketsLocalMap = socketsMap(service.getVertx());
    this.router = sockJSHandler.socketHandler(this::onConnect);
}
 
Example #28
Source File: WebExamples.java    From vertx-web with Apache License 2.0 3 votes vote down vote up
public void example43(Vertx vertx) {

    Router router = Router.router(vertx);

    SockJSHandlerOptions options = new SockJSHandlerOptions()
      .setHeartbeatInterval(2000);

    SockJSHandler sockJSHandler = SockJSHandler.create(vertx, options);

    router.route("/myapp/*").handler(sockJSHandler);
  }
 
Example #29
Source File: WebExamples.java    From vertx-web with Apache License 2.0 3 votes vote down vote up
public void example48(Vertx vertx, AuthenticationProvider authProvider) {

    Router router = Router.router(vertx);

    // Let through any messages sent to 'demo.orderService' from the client
    PermittedOptions inboundPermitted = new PermittedOptions()
      .setAddress("demo.orderService");

    // But only if the user is logged in and has the authority "place_orders"
    inboundPermitted.setRequiredAuthority("place_orders");

    SockJSHandler sockJSHandler = SockJSHandler.create(vertx);

    // Now set up some basic auth handling:

    router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx)));

    AuthenticationHandler basicAuthHandler = BasicAuthHandler.create(authProvider);

    router.route("/eventbus/*").handler(basicAuthHandler);

    // mount the bridge on the router
    router.mountSubRouter(
      "/eventbus",
      sockJSHandler.bridge(new SockJSBridgeOptions()
        .addInboundPermitted(inboundPermitted)));
  }