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

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

Introduction

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

Prototype

public JsonObject getJsonObject(String key, JsonObject def) 

Source Link

Document

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

Usage

From source file:io.engagingspaces.graphql.schema.SchemaMetadata.java

License:Open Source License

/**
 * Creates a new instance from its json representation.
 *
 * @param json the serialized json object
 */// w w  w.ja v a 2  s.  c  o m
public SchemaMetadata(JsonObject json) {
    Objects.requireNonNull(json, "Schema metadata json cannot be null");
    this.proxyJson = json.getJsonObject("proxyJson", new JsonObject());
    this.metadata = json.getJsonObject("metadata");
    this.options = new SchemaDefinitionOptions(json.getJsonObject("schemaDefinitionOptions"));
    this.serviceAddress = json.getString("serviceAddress");
}

From source file:io.flowly.auth.ExtJwtAuthProvider.java

License:Open Source License

@Override
public void authenticate(JsonObject authInfo, Handler<AsyncResult<User>> resultHandler) {
    try {//from   ww  w.  ja  v  a  2 s. co  m
        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.knotx.adapter.common.http.HttpAdapterConfiguration.java

License:Apache License

public HttpAdapterConfiguration(JsonObject config) {
    address = config.getString("address");
    services = config.getJsonArray("services").stream().map(item -> (JsonObject) item).map(item -> {
        ServiceMetadata metadata = new ServiceMetadata();
        metadata.path = item.getString("path");
        metadata.domain = item.getString("domain");
        metadata.port = item.getInteger("port");
        metadata.allowedRequestHeaderPatterns = item.getJsonArray("allowedRequestHeaders", new JsonArray())
                .stream().map(object -> (String) object).map(new StringToPatternFunction())
                .collect(Collectors.toList());
        return metadata;
    }).collect(Collectors.toList());
    clientOptions = config.getJsonObject("clientOptions", new JsonObject());
}

From source file:io.knotx.dataobjects.Fragment.java

License:Apache License

public Fragment(JsonObject fragment) {
    this.knots = fragment.getJsonArray(KNOTS_KEY).stream().map(String::valueOf).collect(Collectors.toList());
    this.content = fragment.getString(CONTENT_KEY);
    this.context = fragment.getJsonObject(CONTEXT_KEY, new JsonObject());
}

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   w w  w  .  j  a  v  a 2 s  .com
        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.repository.impl.RepositoryConnectorProxyImpl.java

License:Apache License

public RepositoryConnectorProxyImpl(Vertx vertx, JsonObject configuration) {
    clientOptions = configuration.getJsonObject("clientOptions", new JsonObject());
    clientDestination = configuration.getJsonObject("clientDestination");
    allowedRequestHeaders = configuration.getJsonArray("allowedRequestHeaders", new JsonArray()).stream()
            .map(object -> (String) object).map(new StringToPatternFunction()).collect(Collectors.toList());
    httpClient = createHttpClient(vertx);
}

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 ww  w. j  a  v a 2  s  .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:org.eclipse.hono.service.auth.impl.FileBasedAuthenticationService.java

License:Open Source License

private void parsePermissions(final JsonObject permissionsObject) {

    Objects.requireNonNull(permissionsObject);
    parseRoles(permissionsObject.getJsonObject(FIELD_ROLES, new JsonObject()));
    parseUsers(permissionsObject.getJsonObject(FIELD_USERS, new JsonObject()));
}

From source file:org.eclipse.hono.service.registration.BaseRegistrationService.java

License:Open Source License

private JsonObject getRequestPayload(final JsonObject request) {

    final JsonObject payload = request.getJsonObject(RegistrationConstants.FIELD_PAYLOAD, new JsonObject());
    Boolean enabled = payload.getBoolean(FIELD_ENABLED);
    if (enabled == null) {
        log.debug("adding 'enabled' key to payload");
        payload.put(FIELD_ENABLED, Boolean.TRUE);
    }/*from   w ww .ja  va  2s.  c o m*/
    return payload;
}

From source file:org.entcore.blog.services.impl.DefaultBlogTimelineService.java

License:Open Source License

@Override
public void notifySubmitPost(final HttpServerRequest request, final String blogId, final String postId,
        final UserInfos user, final String resourceUri) {
    if (resourceUri != null && user != null && blogId != null && request != null) {
        QueryBuilder blogQuery = QueryBuilder.start("_id").is(blogId);
        JsonObject blogKeys = new JsonObject().put("author", 1);
        mongo.findOne("blogs", MongoQueryBuilder.build(blogQuery), blogKeys,
                new Handler<Message<JsonObject>>() {
                    @Override// ww  w. j  a v a2s  . c  o  m
                    public void handle(final Message<JsonObject> event) {
                        if ("ok".equals(event.body().getString("status"))) {
                            final String authorId = event.body().getJsonObject("result", new JsonObject())
                                    .getJsonObject("author", new JsonObject()).getString("userId");

                            final QueryBuilder query = QueryBuilder.start("_id").is(postId);
                            final JsonObject keys = new JsonObject().put("title", 1).put("blog", 1);
                            final JsonArray fetch = new JsonArray().add("blog");

                            mongo.findOne("posts", MongoQueryBuilder.build(query), keys, fetch,
                                    MongoDbResult.validResultHandler(new Handler<Either<String, JsonObject>>() {
                                        public void handle(Either<String, JsonObject> event) {
                                            if (event.isLeft())
                                                return;

                                            final JsonObject post = event.right().getValue();

                                            findRecipiants("posts", query, keys, fetch,
                                                    "org-entcore-blog-controllers-PostController|publish", user,
                                                    new Handler<Map<String, Object>>() {
                                                        @Override
                                                        public void handle(Map<String, Object> event) {
                                                            List<String> recipients = new ArrayList<>();
                                                            if (event != null)
                                                                recipients = (List<String>) event
                                                                        .get("recipients");

                                                            recipients.add(authorId);
                                                            JsonObject p = new JsonObject()
                                                                    .put("uri",
                                                                            "/userbook/annuaire#"
                                                                                    + user.getUserId() + "#"
                                                                                    + user.getType())
                                                                    .put("username", user.getUsername())
                                                                    .put("blogTitle",
                                                                            post.getJsonObject("blog",
                                                                                    new JsonObject())
                                                                                    .getString("title"))
                                                                    .put("blogUri", resourceUri)
                                                                    .put("postTitle", post.getString("title"))
                                                                    .put("postUri", resourceUri + "/" + postId)
                                                                    .put("resourceUri",
                                                                            resourceUri + "/" + postId)
                                                                    .put("disableAntiFlood", true);
                                                            notification.notifyTimeline(request,
                                                                    "blog.submit-post", user, recipients,
                                                                    blogId, postId, p);

                                                        }
                                                    });
                                        }
                                    }));
                        }
                    }
                });
    }
}