Search in sources :

Example 1 with PojoEventBusCodec

use of org.folio.rest.tools.codecs.PojoEventBusCodec 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();
                }
            });
        }
    });
}
Also used : Pattern(java.util.regex.Pattern) HttpServerOptions(io.vertx.core.http.HttpServerOptions) Router(io.vertx.ext.web.Router) UnrecognizedPropertyException(com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) PojoEventBusCodec(org.folio.rest.tools.codecs.PojoEventBusCodec) BodyHandler(io.vertx.ext.web.handler.BodyHandler) HttpServer(io.vertx.core.http.HttpServer) Future(io.vertx.core.Future)

Aggregations

UnrecognizedPropertyException (com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException)1 Future (io.vertx.core.Future)1 HttpServer (io.vertx.core.http.HttpServer)1 HttpServerOptions (io.vertx.core.http.HttpServerOptions)1 Router (io.vertx.ext.web.Router)1 BodyHandler (io.vertx.ext.web.handler.BodyHandler)1 IOException (java.io.IOException)1 Pattern (java.util.regex.Pattern)1 MessagingException (javax.mail.MessagingException)1 PojoEventBusCodec (org.folio.rest.tools.codecs.PojoEventBusCodec)1