List of usage examples for io.vertx.core.json JsonObject getJsonObject
public JsonObject getJsonObject(String key)
From source file:io.nitor.api.backend.msgraph.GraphSessionTokenService.java
License:Apache License
public GraphSessionTokenService(HttpClient httpClient, JsonObject adConfig) { this.tokenUrl = adConfig.getJsonObject("openIdConfig").getString("token_endpoint"); this.baseForm = "client_id=" + urlEncode(adConfig.getString("clientId")) + "&scope=" + urlEncode(adConfig.getString("scope")) + "&grant_type=refresh_token" + "&client_secret=" + urlEncode(adConfig.getString("clientSecret")) + "&redirect_uri=" + urlEncode(adConfig.getString("redirectUri")); this.httpClient = httpClient; }
From source file:io.nitor.api.backend.NitorBackend.java
License:Apache License
@Override public void start() { vertx.exceptionHandler(e -> logger.error("Fallback exception handler got", e)); HttpServerOptions httpServerOptions = SetupHttpServerOptions.createHttpServerOptions(config()); Router router = Router.router(vertx); HttpClientOptions clientOptions = new HttpClientOptions(); clientOptions.setConnectTimeout((int) SECONDS.toMillis(5)); clientOptions.setIdleTimeout((int) SECONDS.toMillis(15)); clientOptions.setSsl(true);//from w w w . jav a 2 s .c om HttpClient httpClient = vertx.createHttpClient(clientOptions); Map<String, String> injectedResponseHeaders = new HashMap<>(); for (Entry<String, Object> defaultHeader : config().getJsonObject("defaultHeaders")) { injectedResponseHeaders.put(defaultHeader.getKey().toLowerCase(), defaultHeader.getValue().toString()); } String publicURI = config().getString("publicURI", "http" + (httpServerOptions.isSsl() ? "s" : "") + "://localhost:" + listenPort); if (publicURI.endsWith("/")) { publicURI = publicURI.substring(0, publicURI.length() - 1); } publicURI = publicURI.toLowerCase(ROOT); boolean isOrigReqHttps = httpServerOptions.isSsl() || publicURI.startsWith("https:"); boolean trustPreviousProxy = config().getBoolean("trustPreviousProxy", publicURI.startsWith("https:") && !httpServerOptions.isSsl()); router.route().handler(new AccessLogHandler()::handle); router.route().handler(routingContext -> { HttpServerResponse resp = routingContext.response(); if (isOrigReqHttps) { resp.putHeader("strict-transport-security", "max-age=31536000; includeSubDomains"); } if (trustPreviousProxy) { String origHost = parseForwardedHeaders(routingContext.request().headers()); if (origHost != null) { routingContext.put(REMOTE_ADDRESS, origHost); } } if (!injectedResponseHeaders.isEmpty()) { routingContext.addHeadersEndHandler(v -> { for (Entry<String, String> header : injectedResponseHeaders.entrySet()) { if (!resp.headers().contains(header.getKey())) { resp.putHeader(header.getKey(), header.getValue()); } } }); } routingContext.next(); }); router.get("/healthCheck").handler(routingContext -> routingContext.response().setStatusCode(200).end()); router.get("/certCheck").handler(routingContext -> { String resp; try { resp = "Certs: " + Arrays.toString(routingContext.request().peerCertificateChain()); } catch (SSLPeerUnverifiedException e) { resp = "No client certs available:" + e.getMessage(); } routingContext.response().setChunked(true).putHeader(CONTENT_TYPE, "text/plain; charset=utf-8") .write(resp).end(); }); JsonObject clientAuth = config().getJsonObject("clientAuth"); if (clientAuth != null) { if (null != clientAuth.getString("clientChain")) { router.route(clientAuth.getString("route", "/*")).handler(routingContext -> { try { routingContext.request().peerCertificateChain(); routingContext.next(); } catch (SSLPeerUnverifiedException e) { routingContext.response().setStatusCode(FORBIDDEN.code()); routingContext.response().end(); logger.info("Rejected request that was missing valid client certificate from ip {}: {}", routingContext.request().remoteAddress(), e.getMessage()); } }); } } boolean virtualHost = config().getBoolean("virtualHost", false); if (virtualHost) { router.route().handler(ctx -> { ctx.put("host", getUriHostName(ctx.request().host())); ctx.next(); }); } JsonObject sessionConf = config().getJsonObject("session"); CookieSessionHandler sessionHandler = sessionConf != null ? new CookieSessionHandler(sessionConf) : null; if (sessionHandler != null) { router.route().handler(CookieHandler.create()); router.get("/proxyLogout").handler(routingContext -> { routingContext.cookies() .forEach(cookie -> secureCookie(cookie, (int) DAYS.toSeconds(30)).setValue("")); routingContext.response().putHeader(CACHE_CONTROL, "no-cache, no-store, must-revalidate") .putHeader(EXPIRES, "0").putHeader(CONTENT_TYPE, "text/plain; charset=utf-8") .end("Logged out", "UTF-8"); }); } JsonObject adAuth = config().getJsonObject("adAuth"); if (adAuth != null) { JsonObject openIdConfig = adAuth.getJsonObject("openIdConfig"); if (openIdConfig == null || !openIdConfig.containsKey("authorization_endpoint") || !openIdConfig.containsKey("token_endpoint")) { String configURI = adAuth.getString("configurationURI"); try { logger.info("Fetching configuration from " + configURI); URL url = URI.create(configURI).toURL(); openIdConfig = new JsonObject(buffer(toBytes(url.openStream()))); } catch (Exception e) { RuntimeException ex = new RuntimeException("Failed to fetch open id config from " + configURI, e); logger.fatal("adAuth config failure", ex); throw ex; } logger.info( "To speed up startup please define \"adAuth\": {\"openIdConfig\": {\"authorization_endpoint\": \"" + openIdConfig.getString("authorization_endpoint") + "\", \"token_endpoint\": \"" + openIdConfig.getString("token_endpoint") + "\" } }"); } adAuth.put("openIdConfig", openIdConfig); SetupAzureAdConnectAuth.setupAzureAd(adAuth, router, publicURI, virtualHost, sessionHandler, httpClient); } JsonObject basicAuth = config().getJsonObject("basicAuth"); if (basicAuth != null) { AuthHandler basicAuthHandler = BasicAuthHandler.create( new SimpleConfigAuthProvider(basicAuth.getJsonObject("users")), basicAuth.getString("realm", "nitor")); router.route(basicAuth.getString("route", "/*")).handler(basicAuthHandler); } if (sessionHandler != null) { router.get("/cookieCheck").handler(routingContext -> { Map<String, String> headers = sessionHandler.getSessionData(routingContext); StringBuilder sb = new StringBuilder(2048); if (headers == null) { sb.append("No valid session"); } else { headers.forEach((key, value) -> { sb.append(key).append('='); if (key.startsWith(SECRET_DATA_PREFIX)) sb.append("<secret>"); else sb.append(value); sb.append('\n'); }); } routingContext.response().putHeader(CONTENT_TYPE, "text/plain; charset=utf-8").end(sb.toString()); }); } JsonArray customizeConf = config().getJsonArray("customize"); if (customizeConf != null) { customizeConf.forEach(c -> { JsonObject conf = (JsonObject) c; InlineJS inlineJs = new InlineJS(vertx, conf.getString("jsFile", "custom.js")); router.route(conf.getString("route")).handler(ctx -> { inlineJs.call("handleRequest", ctx.request(), ctx); ctx.addHeadersEndHandler((v) -> inlineJs.call("handleResponse", ctx.response(), ctx)); ctx.next(); }); }); } setupServices(config(), httpServerOptions, router, new ServiceRouterBuilder(), httpClient, sessionHandler, adAuth, isOrigReqHttps); router.route().failureHandler(routingContext -> { String error = "ERROR"; int statusCode = routingContext.statusCode(); Throwable t = routingContext.failure(); logger.info("Handling failure statusCode=" + statusCode, t); HttpServerResponse resp = routingContext.response(); if (resp.ended()) { return; } if (resp.headWritten()) { resp.end(); routingContext.request().connection().close(); return; } if (t != null) { if (t instanceof ProxyException) { statusCode = ((ProxyException) t).statusCode; } error = "ERROR: " + t.toString(); } resp.setStatusCode(statusCode != -1 ? statusCode : INTERNAL_SERVER_ERROR.code()); resp.headers().set("Content-Type", "text/plain; charset=UTF-8"); resp.headers().set("Content-Length", Integer.toString(error.length())); resp.end(error); }); vertx.createHttpServer(httpServerOptions).requestHandler(router).listen(listenPort, listenHost); }
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 v a2 s . c om*/ 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.tls.SetupHttpServerOptions.java
License:Apache License
public static HttpServerOptions createHttpServerOptions(JsonObject config) { JsonObject tls = config.getJsonObject("tls"); HttpServerOptions httpOptions = new HttpServerOptions() // basic TCP/HTTP options .setReuseAddress(true).setCompressionSupported(false) // otherwise it automatically compresses based on response headers even if pre-compressed with e.g. proxy .setUsePooledBuffers(true).setCompressionLevel(2) .setIdleTimeout(config.getInteger("idleTimeout", (int) MINUTES.toSeconds(10))); if (!config.getBoolean("http2", true)) { httpOptions.setAlpnVersions(asList(HTTP_1_1)); }//from w w w . j a va2s. c om if (tls != null) { httpOptions.setSsl(true) // server side certificate .setPemKeyCertOptions(new PemKeyCertOptions().setKeyPath(tls.getString("serverKey")) .setCertPath(tls.getString("serverCert"))) // TLS tuning .addEnabledSecureTransportProtocol("TLSv1.2").addEnabledSecureTransportProtocol("TLSv1.3"); JsonObject clientAuth = config.getJsonObject("clientAuth"); if (httpOptions.isSsl() && clientAuth != null && clientAuth.getString("clientChain") != null) { // client side certificate httpOptions.setClientAuth(REQUEST) .setTrustOptions(new PemTrustOptions().addCertPath(clientAuth.getString("clientChain"))); } if (TRUE.equals(config.getBoolean("useNativeOpenSsl"))) { httpOptions.setUseAlpn(true).setSslEngineOptions(new OpenSSLEngineOptions()); cipherSuites.stream().map(SetupHttpServerOptions::javaCipherNameToOpenSSLName) .forEach(httpOptions::addEnabledCipherSuite); } else { httpOptions.setUseAlpn(DynamicAgent.enableJettyAlpn()) .setJdkSslEngineOptions(new JdkSSLEngineOptions()); cipherSuites.forEach(httpOptions::addEnabledCipherSuite); } } return httpOptions; }
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 av a 2 s . c om*/ }
From source file:io.nonobot.core.handlers.GiphyHandler.java
License:Apache License
public void handle(Message msg) { String query = msg.matchedGroup(1); HttpClientRequest req = client.get(80, "api.giphy.com", "/v1/gifs/search?q=" + query + "&api_key=" + "dc6zaTOxFJmzC", resp -> { if (resp.statusCode() == 200 && resp.getHeader("Content-Type").equals("application/json")) { System.out.println(resp.statusCode()); System.out.println(resp.statusMessage()); System.out.println(resp.getHeader("Content-Type")); resp.exceptionHandler(err -> { msg.reply("Error: " + err.getMessage()); });/*from w w w . j a v a2 s.co m*/ Buffer buf = Buffer.buffer(); resp.handler(buf::appendBuffer); resp.endHandler(v -> { JsonObject json = new JsonObject(buf.toString()); JsonArray images = json.getJsonArray("data"); if (images.size() > 0) { JsonObject image = images.getJsonObject(0); // Should be random !!! String url = image.getJsonObject("images").getJsonObject("original") .getString("url"); msg.reply(url); } msg.reply("got response " + json); }); } else { msg.reply("Error"); } }); req.exceptionHandler(err -> { msg.reply("Error: " + err.getMessage()); }); req.end(); }
From source file:io.nonobot.core.handlers.GitHubVerticle.java
License:Apache License
@Override public void start() throws Exception { super.start(); Router router = Router.router(vertx); bot.webRouter().mountSubRouter("/github", router); router.post().handler(ctx -> {//from w ww.j a v a 2 s . c o m HttpServerRequest req = ctx.request(); String event = req.getHeader("X-Github-Event"); if (!"push".equals(event)) { req.response().setStatusCode(400).end("X-Github-Event " + event + " not handled"); return; } String contentType = req.getHeader("Content-Type"); if (!"application/json".equals(contentType)) { req.response().setStatusCode(400).end("Content-Type " + contentType + " not handled"); return; } req.bodyHandler(body -> { JsonObject json = body.toJsonObject(); req.response().end(); String chatId = req.getParam("chat"); JsonArray commits = json.getJsonArray("commits"); if (chatId != null && commits != null && commits.size() > 0) { String commitWord = commits.size() > 1 ? "commits" : "commit"; bot.chatRouter().sendMessage(new SendOptions().setChatId(chatId), "Got " + commits.size() + " new " + commitWord + " from " + json.getJsonObject("pusher").getString("name") + " on " + json.getJsonObject("repository").getString("full_name")); for (int index = 0; index < commits.size(); index++) { JsonObject commit = commits.getJsonObject(index); bot.chatRouter().sendMessage(new SendOptions().setChatId(chatId), " * " + commit.getString("message") + " " + commit.getString("url")); } } }); }); }
From source file:io.rhiot.kafka.bridge.JsonMessageConverter.java
License:Apache License
@Override public Message toAmqpMessage(String amqpAddress, ConsumerRecord<String, byte[]> record) { Message message = Proton.message();// w ww . j a v a2 s. c om message.setAddress(amqpAddress); // get the root JSON JsonObject json = new JsonObject(new String(record.value())); // get AMQP properties from the JSON JsonObject jsonProperties = json.getJsonObject(JsonMessageConverter.PROPERTIES); if (jsonProperties != null) { for (Entry<String, Object> entry : jsonProperties) { if (entry.getValue() != null) { if (entry.getKey().equals(JsonMessageConverter.MESSAGE_ID)) { message.setMessageId(entry.getValue()); } else if (entry.getKey().equals(JsonMessageConverter.TO)) { message.setAddress(entry.getValue().toString()); } else if (entry.getKey().equals(JsonMessageConverter.SUBJECT)) { message.setSubject(entry.getValue().toString()); } else if (entry.getKey().equals(JsonMessageConverter.REPLY_TO)) { message.setReplyTo(entry.getValue().toString()); } else if (entry.getKey().equals(JsonMessageConverter.CORRELATION_ID)) { message.setCorrelationId(entry.getValue()); } } } } // get AMQP application properties from the JSON JsonObject jsonApplicationProperties = json.getJsonObject(JsonMessageConverter.APPLICATION_PROPERTIES); if (jsonApplicationProperties != null) { Map<Symbol, Object> applicationPropertiesMap = new HashMap<>(); for (Entry<String, Object> entry : jsonApplicationProperties) { applicationPropertiesMap.put(Symbol.valueOf(entry.getKey()), entry.getValue()); } ApplicationProperties applicationProperties = new ApplicationProperties(applicationPropertiesMap); message.setApplicationProperties(applicationProperties); } // put message annotations about partition, offset and key (if not null) Map<Symbol, Object> messageAnnotationsMap = new HashMap<>(); messageAnnotationsMap.put(Symbol.valueOf(Bridge.AMQP_PARTITION_ANNOTATION), record.partition()); messageAnnotationsMap.put(Symbol.valueOf(Bridge.AMQP_OFFSET_ANNOTATION), record.offset()); if (record.key() != null) messageAnnotationsMap.put(Symbol.valueOf(Bridge.AMQP_KEY_ANNOTATION), record.key()); // get AMQP message annotations from the JSON JsonObject jsonMessageAnnotations = json.getJsonObject(JsonMessageConverter.MESSAGE_ANNOTATIONS); if (jsonMessageAnnotations != null) { for (Entry<String, Object> entry : jsonMessageAnnotations) { messageAnnotationsMap.put(Symbol.valueOf(entry.getKey()), entry.getValue()); } } MessageAnnotations messageAnnotations = new MessageAnnotations(messageAnnotationsMap); message.setMessageAnnotations(messageAnnotations); // get the AMQP message body from the JSON JsonObject jsonBody = json.getJsonObject(JsonMessageConverter.BODY); if (jsonBody != null) { // type attribtute for following sectin : AMQP value or raw data/binary String type = jsonBody.getString(JsonMessageConverter.SECTION_TYPE); if (type.equals(JsonMessageConverter.SECTION_AMQP_VALUE_TYPE)) { // section is an AMQP value Object jsonSection = jsonBody.getValue(JsonMessageConverter.SECTION); // encoded as String if (jsonSection instanceof String) { message.setBody(new AmqpValue(jsonSection)); // encoded as an array/List } else if (jsonSection instanceof JsonArray) { JsonArray jsonArray = (JsonArray) jsonSection; message.setBody(new AmqpValue(jsonArray.getList())); // encoded as a Map } else if (jsonSection instanceof JsonObject) { JsonObject jsonObject = (JsonObject) jsonSection; message.setBody(new AmqpValue(jsonObject.getMap())); } } else if (type.equals(JsonMessageConverter.SECTION_DATA_TYPE)) { // section is a raw binary data // get the section from the JSON (it's base64 encoded) byte[] value = jsonBody.getBinary(JsonMessageConverter.SECTION); message.setBody(new Data(new Binary(Base64.getDecoder().decode(value)))); } } return message; }
From source file:io.sqp.proxy.vertx.VertxBackendConnectionPool.java
License:Open Source License
private void loadConfigurations(JsonArray backendConfs) throws ConfigurationException { // first validate the configuration object if (backendConfs == null || backendConfs.isEmpty()) { throw new ConfigurationException("No backend was configured."); }/*from w ww . jav a 2s .com*/ if (backendConfs.size() > 1) { logger.log(Level.WARNING, "Only one backend configuration is supported at the moment. The rest is ignored."); } JsonObject firstConf = backendConfs.getJsonObject(0); if (firstConf == null) { throwInvalidConfiguration("It's not a valid JSON object."); } // Every backend needs a specific 'config' configuration map JsonObject backendSpecificConf = firstConf.getJsonObject("config"); if (backendSpecificConf == null) { throwInvalidConfiguration("Backend specific configuration is missing."); } _backendSpecificConfiguration = backendSpecificConf.getMap(); // The 'type' defines the subclass of BackendConnection that is the heart of the backend String backendType = firstConf.getString("type"); if (backendType == null) { throwInvalidConfiguration("No type specified."); } // Get the class from the class loader and verify it's a subclass of BackendConnection Class<?> uncastedBackendClass = null; try { uncastedBackendClass = Class.forName(backendType); } catch (ClassNotFoundException e) { throwInvalidConfiguration("Class '" + backendType + "' specified as 'type' was not found."); } try { _backendClass = uncastedBackendClass.asSubclass(Backend.class); } catch (ClassCastException e) { throwInvalidConfiguration("Class '" + backendType + "' is not a valid Backend implementation."); } }
From source file:net.kuujo.vertigo.deployment.ComponentFactory.java
License:Apache License
@Override public void resolve(String identifier, DeploymentOptions options, ClassLoader classLoader, Future<String> resolution) { identifier = VerticleFactory.removePrefix(identifier); JsonObject config = Configs.load(identifier); String main = config.getString("identifier"); if (main == null) { throw new VertxException(identifier + " does not contain a identifier field"); }//from w w w. ja v a 2s . c o m JsonObject deployment = config.getJsonObject("deployment"); if (deployment != null) { if (deployment.containsKey("worker")) { options.setWorker(deployment.getBoolean("worker")); } if (deployment.containsKey("multi-threaded")) { options.setMultiThreaded(deployment.getBoolean("multi-threaded")); } } resolution.complete(main); }