Example usage for io.vertx.core.json JsonObject getString

List of usage examples for io.vertx.core.json JsonObject getString

Introduction

In this page you can find the example usage for io.vertx.core.json JsonObject getString.

Prototype

public String getString(String key, String def) 

Source Link

Document

Like #getString(String) but specifying a default value to return if there is no entry.

Usage

From source file:io.nitor.api.backend.msgraph.GraphQueryHandler.java

License:Apache License

public GraphQueryHandler(JsonObject conf, int routeLength, JsonObject adAuth,
        CookieSessionHandler sessionHandler, HttpClient httpClient) {
    this.routeLength = routeLength;
    this.sessionHandler = sessionHandler;
    this.httpClient = httpClient;
    String target = conf.getString("target", "https://graph.microsoft.com/beta");
    if (target.endsWith("/"))
        target = target.substring(0, target.length() - 1);
    this.baseUrl = target;
    this.tokenCache = new GraphSessionTokenService(httpClient, adAuth);
    if (!adAuth.getString("scope").contains("offline_access")) {
        throw new IllegalArgumentException("auth scope must contain \"offline_access\"");
    }//from  ww w  .  ja  v  a2  s  .  c  om
}

From source file:io.nitor.api.backend.NitorBackend.java

License:Apache License

private void setupServices(JsonObject configRoot, HttpServerOptions httpServerOptions, Router router,
        ServiceRouterBuilder routeBuilder, HttpClient httpClient, CookieSessionHandler sessionHandler,
        JsonObject adAuth, boolean isOrigReqHttps) {
    JsonArray services = configRoot.getJsonArray("services", new JsonArray());
    services.forEach(s -> {/*from w  w w  . jav a  2s .c  om*/
        JsonObject service = (JsonObject) s;
        String type = service.getString("type", "<missing>");
        String logMsg = "Setting up service '" + type + "' on route '" + service.getString("route") + "'";
        switch (type) {
        case "proxy":
            setupProxy(service, routeBuilder, httpServerOptions, isOrigReqHttps);
            break;
        case "static":
            setupStaticFiles(service, routeBuilder);
            break;
        case "s3":
            setupS3(service, routeBuilder);
            break;
        case "lambda":
            setupLambda(service, routeBuilder);
            break;
        case "graph":
            setupGraph(service, routeBuilder, adAuth, sessionHandler, httpClient);
            break;
        case "virtualHost":
            String virtualHost = service.getString("host");
            logMsg += " for virtual host '" + virtualHost + "'";
            setupServices(service, httpServerOptions, null, routeBuilder.virtualHostHandler(virtualHost),
                    httpClient, sessionHandler, adAuth, isOrigReqHttps);
            break;
        case "cache":
            setupCache(service, routeBuilder);
            break;
        default: {
            RuntimeException ex = new RuntimeException("No support for service '" + type + "'");
            logger.fatal("service config failure", ex);
            throw ex;
        }
        }
        logger.info(logMsg);
    });
    if (router != null) {
        routeBuilder.registerHandlers(router);
    }
}

From source file:io.nitor.api.backend.proxy.SetupProxy.java

License:Apache License

public static void setupProxy(Vertx vertx, ServiceRouterBuilder routerBuilder, JsonObject proxyConf,
        HttpServerOptions serverOptions, boolean isOrigReqHttps) {
    boolean ssl = proxyConf.getBoolean("ssl", false);

    HttpClient client = vertx.createHttpClient(new HttpClientOptions()
            .setConnectTimeout((int) SECONDS.toMillis(proxyConf.getInteger("connectTimeout", 10)))
            .setIdleTimeout((int) SECONDS.toSeconds(proxyConf.getInteger("idleTimeout", 15)))
            .setMaxPoolSize(proxyConf.getInteger("maxPoolSize", 30))
            .setPipelining(proxyConf.getInteger("pipelineDepth", 0) > 1)
            .setPipeliningLimit(proxyConf.getInteger("pipelineDepth", 1)).setMaxWaitQueueSize(100)
            .setUsePooledBuffers(true).setProtocolVersion(HTTP_1_1).setTryUseCompression(false).setSsl(ssl));

    String prefix = proxyConf.getString("path", "");
    if (prefix.endsWith("/")) {
        prefix = prefix.substring(0, prefix.length() - 1);
    }/*ww w  .  j a va  2s.com*/
    String route = proxyConf.getString("route", "");
    if (route.endsWith("*")) {
        route = route.substring(0, route.length() - 1);
    }
    if (route.endsWith("/")) {
        route = route.substring(0, route.length() - 1);
    }

    final String proxyRoute = route;
    final Proxy.Target proxyTarget = new Proxy.Target(proxyConf.getString("host"), proxyConf.getInteger("port"),
            prefix, proxyConf.getString("hostHeader"));
    logger.info("Proxying {} to {}://{}:{}/{}", route, ssl ? "https" : "http", proxyTarget.socketHost,
            proxyTarget.socketPort, proxyTarget.uri);

    Proxy proxy = new Proxy(client, (routingContext, targetHandler) -> {
        String suffix = routingContext.request().uri().substring(proxyRoute.length());
        targetHandler.handle(proxyTarget.withSuffix(suffix));
    }, serverOptions.getIdleTimeout(), proxyConf.getInteger("clientReceiveTimeout", 300), isOrigReqHttps,
            SimpleLogProxyTracer::new, new DefaultPumpStarter());

    if (proxyConf.getJsonObject("addHeaders") != null) {
        final Map<String, String> addHeaders = new HashMap<>();
        for (Map.Entry<String, Object> entry : proxyConf.getJsonObject("addHeaders")) {
            addHeaders.put(entry.getKey(), entry.getValue().toString());
        }
        proxy.addHeaders(addHeaders);
    }

    routerBuilder.route(proxyConf.getString("route"), proxy::handle, routingContext -> {
        if (routingContext.failed()) {
            Throwable error = routingContext.failure();
            logger.warn("General failure handler", error);
            String statusMsg = "";
            int statusCode = BAD_GATEWAY.code();
            if (error instanceof ProxyException) {
                ProxyException ex = (ProxyException) error;
                statusCode = ex.statusCode;
                if (ex.getCause() != null) {
                    statusMsg = ex.getCause().getMessage();
                } else if (ex.reason == RejectReason.noHostHeader) {
                    statusMsg = "Exhausted resources while trying to extract Host header from the request";
                }
            }
            if (!routingContext.response().headWritten() && !routingContext.response().ended()) {
                routingContext.response().setStatusCode(statusCode);
                routingContext.response().headers().set("content-type", "text/plain;charset=UTF-8");
                routingContext.response().end(statusMsg);
            }
        } else {
            routingContext.next();
        }
    });
}

From source file:io.nitor.api.backend.s3.S3Handler.java

License:Apache License

public S3Handler(Vertx vertx, JsonObject conf, int routeLength) {
    this.routeLength = routeLength;

    indexFile = conf.getString("indexFile", "index.html");

    String staticPathConfig = conf.getString("staticPaths");
    staticPaths = staticPathConfig != null ? Pattern.compile(staticPathConfig) : null;

    String region = resolveRegion(conf).toString();
    this.s3Host = ("us-east-1".equals(region) ? "s3" : "s3-" + region) + ".amazonaws.com";

    String bucket = conf.getString("bucket");
    String basePath = '/' + bucket + '/' + conf.getString("path", "");
    basePathComponents = PathComponent.splitPath(basePath);

    AwsCredentialsProvider secretsProvider = resolveCredentialsProvider(conf);
    signer = new AWSRequestSigner(region, s3Host, secretsProvider);

    JsonArray operations = conf.getJsonArray("operations", new JsonArray().add("GET"));
    operations.forEach(op -> allowedMethods.add(HttpMethod.valueOf(op.toString())));

    http = vertx.createHttpClient(new HttpClientOptions()
            .setConnectTimeout((int) SECONDS.toMillis(conf.getInteger("connectTimeout", 5)))
            .setIdleTimeout((int) SECONDS.toSeconds(conf.getInteger("idleTimeout", 60)))
            .setMaxPoolSize(conf.getInteger("maxPoolSize", 100)).setPipelining(false).setMaxWaitQueueSize(100)
            .setUsePooledBuffers(true).setProtocolVersion(HTTP_1_1).setMaxRedirects(5)
            .setTryUseCompression(false));
}

From source file:io.nitor.api.backend.session.CookieConverter.java

License:Apache License

public CookieConverter(JsonObject sessionConf, int maxAge) {
    this.cookieName = sessionConf.getString("cookieName", "__Host-auth");
    this.encryptor = new Encryptor(sessionConf);
    this.maxAge = maxAge;
    this.maxCacheSize = sessionConf.getInteger("maxCookieCacheSize", 10_000);
}

From source file:io.nitor.api.backend.session.Encryptor.java

License:Apache License

public Encryptor(JsonObject cryptConf) {
    try {//from   w w  w.j av a  2 s.  com
        Path secretFile = Paths.get(cryptConf.getString("secretFile", ".secret"));
        JsonArray secretGenerator = cryptConf.getJsonArray("secretGenerator");
        byte[] secret;
        if (isReadable(secretFile)) {
            logger.info("Reading existing secret from " + secretFile);
            secret = readAllBytes(secretFile);
            if (secret.length != AES_KEY_LENGTH + AES_AUTH_LENGTH) {
                throw new RuntimeException("Corrupted secret file '" + secretFile.toAbsolutePath() + "'");
            }
        } else if (secretGenerator != null) {
            logger.info("Generating a new secret using " + secretGenerator);
            secret = generateSecret(secretGenerator);
            if (secret.length < AES_KEY_LENGTH + AES_AUTH_LENGTH) {
                throw new RuntimeException("Too small secret generated");
            }
        } else {
            logger.info("Generating a new secret and writing it to " + secretFile);
            secret = new byte[AES_KEY_LENGTH + AES_AUTH_LENGTH];
            CRYPTO_POOL.get().random.nextBytes(secret);
            write(secretFile, secret, CREATE, TRUNCATE_EXISTING, DSYNC);
        }
        logger.info("Using secret " + toHexString(Arrays.hashCode(secret)));
        byte[] aesKey = copyOf(secret, AES_KEY_LENGTH);
        byte[] aesAuthData = copyOfRange(secret, AES_KEY_LENGTH, AES_KEY_LENGTH + AES_AUTH_LENGTH);
        if (aesKey.length != AES_KEY_LENGTH || aesAuthData.length != AES_AUTH_LENGTH) {
            throw new RuntimeException("Wrong length of key or auth data");
        }
        this.symmetricKey = new SecretKeySpec(aesKey, "AES");
        this.hmacSecret = new SecretKeySpec(aesAuthData, MAC_ALGORITHM);
    } catch (Exception e) {
        throw new RuntimeException("Could not create cipher", e);
    }
}

From source file:io.nonobot.core.BotOptions.java

License:Apache License

public BotOptions(JsonObject json) {
    name = json.getString("name", DEFAULT_NAME);
    httpServerOptions = json.getJsonObject("httpServerOptions") != null
            ? new HttpServerOptions(json.getJsonObject("httpServerOptions"))
            : null;//from   w  w  w. j  a va2 s .  co m
}

From source file:io.sqp.proxy.ServerVerticle.java

License:Open Source License

@Override
public void start() {
    // TODO: set subprotocols

    JsonObject config = config();

    String path = config.getString("path", DEFAULT_PATH);
    int port = config.getInteger("port", DEFAULT_PORT);
    int poolSize = config.getInteger("connectionPoolSize", DEFAULT_POOL_SIZE);
    JsonArray backendConfs = config.getJsonArray("backends");
    _executorService = Executors.newFixedThreadPool(10); // TODO: set this reasonably

    // Initialize the backend connection pool
    BackendConnectionPool connectionPool = new VertxBackendConnectionPool(vertx, poolSize, backendConfs);

    try {/*from   w  ww.ja v  a 2 s  .  c  o  m*/
        connectionPool.init();
    } catch (ServerErrorException e) {
        _logger.log(Level.SEVERE, "Failed to create the connection pool", e);
        throw new RuntimeException(e.getMessage(), e.getCause());
    }

    HttpServerOptions options = new HttpServerOptions();
    int maxFrameSize = options.getMaxWebsocketFrameSize();

    // Create the actual server
    HttpServer server = vertx.createHttpServer(options);

    // For each incoming websocket connection: create a client connection object
    server.websocketHandler(socket -> {
        if (!socket.path().equals(path)) {
            socket.reject();
            return;
        }
        // TODO: check sub protocols
        new VertxClientConnection(_executorService, socket, connectionPool, maxFrameSize);
    });
    // start to listen
    server.listen(port, result -> {
        if (result.succeeded()) {
            _logger.log(Level.INFO, "Listening on port " + port + " and path '" + path + "'...");
            setStarted(true);
        } else {
            _logger.log(Level.SEVERE, "Failed to listen", result.cause());
            setStartingError(result.cause());
        }
    });
}

From source file:microservicerx.rx.DistributedObservable.java

public DistributedObservable(JsonObject that) {
    this(that.getString("address", null));
}

From source file:net.kuujo.vertigo.network.impl.ComponentConfigImpl.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public void update(JsonObject component) {
    if (this.name == null) {
        this.name = component.getString(COMPONENT_NAME, UUID.randomUUID().toString());
    }//from w  w  w. j  a v a2 s .c om
    if (this.identifier == null) {
        this.identifier = component.getString(COMPONENT_IDENTIFIER);
        if (this.identifier == null) {
            throw new NetworkFormatException("Component " + this.name + " did not specify an identifier.");
        }
    }
    if (component.containsKey(COMPONENT_CONFIG)) {
        this.config = component.getJsonObject(COMPONENT_CONFIG);
    }
    if (component.containsKey(COMPONENT_WORKER)) {
        this.worker = component.getBoolean(COMPONENT_WORKER);
    }
    if (component.containsKey(COMPONENT_MULTI_THREADED)) {
        this.multiThreaded = component.getBoolean(COMPONENT_MULTI_THREADED);
    }
    if (component.containsKey(COMPONENT_STATEFUL)) {
        this.stateful = component.getBoolean(COMPONENT_STATEFUL);
    }
    if (component.containsKey(COMPONENT_REPLICAS)) {
        this.replicas = component.getInteger(COMPONENT_REPLICAS, 1);
    }
    if (component.containsKey(COMPONENT_RESOURCES)) {
        this.resources.addAll(component.getJsonArray(COMPONENT_RESOURCES, new JsonArray()).getList());
    }
    JsonObject inputs = component.getJsonObject(COMPONENT_INPUT);
    if (inputs == null) {
        inputs = new JsonObject();
    }
    if (this.input == null) {
        this.input = new InputConfigImpl(inputs).setComponent(this);
    } else {
        this.input.update(inputs);
    }
    JsonObject outputs = component.getJsonObject(COMPONENT_OUTPUT);
    if (outputs == null) {
        outputs = new JsonObject();
    }
    if (this.output == null) {
        this.output = new OutputConfigImpl(outputs).setComponent(this);
    } else {
        this.output.update(outputs);
    }
}