List of usage examples for io.vertx.core.json JsonObject put
public JsonObject put(String key, Object value)
From source file:io.knotx.dataobjects.ClientResponse.java
License:Apache License
public JsonObject toMetadataJson() { JsonObject json = new JsonObject(); json.put("statusCode", statusCode); json.put("headers", MultiMapConverter.toJsonObject(headers)); return json;/*from w w w.jav a 2 s.com*/ }
From source file:io.knotx.knot.service.service.ServiceEngine.java
License:Apache License
private JsonObject buildResultObject(AdapterResponse adapterResponse) { JsonObject object = new JsonObject(); String rawData = adapterResponse.getResponse().getBody().toString().trim(); if (rawData.charAt(0) == '[') { object.put(RESULT_NAMESPACE_KEY, new JsonArray(rawData)); } else if (rawData.charAt(0) == '{') { object.put(RESULT_NAMESPACE_KEY, new JsonObject(rawData)); } else {/* w w w . jav a2 s . c om*/ throw new DecodeException("Result is neither Json Array nor Json Object"); } object.put(RESPONSE_NAMESPACE_KEY, new JsonObject().put("statusCode", Integer.toString(adapterResponse.getResponse().getStatusCode()))); return object; }
From source file:io.knotx.launcher.KnotxModuleVerticleFactory.java
License:Apache License
@Override public void resolve(String id, DeploymentOptions deploymentOptions, ClassLoader classLoader, Future<String> resolution) { String identifier = VerticleFactory.removePrefix(id); String descriptorFile = identifier + ".json"; try {/*from www . j a v a2 s. c o m*/ JsonObject descriptor = readDescriptor(classLoader, descriptorFile); String main = readVerticleMainClass(descriptor, descriptorFile); // Any options specified in the module config will override anything specified at deployment time // Options and Config specified in knotx starter JSON will override those configurations JsonObject depOptions = deploymentOptions.toJson(); JsonObject depConfig = depOptions.getJsonObject(CONFIG_KEY, new JsonObject()); JsonObject knotOptions = descriptor.getJsonObject(OPTIONS_KEY, new JsonObject()); JsonObject knotConfig = knotOptions.getJsonObject(CONFIG_KEY, new JsonObject()); depOptions.mergeIn(knotOptions); depOptions.put(CONFIG_KEY, JsonObjectUtil.deepMerge(knotConfig, depConfig)); JsonObject serviceDescriptor = new JsonObject().put(OPTIONS_KEY, depOptions); // Any options or config provided by system properties will override anything specified // at deployment time and on starter Json config serviceDescriptor = overrideConfigWithSystemProperties(identifier, serviceDescriptor); deploymentOptions.fromJson(serviceDescriptor.getJsonObject(OPTIONS_KEY)); resolution.complete(main); } catch (Exception e) { resolution.fail(e); } }
From source file:io.knotx.launcher.SystemPropsConfiguration.java
License:Apache License
/** * Update given JsonObject with the data provided in system property during Knotx start.<br> * In order to provide such overrides you can use two approches: * <ul>/* w ww . j av a2 s . c om*/ * <li>-Dio.knotx.KnotxServer.httpPort=9999, * -Dio.knotx.KnotxServer.splitter.address=other-address - this will override one property * with the value given after '=' </li> * <li>-Dio.knotx.KnotxServer.splitter=file:/aaa/bb/cc.json - this will merge the given cc.json * file from the field specified</li> * </ul> * * @param descriptor - JsonObject with module descriptor * @return JsonObject - updated descriptor */ public JsonObject updateJsonObject(JsonObject descriptor) { final JsonObject object = descriptor.copy(); envConfig.entrySet().forEach(entry -> { String[] path = StringUtils.split(entry.getKey(), "."); JsonObject element = object; for (int idx = 0; idx < path.length; idx++) { if (idx < path.length - 1) { if (element.containsKey(path[idx])) { element = element.getJsonObject(path[idx]); } else { throw new IllegalArgumentException("Wrong config override. There is no matching element " + entry.getKey() + " in the configuration"); } } else { //last if (entry.getValue().getObject() instanceof JsonObject) { element.getJsonObject(path[idx]).mergeIn((JsonObject) entry.getValue().getObject()); } else { element.put(path[idx], entry.getValue().getObject()); } } } }); return object; }
From source file:io.knotx.mocks.adapter.MockActionAdapterHandler.java
License:Apache License
private JsonObject toJsonObject(MultiMap multiMap) { JsonObject result = new JsonObject(); multiMap.names().stream().forEach(name -> result.put(name, multiMap.get(name))); return result; }
From source file:io.knotx.util.JsonObjectUtil.java
License:Apache License
public static JsonObject deepMerge(JsonObject source, JsonObject other) { JsonObject result = source.copy(); other.forEach(entry -> {/*from ww w .j a va 2 s.c o m*/ if (result.containsKey(entry.getKey())) { if (isKeyAJsonObject(result, entry.getKey()) && entry.getValue() instanceof JsonObject) { result.put(entry.getKey(), deepMerge(source.getJsonObject(entry.getKey()), (JsonObject) entry.getValue())); } else { //Override whole key, if value is not jsonObject result.put(entry.getKey(), entry.getValue()); } } else { result.put(entry.getKey(), entry.getValue()); } }); return result; }
From source file:io.knotx.util.MultiMapConverter.java
License:Apache License
/** * Converts MultiMap to JsonObject<br> It expects the MultiMap key, contains List of String * objects, so the result of conversion will look like below * <br>//from ww w. jav a 2s. co m * <pre> * { * "mapKey1": ["val1", "val2"], * "mapKey2": ["val1"] * } * </pre> * * @param multiMap - {@link MultiMap} to convert * @return - {@link JsonObject} with {@link JsonArray} under each object key */ public static JsonObject toJsonObject(MultiMap multiMap) { JsonObject json = new JsonObject(); ((io.vertx.core.MultiMap) multiMap.getDelegate()).forEach(entry -> { JsonArray values; if (json.containsKey(entry.getKey())) { values = json.getJsonArray(entry.getKey()); } else { values = new JsonArray(); json.put(entry.getKey(), values); } values.add(entry.getValue()); }); return json; }
From source file:io.nitor.api.backend.auth.SetupAzureAdConnectAuth.java
License:Apache License
public static void setupAzureAd(JsonObject adAuth, Router router, String publicURI, boolean virtualHost, CookieSessionHandler sessionHandler, HttpClient httpClient) { final String callbackPath = adAuth.getString("callbackPath", "/oidc/callback"); String redirectUri = publicURI + callbackPath; adAuth.put("redirectUri", redirectUri); String path = adAuth.getString("route", "/*"); List<GraphQuery> graphQueries = new ArrayList<>(); JsonArray queryNodes = adAuth.getJsonArray("graphQueries"); if (queryNodes == null) { graphQueries.add(new GraphQuery(adAuth, "https://graph.microsoft.com/beta/me?$expand=memberOf")); } else {/*from w w w .ja v a2s . c o m*/ queryNodes.stream().map(JsonObject.class::cast).map(GraphQuery::new).forEach(graphQueries::add); } Set<String> forbiddenHeaders = graphQueries.stream().flatMap(gq -> gq.headerMappings.keySet().stream()) .collect(toSet()); logger.info("Graph queries: " + graphQueries.stream().map(gq -> gq.graphQueryURI).collect(Collectors.joining(", "))); logger.info("Headers: " + forbiddenHeaders); HashMap<String, Pattern> requiredHeaderMatchers = new HashMap<>(); adAuth.getJsonObject("requiredHeaders", new JsonObject()).forEach(mapping -> requiredHeaderMatchers .put(mapping.getKey(), Pattern.compile(mapping.getValue().toString()))); RedirectTokenService redirectTokenService = new RedirectTokenService(sessionHandler.getCookieConverter()); Handler<RoutingContext> securityHandler = authHandler(adAuth, forbiddenHeaders, requiredHeaderMatchers, publicURI, virtualHost, sessionHandler, redirectUri, redirectTokenService); router.get(FORBIDDEN_PATH).handler(ctx -> errorWithLogoutLink(ctx, FORBIDDEN)); router.get(UNAUTHORIZED_PATH).handler(ctx -> errorWithLogoutLink(ctx, UNAUTHORIZED)); router.get(callbackPath).handler(validateAuthCallback(adAuth, httpClient, sessionHandler, graphQueries, redirectUri, redirectTokenService)); if (virtualHost) { router.options(PROXY_AUTH_REDIRECT_AFTER).handler(SetupAzureAdConnectAuth::optionsHandler); router.route(PROXY_AUTH_REDIRECT_AFTER).handler(ctx -> { // phase 3: executed when returning to virtual domain with cookie and original url inside token // -> jump to original locatin and set the cookie String token = ctx.request().getParam("t"); Map<String, String> params = redirectTokenService.getParameters(ctx, token); if (params == null) { ctx.reroute(GET, UNAUTHORIZED_PATH); logger.warn("phase3: Could not decrypt parameters from 't'"); return; } String originalUrl = params.get("u"); String originalHost = getUriHostName(originalUrl); String host = getUriHostName(ctx.request().host()); if (originalHost != null && originalHost.equals(host)) { ctx.response().setStatusCode(TEMPORARY_REDIRECT.code()).putHeader(LOCATION, originalUrl) .putHeader(SET_COOKIE, params.get("c")).end(); } else { logger.warn("phase3: original host from cookie " + originalHost + " does not match request host " + host); ctx.reroute(GET, FORBIDDEN_PATH); } }); } router.route(path).handler(securityHandler); if (virtualHost) { router.options(PROXY_AUTH_REDIRECT_BEFORE).handler(SetupAzureAdConnectAuth::optionsHandler); router.route(PROXY_AUTH_REDIRECT_BEFORE).handler(securityHandler); router.route(PROXY_AUTH_REDIRECT_BEFORE).handler(ctx -> { // phase 2: executed when returning from authentication server with valid cookie // -> jump to original virtual host domain and pass the original url and auth cookie inside token String token = ctx.request().getParam("t"); Map<String, String> params = redirectTokenService.getParameters(ctx, token); if (params == null) { ctx.reroute(GET, UNAUTHORIZED_PATH); logger.warn("phase2: Could not decrypt parameters from 't'"); return; } String originalUrl = params.get("u"); String originalHost = getUriHostNamePort(originalUrl); if (originalUrl == null || !originalUrl.startsWith("https://")) { ctx.reroute(GET, FORBIDDEN_PATH); logger.warn( "phase2: original url from cookie " + originalUrl + " does not start with https://"); return; } Cookie cookie = sessionHandler.getAuthCookie(ctx.cookies()); params.put("c", cookie.encode()); String newToken = redirectTokenService.createToken(ctx, params); StringBuilder sb = new StringBuilder(); sb.append("https://").append(originalHost).append(PROXY_AUTH_REDIRECT_AFTER).append("?t=") .append(urlEncode(newToken)); ctx.response().setStatusCode(TEMPORARY_REDIRECT.code()).putHeader(LOCATION, sb).end(); }); } }
From source file:io.nitor.api.backend.auth.SetupAzureAdConnectAuth.java
License:Apache License
static void processGraphTokenResponse(HttpClientResponse resp, RoutingContext ctx, HttpClient httpClient, CookieSessionHandler sessionHandler, List<GraphQuery> graphQueries, String originalUrl) { if (resp.statusCode() != OK.code()) { resp.bodyHandler(body -> {//from w ww . ja v a 2s .c o m logger.warn("Failed to fetch graph access token: " + resp.statusMessage() + " - " + resp.getHeader(WWW_AUTHENTICATE) + " ::: " + body); ctx.reroute(GET, UNAUTHORIZED_PATH); }); return; } resp.bodyHandler(body -> { JsonObject json = body.toJsonObject(); String token = json.getString("access_token"); String refreshToken = json.getString("refresh_token"); // clean out sensitive stuff json.put("access_token", "<censored>"); json.put("refresh_token", "<censored>"); logger.debug("Got graph access response: {}", json); final AtomicInteger pendingRequests = new AtomicInteger(graphQueries.size()); final Map<String, String> sessionData = new HashMap<>(); ofNullable(refreshToken).ifPresent(t -> sessionData.put(GRAPH_ACCESS_TOKEN_KEY, t)); for (GraphQuery query : graphQueries) { String clientRequestId = UUID.randomUUID().toString(); logger.debug("Requesting " + query.graphQueryURI + "[" + clientRequestId + "]"); httpClient.getAbs(query.graphQueryURI).putHeader(AUTHORIZATION, "Bearer " + token) .putHeader(ACCEPT, APPLICATION_JSON).putHeader("client-request-id", clientRequestId) .setTimeout(SECONDS.toMillis(10)).exceptionHandler(err -> { if (pendingRequests.getAndSet(-1) != -1) { logger.error("Failed to fetch user information [" + clientRequestId + "]", err); ctx.reroute(GET, UNAUTHORIZED_PATH); } }).handler(r -> processMicrosoftUserInformation(r, ctx, sessionHandler, query.headerMappings, originalUrl, pendingRequests, sessionData, clientRequestId)) .end(); } }); }
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 .j a v a2 s .co m*/ 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); }