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) 

Source Link

Document

Get the JsonObject value with the specified key

Usage

From source file:io.hijynx.ensemble.identity.RoleServiceVertxProxyHandler.java

License:Apache License

public void handle(Message<JsonObject> msg) {
    try {// w  w  w.ja  v  a2s .c om
        JsonObject json = msg.body();
        String action = msg.headers().get("action");
        if (action == null) {
            throw new IllegalStateException("action not specified");
        }
        accessed();
        switch (action) {
        case "addRole": {
            service.addRole(
                    json.getJsonObject("role") == null ? null
                            : new io.hijynx.ensemble.identity.Role(json.getJsonObject("role")),
                    createHandler(msg));
            break;
        }
        case "retrieveRole": {
            service.retrieveRole((java.lang.String) json.getValue("id"), res -> {
                if (res.failed()) {
                    if (res.cause() instanceof ServiceException) {
                        msg.reply(res.cause());
                    } else {
                        msg.reply(new ServiceException(-1, res.cause().getMessage()));
                    }
                } else {
                    msg.reply(res.result() == null ? null : res.result().toJson());
                }
            });
            break;
        }
        case "retrieveRoleByName": {
            service.retrieveRoleByName((java.lang.String) json.getValue("rolename"), res -> {
                if (res.failed()) {
                    if (res.cause() instanceof ServiceException) {
                        msg.reply(res.cause());
                    } else {
                        msg.reply(new ServiceException(-1, res.cause().getMessage()));
                    }
                } else {
                    msg.reply(res.result() == null ? null : res.result().toJson());
                }
            });
            break;
        }
        case "retrieveAllRoles": {
            service.retrieveAllRoles(res -> {
                if (res.failed()) {
                    if (res.cause() instanceof ServiceException) {
                        msg.reply(res.cause());
                    } else {
                        msg.reply(new ServiceException(-1, res.cause().getMessage()));
                    }
                } else {
                    msg.reply(new JsonArray(
                            res.result().stream().map(Role::toJson).collect(Collectors.toList())));
                }
            });
            break;
        }
        case "updateRole": {
            service.updateRole(json.getJsonObject("role") == null ? null
                    : new io.hijynx.ensemble.identity.Role(json.getJsonObject("role")), res -> {
                        if (res.failed()) {
                            if (res.cause() instanceof ServiceException) {
                                msg.reply(res.cause());
                            } else {
                                msg.reply(new ServiceException(-1, res.cause().getMessage()));
                            }
                        } else {
                            msg.reply(res.result() == null ? null : res.result().toJson());
                        }
                    });
            break;
        }
        case "deleteRole": {
            service.deleteRole((java.lang.String) json.getValue("id"), createHandler(msg));
            break;
        }
        case "retrieveAssignedMembers": {
            service.retrieveAssignedMembers((java.lang.String) json.getValue("roleId"), createListHandler(msg));
            break;
        }
        case "retrieveAssignedPrivileges": {
            service.retrieveAssignedPrivileges((java.lang.String) json.getValue("roleId"),
                    createListHandler(msg));
            break;
        }
        case "grant": {
            service.grant((java.lang.String) json.getValue("roleId"),
                    (java.lang.String) json.getValue("privilegeId"), createHandler(msg));
            break;
        }
        case "revoke": {
            service.revoke((java.lang.String) json.getValue("roleId"),
                    (java.lang.String) json.getValue("privilegeId"), createHandler(msg));
            break;
        }
        case "assign": {
            service.assign((java.lang.String) json.getValue("roleId"),
                    (java.lang.String) json.getValue("userId"), createHandler(msg));
            break;
        }
        case "deassign": {
            service.deassign((java.lang.String) json.getValue("roleId"),
                    (java.lang.String) json.getValue("userId"), createHandler(msg));
            break;
        }
        default: {
            throw new IllegalStateException("Invalid action: " + action);
        }
        }
    } catch (Throwable t) {
        msg.reply(new ServiceException(500, t.getMessage()));
        throw t;
    }
}

From source file:io.hijynx.ensemble.identity.UserServiceVertxProxyHandler.java

License:Apache License

public void handle(Message<JsonObject> msg) {
    try {/*from w  ww .  ja  va2  s  .  c om*/
        JsonObject json = msg.body();
        String action = msg.headers().get("action");
        if (action == null) {
            throw new IllegalStateException("action not specified");
        }
        accessed();
        switch (action) {
        case "addUser": {
            service.addUser(
                    json.getJsonObject("user") == null ? null
                            : new io.hijynx.ensemble.identity.User(json.getJsonObject("user")),
                    createHandler(msg));
            break;
        }
        case "retrieveUser": {
            service.retrieveUser((java.lang.String) json.getValue("id"), res -> {
                if (res.failed()) {
                    if (res.cause() instanceof ServiceException) {
                        msg.reply(res.cause());
                    } else {
                        msg.reply(new ServiceException(-1, res.cause().getMessage()));
                    }
                } else {
                    msg.reply(res.result() == null ? null : res.result().toJson());
                }
            });
            break;
        }
        case "retrieveByUsername": {
            service.retrieveByUsername((java.lang.String) json.getValue("username"), res -> {
                if (res.failed()) {
                    if (res.cause() instanceof ServiceException) {
                        msg.reply(res.cause());
                    } else {
                        msg.reply(new ServiceException(-1, res.cause().getMessage()));
                    }
                } else {
                    msg.reply(res.result() == null ? null : res.result().toJson());
                }
            });
            break;
        }
        case "retrieveAllUsers": {
            service.retrieveAllUsers(res -> {
                if (res.failed()) {
                    if (res.cause() instanceof ServiceException) {
                        msg.reply(res.cause());
                    } else {
                        msg.reply(new ServiceException(-1, res.cause().getMessage()));
                    }
                } else {
                    msg.reply(new JsonArray(
                            res.result().stream().map(User::toJson).collect(Collectors.toList())));
                }
            });
            break;
        }
        case "updateUser": {
            service.updateUser(json.getJsonObject("user") == null ? null
                    : new io.hijynx.ensemble.identity.User(json.getJsonObject("user")), res -> {
                        if (res.failed()) {
                            if (res.cause() instanceof ServiceException) {
                                msg.reply(res.cause());
                            } else {
                                msg.reply(new ServiceException(-1, res.cause().getMessage()));
                            }
                        } else {
                            msg.reply(res.result() == null ? null : res.result().toJson());
                        }
                    });
            break;
        }
        case "deleteUser": {
            service.deleteUser((java.lang.String) json.getValue("id"), createHandler(msg));
            break;
        }
        case "updatePassword": {
            service.updatePassword((java.lang.String) json.getValue("userId"),
                    (java.lang.String) json.getValue("password"), createHandler(msg));
            break;
        }
        default: {
            throw new IllegalStateException("Invalid action: " + action);
        }
        }
    } catch (Throwable t) {
        msg.reply(new ServiceException(500, t.getMessage()));
        throw t;
    }
}

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));
        }/*from  w w w .j av  a  2s  .  com*/
    }
    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  a v a2s .c  o  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.server.KnotxServerConfiguration.java

License:Apache License

public KnotxServerConfiguration(JsonObject config) {
    httpPort = config.getInteger("httpPort");
    splitterAddress = config.getJsonObject("splitter").getString("address");
    assemblerAddress = config.getJsonObject("assembler").getString("address");

    displayExceptionDetails = config.getBoolean("displayExceptionDetails", false);

    engineRouting = Maps.newEnumMap(HttpMethod.class);
    config.getJsonObject("routing").stream().forEach(this::parseMethodRouting);

    repositoryAddressMapping = Maps.newHashMap();
    config.getJsonArray("repositories").stream().map(item -> (JsonObject) item)
            .forEach(object -> repositoryAddressMapping.put(object.getString("path"),
                    new RepositoryEntry(object.getString("address"), object.getBoolean("doProcessing", true))));

    allowedResponseHeaders = config.getJsonArray("allowedResponseHeaders").stream()
            .map(item -> ((String) item).toLowerCase()).collect(Collectors.toSet());
}

From source file:io.knotx.server.KnotxServerConfiguration.java

License:Apache License

private RoutingEntry parseRoutingCriteria(JsonObject object) {
    return new RoutingEntry(object.getString("path"), object.getString("address"),
            parseOnTransition(object.getJsonObject("onTransition")));
}

From source file:io.knotx.util.JsonObjectUtil.java

License:Apache License

public static JsonObject deepMerge(JsonObject source, JsonObject other) {
    JsonObject result = source.copy();//from w  ww  .j  av a  2 s.  c o m
    other.forEach(entry -> {
        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.nitor.api.backend.auth.SetupAzureAdConnectAuth.java

License:Apache License

private static Handler<RoutingContext> authHandler(JsonObject adAuth, Set<String> forbiddenHeaders,
        HashMap<String, Pattern> requiredHeaderMatchers, String publicURI, boolean virtualHosting,
        CookieSessionHandler sessionHandler, String redirectUri, RedirectTokenService redirectTokenService) {
    String publicHost = getUriHostName(publicURI);
    return ctx -> {
        Optional<Map<String, String>> headers = ofNullable(sessionHandler.getSessionData(ctx));
        if (headers.isPresent()) {
            MultiMap h = ctx.request().headers();
            forbiddenHeaders.forEach(h::remove);
            headers.get().entrySet().stream().filter(e -> !e.getKey().startsWith(SECRET_DATA_PREFIX))
                    .forEach(e -> h.set(e.getKey(), e.getValue()));

            if (!requiredHeaderMatchers.entrySet().stream()
                    .allMatch(e -> headerMatches(h.get(e.getKey()), e.getValue()))) {
                logger.info("Not authorised to view resource '" + ctx.request().path() + "' with session data: "
                        + headers.get());

                ctx.reroute(GET, FORBIDDEN_PATH);
                return;
            }//from w  ww  .  j  a va2s  . c  om

            ctx.next();
            return;
        }

        String publicURIWithoutProtocol = getUriHostName(publicURI);

        String host = getUriHostName(ctx.request().host());
        if (virtualHosting && !publicURIWithoutProtocol.equals(host)) {
            // phase 1: executed iff authentication cookie is missing && the browser is not on the auth domain but on a virtual domain
            // -> jump to auth domain and pass the current url inside token
            String currentUri = forceHttps(replaceHostAndPort(ctx.request().absoluteURI(), host));
            String token = redirectTokenService.createToken(ctx, singletonMap("u", currentUri));
            ctx.response()
                    .setStatusCode((ctx.request().method() == GET ? TEMPORARY_REDIRECT : SEE_OTHER).code()) // ask browser to turn POST etc into GET when redirecting
                    .putHeader(CACHE_CONTROL, "no-cache, no-store, must-revalidate").putHeader(EXPIRES, "0")
                    .putHeader(LOCATION, publicURI + PROXY_AUTH_REDIRECT_BEFORE + "?t=" + urlEncode(token))
                    .end();
            return;
        }

        StringBuilder sb = new StringBuilder();
        String currentUri = forceHttps(replaceHost(ctx.request().absoluteURI(), publicHost));
        sb.append(adAuth.getJsonObject("openIdConfig").getString("authorization_endpoint"))
                .append("?domain_hint=organizations&response_type=code&response_mode=query")
                .append("&client_id=").append(urlEncode(adAuth.getString("clientId"))).append("&redirect_uri=")
                .append(urlEncode(redirectUri)).append("&scope=").append(urlEncode(adAuth.getString("scope")))
                //.append("&login_hint=").append(urlEncode(previousKnownUserName)) -- could try to fetch it from expired session cookie?
                //.append("&prompt=").append("login") -- force login - maybe do if IP is from different country?
                .append("&state=")
                .append(urlEncode(redirectTokenService.createToken(ctx, singletonMap("a", currentUri))));
        ctx.response().setStatusCode(TEMPORARY_REDIRECT.code()).putHeader(LOCATION, sb)
                .putHeader(CACHE_CONTROL, "no-cache, no-store, must-revalidate").putHeader(EXPIRES, "0").end();
    };
}

From source file:io.nitor.api.backend.auth.SetupAzureAdConnectAuth.java

License:Apache License

private static void finalizeAuthentication(RoutingContext ctx, JsonObject adAuth, HttpClient httpClient,
        CookieSessionHandler sessionHandler, List<GraphQuery> graphQueries, String redirectUri,
        RedirectTokenService redirectTokenService) {
    Map<String, String> params = redirectTokenService.getParameters(ctx, ctx.request().getParam("state"));
    if (params == null || params.get("a") == null) {
        logger.error("Missing state parameter");
        ctx.reroute(GET, UNAUTHORIZED_PATH);
        return;//from   w  w w  .  j  a va2 s.co m
    }
    String originalUrl = params.get("a");
    String code = ctx.request().getParam("code");
    String graphScopes = adAuth.getString("scope");
    Buffer form = Buffer
            .buffer("code=" + urlEncode(code) + "&client_id=" + urlEncode(adAuth.getString("clientId"))
                    + "&scope=" + urlEncode(graphScopes) + "&grant_type=authorization_code" + "&client_secret="
                    + urlEncode(adAuth.getString("clientSecret")) + "&redirect_uri=" + urlEncode(redirectUri));
    String tokenUrl = adAuth.getJsonObject("openIdConfig").getString("token_endpoint");
    logger.debug("Requesting graph access token from " + tokenUrl + " with [ " + form + "]");
    httpClient.postAbs(tokenUrl).putHeader(ACCEPT, APPLICATION_JSON)
            .putHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
            .putHeader(CONTENT_LENGTH, String.valueOf(form.length())).setTimeout(SECONDS.toMillis(10))
            .exceptionHandler(err -> {
                logger.error("Failed to fetch graph access token", err);
                ctx.reroute(GET, UNAUTHORIZED_PATH);
            }).handler(resp -> processGraphTokenResponse(resp, ctx, httpClient, sessionHandler, graphQueries,
                    originalUrl))
            .end(form);
}

From source file:io.nitor.api.backend.lambda.LambdaHandler.java

License:Apache License

@Override
public void handle(RoutingContext ctx) {
    HttpServerRequest sreq = ctx.request();
    final String path = normalizePath(sreq.path(), routeLength);
    if (path == null) {
        ctx.response().setStatusCode(NOT_FOUND.code()).end();
        return;/*  w w w. ja  va2 s  .  c o m*/
    }
    HttpServerResponse sres = ctx.response();
    PathMatchResult<Entry<String, String>> matchRes = pathTemplateMatcher.match(path);
    final String lambdaFunction, qualifier;
    if (matchRes == null) {
        logger.error("No matching path template");
        sres.setStatusCode(BAD_GATEWAY.code());
        return;
    } else {
        lambdaFunction = matchRes.getValue().getKey();
        qualifier = matchRes.getValue().getValue();
    }
    sreq.bodyHandler(new Handler<Buffer>() {
        @Override
        public void handle(Buffer event) {
            byte[] body = event.getBytes();
            APIGatewayProxyRequestEvent reqObj = new APIGatewayProxyRequestEvent();
            /*
            * Handle body
            */
            String bodyObjStr = null;
            boolean isBase64Encoded = true;
            if (body != null && body.length > 0) {
                String ct = sreq.getHeader("content-type").toLowerCase();
                if (ct.startsWith("text/") || ct.startsWith("application/json")
                        || (ct.indexOf("charset=") > 0)) {
                    String charset = "utf-8";
                    if (ct.indexOf("charset=") > 0) {
                        charset = getCharsetFromContentType(ct);
                    }
                    try {
                        bodyObjStr = Charset.forName(charset).newDecoder()
                                .onMalformedInput(CodingErrorAction.REPORT)
                                .onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(body))
                                .toString();
                        isBase64Encoded = false;
                    } catch (CharacterCodingException e) {
                        logger.error("Decoding body failed", e);
                    }
                }
                if (bodyObjStr == null) {
                    bodyObjStr = Base64.getEncoder().encodeToString(body);
                }
                reqObj = reqObj.withBody(bodyObjStr).withIsBase64Encoded(isBase64Encoded);
            }
            Map<String, List<String>> headerMultivalue = sreq.headers().entries().stream()
                    .collect(toMap(Entry::getKey, x -> sreq.headers().getAll(x.getKey())));
            Map<String, String> headerValue = sreq.headers().entries().stream()
                    .collect(toMap(Entry::getKey, Entry::getValue));

            /*
            * Handle request context
            */
            RequestIdentity reqId = new RequestIdentity().withSourceIp(getRemoteAddress(ctx))
                    .withUserAgent(sreq.getHeader(USER_AGENT));
            if (ctx.user() != null) {
                reqId.withUser(ctx.user().principal().toString());
            }
            ProxyRequestContext reqCtx = new ProxyRequestContext()
                    .withPath(sreq.path().substring(0, routeLength)).withHttpMethod(sreq.method().toString())
                    .withIdentity(reqId);
            reqObj = reqObj.withMultiValueHeaders(headerMultivalue).withHeaders(headerValue)
                    .withHttpMethod(sreq.method().toString()).withPath(sreq.path()).withResource(path)
                    .withQueryStringParameters(splitQuery(sreq.query()))
                    .withMultiValueQueryStringParameters(splitMultiValueQuery(sreq.query()))
                    .withPathParameters(matchRes.getParameters()).withRequestContext(reqCtx);
            String reqStr = JsonObject.mapFrom(reqObj).toString();
            byte[] sendBody = reqStr.getBytes(UTF_8);
            InvokeRequest req = InvokeRequest.builder().invocationType(InvocationType.REQUEST_RESPONSE)
                    .functionName(lambdaFunction).qualifier(qualifier).payload(SdkBytes.fromByteArray(sendBody))
                    .build();
            logger.info("Calling lambda " + lambdaFunction + ":" + qualifier);
            logger.debug("Payload: " + reqStr);
            CompletableFuture<InvokeResponse> respFuture = lambdaCl.invoke(req);
            respFuture.whenComplete((iresp, err) -> {
                if (iresp != null) {
                    try {
                        String payload = iresp.payload().asString(UTF_8);
                        JsonObject resp = new JsonObject(payload);
                        int statusCode = resp.getInteger("statusCode");
                        sres.setStatusCode(statusCode);
                        for (Entry<String, Object> next : resp.getJsonObject("headers").getMap().entrySet()) {
                            sres.putHeader(next.getKey(), next.getValue().toString());
                        }
                        String respBody = resp.getString("body");
                        byte[] bodyArr = new byte[0];
                        if (body != null && !respBody.isEmpty()) {
                            if (TRUE.equals(resp.getBoolean("isBase64Encoded"))) {
                                bodyArr = Base64.getDecoder().decode(body);
                            } else {
                                bodyArr = respBody.getBytes(UTF_8);
                            }
                        }
                        sres.putHeader(CONTENT_LENGTH, String.valueOf(bodyArr.length));
                        Buffer buffer = Buffer.buffer(bodyArr);
                        tryToCacheContent(ctx, buffer);
                        sres.write(buffer);
                    } catch (Throwable t) {
                        logger.error("Error processing lambda request", t);
                        if (!sres.headWritten()) {
                            sres.setStatusCode(BAD_GATEWAY.code());
                            sres.putHeader(CONTENT_TYPE, "application/json");
                            Buffer response = Buffer.buffer(new LambdaErrorResponse(t).toString());
                            sres.putHeader(CONTENT_LENGTH, String.valueOf(response.length()));
                            sres.write(response);
                        }
                    } finally {
                        sres.end();
                    }
                } else {
                    logger.error("Error processing lambda request", err);
                    sres.setStatusCode(BAD_GATEWAY.code());
                    sres.putHeader(CONTENT_TYPE, "application/json");
                    Buffer response = Buffer.buffer(new LambdaErrorResponse(err).toString());
                    sres.putHeader(CONTENT_LENGTH, String.valueOf(response.length()));
                    sres.end(response);
                }
            });
        }
    });
}