Example usage for io.vertx.core.eventbus Message body

List of usage examples for io.vertx.core.eventbus Message body

Introduction

In this page you can find the example usage for io.vertx.core.eventbus Message body.

Prototype

@CacheReturn
T body();

Source Link

Document

The body of the message.

Usage

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

License:Open Source License

/**
 * Processes a registration request message received via the Vertx event bus.
 * //  w w  w  .java2 s  . c om
 * @param regMsg The message.
 */
public final void processRegistrationMessage(final Message<JsonObject> regMsg) {

    try {
        final JsonObject body = regMsg.body();
        final String tenantId = body.getString(RequestResponseApiConstants.FIELD_TENANT_ID);
        final String deviceId = body.getString(RequestResponseApiConstants.FIELD_DEVICE_ID);
        final String operation = body.getString(MessageHelper.SYS_PROPERTY_SUBJECT);

        switch (operation) {
        case ACTION_ASSERT:
            log.debug("asserting registration of device [{}] with tenant [{}]", deviceId, tenantId);
            assertRegistration(tenantId, deviceId, result -> reply(regMsg, result));
            break;
        case ACTION_GET:
            log.debug("retrieving device [{}] of tenant [{}]", deviceId, tenantId);
            getDevice(tenantId, deviceId, result -> reply(regMsg, result));
            break;
        case ACTION_REGISTER:
            JsonObject payload = getRequestPayload(body);
            log.debug("registering device [{}] of tenant [{}] with data {}", deviceId, tenantId,
                    payload != null ? payload.encode() : null);
            addDevice(tenantId, deviceId, payload, result -> reply(regMsg, result));
            break;
        case ACTION_UPDATE:
            payload = getRequestPayload(body);
            log.debug("updating registration for device [{}] of tenant [{}] with data {}", deviceId, tenantId,
                    payload != null ? payload.encode() : null);
            updateDevice(tenantId, deviceId, payload, result -> reply(regMsg, result));
            break;
        case ACTION_DEREGISTER:
            log.debug("deregistering device [{}] of tenant [{}]", deviceId, tenantId);
            removeDevice(tenantId, deviceId, result -> reply(regMsg, result));
            break;
        case ACTION_ENABLED:
            log.debug("checking if device [{}] of tenant [{}] is enabled", deviceId, tenantId);
            isEnabled(tenantId, deviceId, result -> reply(regMsg, result));
            break;
        default:
            log.info("operation [{}] not supported", operation);
            reply(regMsg, RegistrationResult.from(HTTP_BAD_REQUEST));
        }
    } catch (ClassCastException e) {
        log.debug("malformed request message");
        reply(regMsg, RegistrationResult.from(HTTP_BAD_REQUEST));
    }
}

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

License:Open Source License

/**
 * Sends a response to a registration request over the Vertx event bus.
 * /*from w w w . ja va  2s . c o m*/
 * @param request The message to respond to.
 * @param result The registration result that should be conveyed in the response.
 */
protected final void reply(final Message<JsonObject> request, final RegistrationResult result) {

    final JsonObject body = request.body();
    final String tenantId = body.getString(RequestResponseApiConstants.FIELD_TENANT_ID);
    final String deviceId = body.getString(RequestResponseApiConstants.FIELD_DEVICE_ID);

    request.reply(RegistrationConstants.getServiceReplyAsJson(tenantId, deviceId, result));
}

From source file:org.entcore.archive.controllers.ArchiveController.java

License:Open Source License

@BusAddress("entcore.export")
public void export(Message<JsonObject> message) {
    String action = message.body().getString("action", "");
    switch (action) {
    case "exported":
        exportService.exported(message.body().getString("exportId"), message.body().getString("status"),
                message.body().getString("locale", "fr"),
                message.body().getString("host", config.getString("host", "")));
        break;//  ww w .j  a  v  a  2  s. c o  m
    default:
        log.error("Archive : invalid action " + action);
    }
}

From source file:org.entcore.archive.services.impl.FileSystemExportService.java

License:Open Source License

private void sendExportEmail(final String exportId, final String locale, final String status,
        final String host) {
    final String userId = getUserId(exportId);
    String query = "MATCH (u:User {id : {userId}}) RETURN u.email as email ";
    JsonObject params = new JsonObject().put("userId", userId);
    Neo4j.getInstance().execute(query, params, new Handler<Message<JsonObject>>() {
        @Override/*  w  w w . j a  v  a  2s.  com*/
        public void handle(Message<JsonObject> event) {
            JsonArray res = event.body().getJsonArray("result");
            if ("ok".equals(event.body().getString("status")) && res != null && res.size() == 1) {
                JsonObject e = res.getJsonObject(0);
                String email = e.getString("email");
                if (email != null && !email.trim().isEmpty()) {
                    HttpServerRequest r = new JsonHttpServerRequest(
                            new JsonObject().put("headers", new JsonObject().put("Accept-Language", locale)));
                    String subject, template;
                    JsonObject p = new JsonObject();
                    if ("ok".equals(status)) {
                        subject = "email.export.ok";
                        template = "email/export.ok.html";
                        p.put("download", host + "/archive/export/" + exportId);
                        if (log.isDebugEnabled()) {
                            log.debug(host + "/archive/export/" + exportId);
                        }
                    } else {
                        subject = "email.export.ko";
                        template = "email/export.ko.html";
                    }
                    notification.sendEmail(r, email, null, null, subject, template, p, true,
                            handlerToAsyncHandler(new Handler<Message<JsonObject>>() {
                                @Override
                                public void handle(Message<JsonObject> event) {
                                    if (event == null || !"ok".equals(event.body().getString("status"))) {
                                        log.error("Error sending export email for user " + userId);
                                    }
                                }
                            }));
                } else {
                    log.info("User " + userId + " hasn't email.");
                }
            } else if (res != null) {
                log.warn("User " + userId + " not found.");
            } else {
                log.error("Error finding user " + userId + " email : " + event.body().getString("message"));
            }
        }
    });
}

From source file:org.entcore.auth.controllers.AuthController.java

License:Open Source License

@BusAddress("wse.oauth")
public void oauthResourceServer(final Message<JsonObject> message) {
    if (message.body() == null) {
        message.reply(new JsonObject());
        return;/* w  ww  .  j  a  v a  2  s  . c  om*/
    }
    validToken(message);
}

From source file:org.entcore.auth.controllers.AuthController.java

License:Open Source License

private void validToken(final Message<JsonObject> message) {
    protectedResource.handleRequest(new JsonRequestAdapter(message.body()),
            new jp.eisbahn.oauth2.server.async.Handler<Try<OAuthError, ProtectedResource.Response>>() {

                @Override//w ww  .ja v a 2s.c om
                public void handle(Try<OAuthError, ProtectedResource.Response> resp) {
                    ProtectedResource.Response response;
                    try {
                        response = resp.get();
                        JsonObject r = new JsonObject().put("status", "ok")
                                .put("client_id", response.getClientId())
                                .put("remote_user", response.getRemoteUser()).put("scope", response.getScope());
                        message.reply(r);
                    } catch (OAuthError e) {
                        message.reply(new JsonObject().put("error", e.getType()));
                    }
                }
            });
}

From source file:org.entcore.auth.controllers.SamlController.java

License:Open Source License

@Post("/saml/acs")
public void acs(final HttpServerRequest request) {
    validateResponseAndGetAssertion(request, new Handler<Assertion>() {
        @Override//from w  w  w  .j a v a2 s .co  m
        public void handle(final Assertion assertion) {
            SamlServiceProvider sp = spFactory.serviceProvider(assertion);
            sp.execute(assertion, new Handler<Either<String, Object>>() {
                @Override
                public void handle(final Either<String, Object> event) {
                    if (event.isLeft()) {
                        loginResult(request, "fed.auth.error.user.not.found");
                    } else {
                        final String nameIdFromAssertion = getNameId(assertion);
                        final String sessionIndex = getSessionId(assertion);
                        if (log.isDebugEnabled()) {
                            log.debug("NameID : " + nameIdFromAssertion);
                            log.debug("SessionIndex : " + sessionIndex);
                        }
                        if (nameIdFromAssertion == null || sessionIndex == null
                                || nameIdFromAssertion.trim().isEmpty() || sessionIndex.trim().isEmpty()) {
                            redirect(request, LOGIN_PAGE);
                            return;
                        }

                        // if user is already authenticated in the ENT through the ENT login page, we do not authenticate him again
                        // because this will store the "nameid"

                        // ALGORITHM RULE :
                        // if user has "nameId" : it means user connected first with a federated idp
                        // else he connected to the ENT through the ENT login page
                        // this way we know if we need to disonnect/redirect the user to the federated login/home page OR
                        // if we only disconnect him to the ENT (no nameid)
                        final String sessionId = CookieHelper.getInstance().getSigned("oneSessionId", request);

                        //                     final JsonObject query = new JsonObject().put("_id", sessionId);
                        //                     mongo.findOne(SESSIONS_COLLECTION, query, new io.vertx.core.Handler<Message<JsonObject>>() {
                        federationService.getMongoDbSession(sessionId,
                                new io.vertx.core.Handler<Message<JsonObject>>() {
                                    @Override
                                    public void handle(Message<JsonObject> eventMongo) {
                                        JsonObject res = eventMongo.body().getJsonObject("result");
                                        String userId;
                                        if ("ok".equals(eventMongo.body().getString("status")) && res != null
                                                && (userId = res.getString("userId")) != null
                                                && !userId.trim().isEmpty()) {

                                            String nameID = res.getString("NameID");

                                            String userIdAssertion = null;
                                            if (event.right().getValue() != null
                                                    && event.right().getValue() instanceof JsonObject) {
                                                userIdAssertion = ((JsonObject) event.right().getValue())
                                                        .getString("id");
                                            }

                                            // no NameID and same userId : user already connected through IDP ENT
                                            if ((nameID == null || nameID.trim().isEmpty())
                                                    && userIdAssertion != null
                                                    && userIdAssertion.equals(userId)) {
                                                redirect(request, "/");
                                            } else {
                                                endAcs(request, event, sessionIndex, nameIdFromAssertion);
                                            }
                                        } else {
                                            endAcs(request, event, sessionIndex, nameIdFromAssertion);
                                        }
                                    }
                                });
                    }
                }
            });
        }
    });
}

From source file:org.entcore.auth.controllers.SamlController.java

License:Open Source License

private void validateResponseAndGetAssertion(final HttpServerRequest request,
        final Handler<Assertion> handler) {
    getSamlResponse(request, new Handler<String>() {
        @Override/*from   w w  w . j a v  a2 s . c  o m*/
        public void handle(final String samlResponse) {
            if (samlResponse != null && samlResponse.contains("EncryptedAssertion")) {
                JsonObject j = new JsonObject().put("action", "validate-signature-decrypt").put("response",
                        samlResponse);
                vertx.eventBus().send("saml", j, handlerToAsyncHandler(new Handler<Message<JsonObject>>() {
                    @Override
                    public void handle(Message<JsonObject> event) {
                        String assertion = event.body().getString("assertion");
                        if ("ok".equals(event.body().getString("status"))
                                && event.body().getBoolean("valid", false) && assertion != null) {
                            try {
                                handler.handle(SamlUtils.unmarshallAssertion(assertion));
                            } catch (Exception e) {
                                log.error(e.getMessage(), e);
                                redirect(request, LOGIN_PAGE);
                            }
                        } else {
                            redirect(request, LOGIN_PAGE);
                        }
                    }
                }));
            } else if (samlResponse != null) {
                JsonObject j = new JsonObject().put("action", "validate-signature").put("response",
                        samlResponse);
                vertx.eventBus().send("saml", j, handlerToAsyncHandler(new Handler<Message<JsonObject>>() {
                    @Override
                    public void handle(Message<JsonObject> event) {
                        if ("ok".equals(event.body().getString("status"))
                                && event.body().getBoolean("valid", false)) {
                            try {
                                Response response = SamlUtils.unmarshallResponse(samlResponse);
                                if (response.getAssertions() == null || response.getAssertions().size() != 1) {
                                    redirect(request, LOGIN_PAGE);
                                    return;
                                }
                                handler.handle(response.getAssertions().get(0));
                            } catch (Exception e) {
                                log.error(e.getMessage(), e);
                                redirect(request, LOGIN_PAGE);
                            }
                        } else {
                            redirect(request, LOGIN_PAGE);
                        }
                    }
                }));
            } else {
                redirect(request, LOGIN_PAGE);
            }
        }
    });
}

From source file:org.entcore.auth.oauth.OAuthDataHandler.java

License:Open Source License

@Override
public void validateClient(String clientId, String clientSecret, String grantType,
        final Handler<Boolean> handler) {

    String query = "MATCH (n:Application) " + "WHERE n.name = {clientId} " + "AND n.secret = {secret} ";
    if (!"refresh_token".equals(grantType)) {
        query += " AND n.grantType = {grantType} ";
    }/*w ww . ja v  a  2  s.co m*/
    query += "RETURN count(n) as nb";
    Map<String, Object> params = new HashMap<>();
    params.put("clientId", clientId);
    params.put("secret", clientSecret);
    params.put("grantType", grantType);
    neo.execute(query, params, new io.vertx.core.Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> res) {
            JsonArray a = res.body().getJsonArray("result");
            if ("ok".equals(res.body().getString("status")) && a != null && a.size() == 1) {
                JsonObject r = a.getJsonObject(0);
                handler.handle(r != null && r.getInteger("nb") == 1);
            } else {
                handler.handle(false);
            }
        }
    });

}

From source file:org.entcore.auth.oauth.OAuthDataHandler.java

License:Open Source License

@Override
public void getUserId(final String username, final String password, final Handler<String> handler) {
    if (username != null && password != null && !username.trim().isEmpty() && !password.trim().isEmpty()) {
        String query = "MATCH (n:User) " + "WHERE n.login={login} AND NOT(n.password IS NULL) "
                + "AND (NOT(HAS(n.blocked)) OR n.blocked = false) ";
        if (checkFederatedLogin) {
            query += "AND (NOT(HAS(n.federated)) OR n.federated = false) ";
        }/*www.  j  av  a  2s .c  o m*/
        query += "OPTIONAL MATCH (p:Profile) " + "WHERE HAS(n.profiles) AND p.name = head(n.profiles) "
                + "RETURN DISTINCT n.id as userId, n.password as password, p.blocked as blockedProfile";
        Map<String, Object> params = new HashMap<>();
        params.put("login", username);
        neo.execute(query, params, new io.vertx.core.Handler<Message<JsonObject>>() {

            @Override
            public void handle(Message<JsonObject> res) {
                JsonArray result = res.body().getJsonArray("result");
                if ("ok".equals(res.body().getString("status")) && result != null && result.size() == 1) {
                    checkPassword(result, password, username, handler);
                } else {
                    getUserIdByLoginAlias(username, password, handler);
                }
            }
        });
    } else {
        handler.handle(null);
    }
}