use of io.vertx.core.http.HttpServer in project georocket by georocket.
the class StoreEndpointTest method setupMockEndpoint.
private static Observable<HttpServer> setupMockEndpoint() {
JsonObject config = vertx.getOrCreateContext().config();
String host = config.getString(ConfigConstants.HOST, ConfigConstants.DEFAULT_HOST);
int port = config.getInteger(ConfigConstants.PORT, ConfigConstants.DEFAULT_PORT);
HttpServerOptions serverOptions = new HttpServerOptions().setCompressionSupported(true);
HttpServer server = vertxCore.createHttpServer(serverOptions);
ObservableFuture<HttpServer> observable = RxHelper.observableFuture();
server.requestHandler(getStoreEndpointRouter()::accept).listen(port, host, observable.toHandler());
return observable;
}
use of io.vertx.core.http.HttpServer in project incubator-servicecomb-java-chassis by apache.
the class RestServerVerticle method start.
@Override
public void start(Future<Void> startFuture) throws Exception {
try {
super.start();
// 如果本地未配置地址,则表示不必监听,只需要作为客户端使用即可
if (endpointObject == null) {
LOGGER.warn("rest listen address is not configured, will not start.");
startFuture.complete();
return;
}
Router mainRouter = Router.router(vertx);
mountAccessLogHandler(mainRouter);
initDispatcher(mainRouter);
HttpServer httpServer = createHttpServer();
httpServer.requestHandler(mainRouter::accept);
startListen(httpServer, startFuture);
} catch (Throwable e) {
// vert.x got some states that not print error and execute call back in VertexUtils.blockDeploy, we add a log our self.
LOGGER.error("", e);
throw e;
}
}
use of io.vertx.core.http.HttpServer in project microservices by pwillhan.
the class MainVerticle method startHttpServer.
private Future<Void> startHttpServer() {
System.out.println("#startHttpServer");
Future<Void> future = Future.future();
// <1>
HttpServer server = vertx.createHttpServer();
// <2>
Router router = Router.router(vertx);
// Bind "/" to our hello message - so are still compatible.
router.route("/").handler(routingContext -> {
HttpServerResponse response = routingContext.response();
response.putHeader("content-type", "text/html").end("<h1>Hello from Vert.x 3</h1>");
});
// Enables the reading of the request body for all routes under "/api/customers".
router.route("/api/customers*").handler(BodyHandler.create());
// GET all
// curl http://localhost:8080/api/customers
router.get("/api/customers").handler(this::getAll);
// POST
// curl -X POST http://localhost:8080/api/customers -H 'content-type: application/json' -d '{"name": "Tom", "age": "18"}'
router.post("/api/customers").handler(this::addOne);
server.requestHandler(// <5>
router::accept).listen(8080, ar -> {
// <6>
if (ar.succeeded()) {
LOGGER.info("HTTP server running on port 8080");
future.complete();
} else {
LOGGER.error("Could not start a HTTP server", ar.cause());
future.fail(ar.cause());
}
});
return future;
}
use of io.vertx.core.http.HttpServer in project raml-module-builder by folio-org.
the class RestVerticle method start.
@Override
public void start(Future<Void> startFuture) throws Exception {
readInGitProps();
// process cmd line arguments
cmdProcessing();
deploymentId = UUID.randomUUID().toString();
LogUtil.formatLogMessage(className, "start", "metrics enabled: " + vertx.isMetricsEnabled());
serverMetrics = MetricsService.create(vertx);
// maps paths found in raml to the generated functions to route to when the paths are requested
MappedClasses mappedURLs = populateConfig();
// set of exposed urls as declared in the raml
Set<String> urlPaths = mappedURLs.getAvailURLs();
// create a map of regular expression to url path
Map<String, Pattern> regex2Pattern = mappedURLs.buildURLRegex();
// Create a router object.
Router router = Router.router(vertx);
eventBus = vertx.eventBus();
log.info(context.getInstanceCount() + " verticles deployed ");
try {
// register codec to be able to pass pojos on the event bus
eventBus.registerCodec(new PojoEventBusCodec());
} catch (Exception e3) {
if (e3.getMessage().startsWith("Already a codec registered with name")) {
// needed in case we run multiple verticle instances
// in this vertx instace - re-registering the same codec twice throws an
// exception
log.info("Attempt to register PojoEventBusCodec again... this is acceptable ");
} else {
throw e3;
}
}
// needed so that we get the body content of the request - note that this
// will read the entire body into memory
final BodyHandler handler = BodyHandler.create();
// IMPORTANT!!!
// the body of the request will be read into memory for ALL PUT requests
// and for POST requests with the content-types below ONLY!!!
// multipart, for example will not be read by the body handler as vertx saves
// multiparts and www-encoded to disk - hence multiparts will be handled differently
// see uploadHandler further down
router.put().handler(handler);
router.post().consumes(SUPPORTED_CONTENT_TYPE_JSON_DEF).handler(handler);
router.post().consumes(SUPPORTED_CONTENT_TYPE_TEXT_DEF).handler(handler);
router.post().consumes(SUPPORTED_CONTENT_TYPE_XML_DEF).handler(handler);
router.post().consumes(SUPPORTED_CONTENT_TYPE_FORM).handler(handler);
// run pluggable startup code in a class implementing the InitAPI interface
// in the "org.folio.rest.impl" package
runHook(vv -> {
if (((Future<?>) vv).failed()) {
String reason = ((Future<?>) vv).cause().getMessage();
log.error(messages.getMessage("en", MessageConsts.InitializeVerticleFail, reason));
startFuture.fail(reason);
vertx.close();
System.exit(-1);
} else {
log.info("init succeeded.......");
try {
// startup periodic impl if exists
runPeriodicHook();
} catch (Exception e2) {
log.error(e2);
}
// single handler for all url calls other then documentation
// which is handled separately
router.routeWithRegex("^(?!.*apidocs).*$").handler(rc -> route(mappedURLs, urlPaths, regex2Pattern, rc));
// routes requests on “/assets/*” to resources stored in the “assets”
// directory.
router.route("/assets/*").handler(StaticHandler.create("assets"));
// In the following example all requests to paths starting with
// /apidocs/ will get served from the directory resources/apidocs:
// example:
// http://localhost:8181/apidocs/index.html?raml=raml/_patrons.raml
router.route("/apidocs/*").handler(StaticHandler.create("apidocs"));
// startup http server on port 8181 to serve documentation
if (port == -1) {
// we are here if port was not passed via cmd line
port = config().getInteger("http.port", 8081);
}
// check if mock mode requested and set sys param so that http client factory
// can config itself accordingly
String mockMode = config().getString(HttpClientMock2.MOCK_MODE);
if (mockMode != null) {
System.setProperty(HttpClientMock2.MOCK_MODE, mockMode);
}
// in anycase set the port so it is available to others via the config()
config().put("http.port", port);
Integer p = port;
// if client includes an Accept-Encoding header which includes
// the supported compressions - deflate or gzip.
HttpServerOptions serverOptions = new HttpServerOptions();
serverOptions.setCompressionSupported(false);
HttpServer server = vertx.createHttpServer(serverOptions);
server.requestHandler(router::accept).listen(p, // default to 8181.
result -> {
if (result.failed()) {
startFuture.fail(result.cause());
} else {
try {
runPostDeployHook(res2 -> {
if (!res2.succeeded()) {
log.error(res2.cause().getMessage(), res2.cause());
}
});
} catch (Exception e) {
log.error(e.getMessage(), e);
}
LogUtil.formatLogMessage(className, "start", "http server for apis and docs started on port " + p + ".");
LogUtil.formatLogMessage(className, "start", "Documentation available at: " + "http://localhost:" + Integer.toString(p) + "/apidocs/");
startFuture.complete();
}
});
}
});
}
use of io.vertx.core.http.HttpServer in project vertx-micrometer-metrics by vert-x3.
the class VertxHttpClientServerMetricsTest method setUp.
@Before
public void setUp(TestContext ctx) {
vertx = Vertx.vertx(new VertxOptions().setMetricsOptions(new MicrometerMetricsOptions().setPrometheusOptions(new VertxPrometheusOptions().setEnabled(true)).setRegistryName(registryName).setEnabled(true))).exceptionHandler(ctx.exceptionHandler());
// Setup server
Async serverReady = ctx.async();
vertx.deployVerticle(new AbstractVerticle() {
@Override
public void start(Future<Void> future) throws Exception {
httpServer = vertx.createHttpServer();
httpServer.websocketHandler(ws -> ws.handler(event -> {
vertx.setTimer(REQ_DELAY, timer -> ws.writeTextMessage(SERVER_RESPONSE).end());
})).requestHandler(req -> {
// Timer as artificial processing time
vertx.setTimer(REQ_DELAY, handler -> req.response().setChunked(true).putHeader("Content-Type", "text/plain").write(SERVER_RESPONSE).end());
}).listen(9195, "127.0.0.1", r -> {
if (r.failed()) {
ctx.fail(r.cause());
} else {
serverReady.complete();
}
});
}
});
serverReady.awaitSuccess();
}
Aggregations