List of usage examples for io.vertx.core.json JsonObject containsKey
public boolean containsKey(String key)
From source file:io.engagingspaces.graphql.marshaller.schema.impl.SchemaContextImpl.java
License:Open Source License
/** * {@inheritDoc}/*from ww w .j av a2 s . c om*/ */ @Override @SuppressWarnings("unchecked") public <T, U extends SchemaDecorator> List<T> unmarshallList(JsonObject json, String listKey, U parent) { if (json == null || !json.containsKey(listKey) || json.getValue(listKey) == null) { return Collections.emptyList(); } Object list = json.getValue(listKey); if (list instanceof JsonObject) { return ((JsonObject) list).stream().map(entry -> (T) unmarshall((JsonObject) entry.getValue(), parent)) .collect(Collectors.toList()); } else if (list instanceof JsonArray) { return ((JsonArray) list).stream().map(value -> (T) unmarshall((JsonObject) value, parent)) .collect(Collectors.toList()); } else { throw new IllegalStateException( "Failed to unmarshall type to list. Type: " + list.getClass().getName()); } }
From source file:io.engagingspaces.graphql.marshaller.schema.Unmarshaller.java
License:Open Source License
/** * Used internally for un-marshaling of schema objects. * * @param json the json object to un-marshall * @param context the schema context/*from www .j a v a 2s . co m*/ * @param parent the parent schema decorator object (can be null) * @param <T> type parameter indicating the schema object type to return * @param <U> type parameter indicating the type of the parent schema object * @return the un-marshaled schema decorator object */ @SuppressWarnings("unchecked") static <T, U> T unmarshall(JsonObject json, SchemaContext context, U parent) { String original = json.getString(PropNames.MARSHALED_TYPE); if (StaticDataFetcher.class.getName().equals(original)) { original = DataFetcher.class.getName(); } else if (json.containsKey(PropNames.SCHEMAS)) { original = GraphQLSchema.class.getName(); } else if (original == null) { throw new IllegalStateException("Failed to unmarshall, incorrect format or missing marshaling data"); } String marshallToType = DECORATOR_PACKAGE + original.substring(original.lastIndexOf(DOT)) + DECORATOR_POSTFIX; try { Class<?> clazz = Class.forName(marshallToType); Constructor<?> jsonConstructor; if (parent == null) { jsonConstructor = clazz.getConstructor(JsonObject.class, SchemaContext.class); return (T) jsonConstructor.newInstance(json, context); } Class<?> parentClass = parent.getClass(); if (parent instanceof GraphQLObjectTypeDO || parent instanceof GraphQLInterfaceTypeDO) { parentClass = GraphQLType.class; } jsonConstructor = clazz.getConstructor(JsonObject.class, SchemaContext.class, parentClass); return (T) jsonConstructor.newInstance(json, context, parent); } catch (Exception ex) { throw new IllegalStateException("Failed to marshal '" + original + "' to: " + marshallToType, ex); } }
From source file:io.flowly.auth.ExtJwtAuthProvider.java
License:Open Source License
@Override public void authenticate(JsonObject authInfo, Handler<AsyncResult<User>> resultHandler) { try {/* ww w . ja v a 2 s.com*/ final JsonObject payload = jwt.decode(authInfo.getString("jwt")); final JsonObject options = authInfo.getJsonObject("options", EMPTY_OBJECT); // All dates in JWT are of type NumericDate // a NumericDate is: numeric value representing the number of seconds from 1970-01-01T00:00:00Z UTC until // the specified UTC date/time, ignoring leap seconds final long now = System.currentTimeMillis() / 1000; if (payload.containsKey("exp") && !options.getBoolean("ignoreExpiration", false)) { if (now >= payload.getLong("exp")) { resultHandler.handle(Future.failedFuture("Expired JWT token: exp <= now")); return; } } if (payload.containsKey("iat")) { Long iat = payload.getLong("iat"); // issue at must be in the past if (iat > now) { resultHandler.handle(Future.failedFuture("Invalid JWT token: iat > now")); return; } } if (payload.containsKey("nbf")) { Long nbf = payload.getLong("nbf"); // not before must be after now if (nbf > now) { resultHandler.handle(Future.failedFuture("Invalid JWT token: nbf > now")); return; } } if (options.containsKey("audience")) { JsonArray audiences = options.getJsonArray("audience", EMPTY_ARRAY); JsonArray target = payload.getJsonArray("aud", EMPTY_ARRAY); if (Collections.disjoint(audiences.getList(), target.getList())) { resultHandler .handle(Future.failedFuture("Invalid JWT audience. expected: " + audiences.encode())); return; } } if (options.containsKey("issuer")) { if (!options.getString("issuer").equals(payload.getString("iss"))) { resultHandler.handle(Future.failedFuture("Invalid JWT issuer")); return; } } resultHandler.handle(Future.succeededFuture(new ExtJwtUser(payload, permissionsClaimKey))); } catch (RuntimeException e) { resultHandler.handle(Future.failedFuture(e)); } }
From source file:io.flowly.auth.ExtJwtAuthProvider.java
License:Open Source License
@Override public String generateToken(JsonObject claims, final JWTOptions options) { final JsonObject jsonOptions = options.toJSON(); // we do some "enhancement" of the claims to support roles and permissions if (jsonOptions.containsKey("permissions") && !claims.containsKey(permissionsClaimKey)) { claims.put(permissionsClaimKey, jsonOptions.getJsonArray("permissions")); }/* w w w.ja v a 2s.c o m*/ return jwt.sign(claims, options.toJSON()); }
From source file:io.flowly.auth.manager.BaseManager.java
License:Open Source License
/** * Retrieves direct and indirect memberships that a user or group holds. * * @param vertex vertex in the auth graph representing a user or group. * @param jsonObject JSON object representing the user or group to which retrieved memberships are added. * @param includeEffectiveMemberships indicates if all the user or group memberships are to be retrieved. * @param includeDirectMemberships indicates if the user's direct memberships are to be retrieved. * @param includePermissions indicates if the permissions granted to each group are to be retrieved. *///from www . j av a 2s.c o m protected void getMemberships(Vertex vertex, JsonObject jsonObject, boolean includeEffectiveMemberships, boolean includeDirectMemberships, boolean includePermissions) { boolean isUserVertex = jsonObject.containsKey(User.USER_ID); String uniqueId = isUserVertex ? jsonObject.getString(User.USER_ID) : jsonObject.getString(Group.GROUP_ID); if (includeEffectiveMemberships || includePermissions) { JsonArray effectiveMemberships = new JsonArray(); jsonObject.put(User.EFFECTIVE_MEMBERSHIPS, effectiveMemberships); List<Vertex> groupVertices = graph.traversal().V(vertex).repeat(__.outE(Schema.E_MEMBER_OF).inV()) .emit().toList(); getDistinctMemberships(groupVertices, effectiveMemberships, uniqueId, isUserVertex, includePermissions); } if (includeDirectMemberships) { JsonArray directMemberships = new JsonArray(); jsonObject.put(User.DIRECT_MEMBERSHIPS, directMemberships); getDistinctMemberships(graph.traversal().V(vertex).outE(Schema.E_MEMBER_OF).inV().toList(), directMemberships, null, false, false); } }
From source file:io.knotx.launcher.KnotxStarterVerticle.java
License:Apache License
private DeploymentOptions getModuleOptions(final String module) { DeploymentOptions deploymentOptions = new DeploymentOptions(); if (config().containsKey(CONFIG_OVERRIDE) && config().getJsonObject(CONFIG_OVERRIDE).containsKey(module)) { JsonObject moduleConfig = config().getJsonObject(CONFIG_OVERRIDE).getJsonObject(module); if (moduleConfig.containsKey(MODULE_OPTIONS)) { deploymentOptions.fromJson(moduleConfig.getJsonObject(MODULE_OPTIONS)); }//w w w. j av a 2 s . c om } return deploymentOptions; }
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>//from w w w . j av a2s . co m * <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.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 v a 2s .c om 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 w ww . j av a 2 s .c om * <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.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 www. ja va 2 s. c o 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); }