<commit_before>/**
 * Created by carribus on 03/12/15.
 */

var Router = require('vertx-web-js/router'),
    BodyHandler = require("vertx-web-js/body_handler"),
    bus = vertx.eventBus(),
    server = vertx.createHttpServer(),
    router = Router.router(vertx)
var logger = Java.type("io.vertx.core.logging.LoggerFactory").getLogger('OdoboX:RestAPI');

module.exports = function() {
    var o = {};
    var BUS_ADDRESSES = [
        {
            address: "restapi.register",
            handler: _registerRESTEndpoint
        },
        {
            address: "restapi.unregister",
            handler: _unregisterRESTEndpoint
        },
        {
            address: "restapi.status",
            handler: _restStatus
        }
    ];

    var paths = {
        endpoints: {}
    };

    var status = 'stopped';

    /**
     * Registers the RestAPI eventbus addresses and starts listening on the configured interfaces and ports
     *
     * Expected Config Structure:
     *
     * {
     *  host: String,
     *  port: Number
     * }
     *
     * @param config
     */
    o.start = function(config, cb) {
        if ( 'stopped' == status ) {
            // enable body handling on all routes
            router.route().handler(BodyHandler.create().handle);

            server.requestHandler(router.accept).listen(config.port, config.host, function(res, err) {
                if ( !err ) {
                    logger.info('REST API available on: ' + config.host + ':' + config.port)

                    // register the event bus addresses
                    BUS_ADDRESSES.forEach(function (e) {
                        logger.info('[RESTAPI] Registering address: ' + e.address);
                        e.consumer = bus.consumer(e.address);
                        e.consumer
                            .handler(e.handler)
                            .completionHandler(function (res, err) {
                                if (err) {
                                    logger.info('[RESTAPI] ' + e.address + ' registration failed across the cluster!');
                                }
                            });
                    });

                    // register the utility endpoint(s)
                    _registerUtilityEndpoints();

                    status = 'started';
                    cb(true);
                    //startFuture.complete();
                } else {
                    //startFuture.fail();
                    cb(false);
                }
            });
        }
    };

    /**
     * Stops listening on the interfaces/ports
     * @param cb
     */
    o.stop = function(cb) {
        // TODO: Write the cleanup logic here
        if ( 'started' == status ) {
            status = 'stopped';
            cb(true);
        } else {
            cb(false);
        }
    };

    /**
     *
     * @param message
     * @private
     */
    function _registerRESTEndpoint(message) {
        var body = message.body();

        if ( _validateMessage(body) ) {
            logger.info('[RESTAPI] Registering [' + body.method + ']' + '/' + body.resource + '/' + body.endpoint);
            var route = router.route(body.method, '/' + body.resource + '/' + body.endpoint);

            if ( body.method != 'GET' && body.expects ) {
                route.consumes(body.expects);
            }
            if ( body.produces ) {
                route.produces(body.produces);
            }

            route
                .handler(function(routingContext) {
                    var response = routingContext.response();
                    var request = routingContext.request();
                    var bodyData;
                    var headers = request.headers().names();

                    if ( body.expects ) {
                        bodyData = body.expects == 'application/json'
                            ? routingContext.getBodyAsJson()
                            : routingContext.getBody()
                    }

                    response.setChunked(true);
                    if ( body.produces ) {
                        response.putHeader('content-type', routingContext.getAcceptableContentType());
                    }<commit_msg>Fixed bug with body conversion in restapi.<commit_after>/**
 * Created by carribus on 03/12/15.
 */

var Router = require('vertx-web-js/router'),
    BodyHandler = require("vertx-web-js/body_handler"),
    bus = vertx.eventBus(),
    server = vertx.createHttpServer(),
    router = Router.router(vertx)
var logger = Java.type("io.vertx.core.logging.LoggerFactory").getLogger('OdoboX:RestAPI');

module.exports = function() {
    var o = {};
    var BUS_ADDRESSES = [
        {
            address: "restapi.register",
            handler: _registerRESTEndpoint
        },
        {
            address: "restapi.unregister",
            handler: _unregisterRESTEndpoint
        },
        {
            address: "restapi.status",
            handler: _restStatus
        }
    ];

    var paths = {
        endpoints: {}
    };

    var status = 'stopped';

    /**
     * Registers the RestAPI eventbus addresses and starts listening on the configured interfaces and ports
     *
     * Expected Config Structure:
     *
     * {
     *  host: String,
     *  port: Number
     * }
     *
     * @param config
     */
    o.start = function(config, cb) {
        if ( 'stopped' == status ) {
            // enable body handling on all routes
            router.route().handler(BodyHandler.create().handle);

            server.requestHandler(router.accept).listen(config.port, config.host, function(res, err) {
                if ( !err ) {
                    logger.info('REST API available on: ' + config.host + ':' + config.port)

                    // register the event bus addresses
                    BUS_ADDRESSES.forEach(function (e) {
                        logger.info('[RESTAPI] Registering address: ' + e.address);
                        e.consumer = bus.consumer(e.address);
                        e.consumer
                            .handler(e.handler)
                            .completionHandler(function (res, err) {
                                if (err) {
                                    logger.info('[RESTAPI] ' + e.address + ' registration failed across the cluster!');
                                }
                            });
                    });

                    // register the utility endpoint(s)
                    _registerUtilityEndpoints();

                    status = 'started';
                    cb(true);
                    //startFuture.complete();
                } else {
                    //startFuture.fail();
                    cb(false);
                }
            });
        }
    };

    /**
     * Stops listening on the interfaces/ports
     * @param cb
     */
    o.stop = function(cb) {
        // TODO: Write the cleanup logic here
        if ( 'started' == status ) {
            status = 'stopped';
            cb(true);
        } else {
            cb(false);
        }
    };

    /**
     *
     * @param message
     * @private
     */
    function _registerRESTEndpoint(message) {
        var body = message.body();

        if ( _validateMessage(body) ) {
            logger.info('[RESTAPI] Registering [' + body.method + ']' + '/' + body.resource + '/' + body.endpoint);
            var route = router.route(body.method, '/' + body.resource + '/' + body.endpoint);

            if ( body.method != 'GET' && body.expects ) {
                route.consumes(body.expects);
            }
            if ( body.produces ) {
                route.produces(body.produces);
            }

            route
                .handler(function(routingContext) {
                    var response = routingContext.response();
                    var request = routingContext.request();
                    var bodyData;
                    var headers = request.headers().names();

                    try {
                        if ( body.expects ) {
                            bodyData = body.expects == 'application/json'
                                ? routingContext.getBodyAsJson()
                                : routingContext.getBody()
                        }
                    } catch (e) {
                        logger.warn('[RESTAPI] Failed to convert received body');
                        response.setStatusCode(400).setStatusMessage("Bad Request");
                        response.end();
                        return;
                    }

                    response.setChunked(true);
                    if ( body.produces ) {
                        response.putHeader('content-type', routingContext.getAcceptableContentType());
                    }
{'fraction_non_alphanumeric': 0.11413290851160673, 'fraction_numerical': 0.0017068730086481567, 'mean_word_length': 1.243809037528721, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3126939', 'n_tokens_mistral': 2296, 'n_tokens_neox': 2127, 'n_words': 433}