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

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

Introduction

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

Prototype

public JsonObject() 

Source Link

Document

Create a new, empty instance

Usage

From source file:de.braintags.netrelay.controller.authentication.FormLoginHandlerBt.java

License:Open Source License

@Override
public void handle(RoutingContext context) {
    HttpServerRequest req = context.request();
    if (req.method() != HttpMethod.POST) {
        context.fail(405); // Must be a POST
    } else {//from   w w  w  .  j av  a  2s . c  o  m
        if (!req.isExpectMultipart()) {
            throw new IllegalStateException("Form body not parsed - did you forget to include a BodyHandler?");
        }
        MultiMap params = req.formAttributes();
        String username = params.get(usernameParam);
        String password = params.get(passwordParam);
        if (username == null || password == null) {
            LOGGER.warn("No username or password provided in form - did you forget to include a BodyHandler?");
            context.fail(400);
        } else {
            JsonObject authInfo = new JsonObject().put("username", username).put("password", password);
            authProvider.authenticate(authInfo, res -> {
                if (res.succeeded()) {
                    User user = res.result();
                    LOGGER.info("Login success, found user " + user);
                    MemberUtil.setContextUser(context, user);
                    if (redirectBySession(context)) {
                        return;
                    }
                    // Either no session or no return url
                    if (!redirectByDirectLoginUrl(context)) {
                        // Just show a basic page
                        req.response().end(DEFAULT_DIRECT_LOGGED_IN_OK_PAGE);
                    }
                } else {
                    LOGGER.info("authentication failed: " + res.cause());
                    handleAuthenticationError(context, res.cause());
                }
            });
        }
    }
}

From source file:de.braintags.netrelay.controller.authentication.RegisterController.java

License:Open Source License

private JsonObject getAuthObject(IAuthenticatable user, AuthProviderProxy proxy) {
    AuthProvider prov = proxy.getProvider();
    if (prov instanceof MongoAuthImpl) {
        JsonObject authInfo = new JsonObject();
        authInfo.put(((MongoAuthImpl) prov).getUsernameCredentialField(), user.getEmail())
                .put(((MongoAuthImpl) prov).getPasswordCredentialField(), user.getPassword());
        return authInfo;
    } else if (prov instanceof IDatastoreAuth) {
        JsonObject authInfo = new JsonObject();
        authInfo.put(IDatastoreAuth.CREDENTIAL_USERNAME_FIELD, user.getEmail())
                .put(IDatastoreAuth.CREDENTIAL_PASSWORD_FIELD, user.getPassword());
        return authInfo;
    }/*from   w  w  w.j a  v  a2 s.c  o  m*/
    throw new UnsupportedOperationException("Unsupported authprovider class: " + prov.getClass());
}

From source file:de.braintags.netrelay.controller.filemanager.elfinder.command.impl.AbstractCommand.java

License:Open Source License

private void doExecute(ElFinderContext efContext, Handler<AsyncResult<JsonObject>> handler) {
    JsonObject json = new JsonObject();
    try {/*from   www.j  ava  2 s  . co  m*/
        execute(efContext, json, res -> {
            if (res.failed()) {
                handler.handle(Future.failedFuture(res.cause()));
            } else {
                listenerAfter(efContext, json, res.result(), handler);
            }
        });
    } catch (Exception e) {
        handler.handle(Future.failedFuture(e));
    }
}

From source file:de.braintags.netrelay.controller.filemanager.elfinder.command.impl.AbstractCommand.java

License:Open Source License

protected JsonObject getTargetInfo(ElFinderContext efContext, ITarget target) {
    JsonObject info = new JsonObject();

    info.put(ElFinderConstants.ELFINDER_PARAMETER_HASH, target.getHash());
    info.put(ElFinderConstants.ELFINDER_PARAMETER_MIME, target.getMimeType());
    info.put(ElFinderConstants.ELFINDER_PARAMETER_TIMESTAMP, target.getLastModified());
    info.put(ElFinderConstants.ELFINDER_PARAMETER_SIZE, target.getSize());
    info.put(ElFinderConstants.ELFINDER_PARAMETER_READ,
            target.isReadable() ? ElFinderConstants.ELFINDER_TRUE_RESPONSE
                    : ElFinderConstants.ELFINDER_FALSE_RESPONSE);
    info.put(ElFinderConstants.ELFINDER_PARAMETER_WRITE,
            target.isWritable() ? ElFinderConstants.ELFINDER_TRUE_RESPONSE
                    : ElFinderConstants.ELFINDER_FALSE_RESPONSE);
    info.put(ElFinderConstants.ELFINDER_PARAMETER_LOCKED,
            target.isLocked() ? ElFinderConstants.ELFINDER_TRUE_RESPONSE
                    : ElFinderConstants.ELFINDER_FALSE_RESPONSE);

    if (target.getMimeType() != null && target.getMimeType().startsWith("image")) {
        String uri = efContext.getRoutingContext().request().absoluteURI()
                + String.format(CMD_TMB_TARGET, target.getHash());
        info.put(ElFinderConstants.ELFINDER_PARAMETER_THUMBNAIL, uri);
    }/*from  w w  w  . j a  v  a  2 s  .com*/

    if (target.isRoot()) {
        info.put(ElFinderConstants.ELFINDER_PARAMETER_DIRECTORY_FILE_NAME, target.getVolume().getAlias());
        info.put(ElFinderConstants.ELFINDER_PARAMETER_VOLUME_ID, target.getVolume().getId());
    } else {
        info.put(ElFinderConstants.ELFINDER_PARAMETER_DIRECTORY_FILE_NAME, target.getName());
        info.put(ElFinderConstants.ELFINDER_PARAMETER_PARENTHASH, target.getParent().getHash());
    }

    if (target.isFolder()) {
        info.put(ElFinderConstants.ELFINDER_PARAMETER_HAS_DIR,
                target.hasChildFolder() ? ElFinderConstants.ELFINDER_TRUE_RESPONSE
                        : ElFinderConstants.ELFINDER_FALSE_RESPONSE);
    }
    return info;
}

From source file:de.braintags.netrelay.controller.filemanager.elfinder.command.impl.AbstractCommand.java

License:Open Source License

protected JsonObject getOptions(ElFinderContext efContext, ITarget target) {
    JsonObject options = new JsonObject();
    options.put(ElFinderConstants.ELFINDER_PARAMETER_PATH, target.getName());
    options.put(ElFinderConstants.ELFINDER_PARAMETER_COMMAND_DISABLED, new JsonArray());
    options.put(ElFinderConstants.ELFINDER_PARAMETER_FILE_SEPARATOR,
            ElFinderConstants.ELFINDER_PARAMETER_FILE_SEPARATOR);
    options.put(ElFinderConstants.ELFINDER_PARAMETER_OVERWRITE_FILE, ElFinderConstants.ELFINDER_TRUE_RESPONSE);
    // options.put(ElFinderConstants.ELFINDER_PARAMETER_ARCHIVERS, ArchiverOption.JSON_INSTANCE);
    return options;
}

From source file:de.elsibay.EbbTicketShowcase.java

License:Open Source License

@Override
public void start(Future<Void> startFuture) throws Exception {

    SessionStore sessionStore = LocalSessionStore.create(vertx);
    Router backendRouter = Router.router(vertx);
    backendRouter.route().handler(LoggerHandler.create(LoggerHandler.DEFAULT_FORMAT));
    CookieHandler cookieHandler = CookieHandler.create();
    SessionHandler sessionHandler = SessionHandler.create(sessionStore);
    // the CORS OPTION request must not set cookies
    backendRouter.get().handler(cookieHandler);
    backendRouter.get().handler(sessionHandler);
    backendRouter.post().handler(cookieHandler);
    backendRouter.post().handler(sessionHandler);

    // setup CORS
    CorsHandler corsHandler = CorsHandler.create("http(s)?://" + WEBSERVER_HOST + ":" + WEBSERVER_PORT)
            .allowCredentials(true).allowedHeader(HttpHeaders.ACCEPT.toString())
            .allowedHeader(HttpHeaders.ORIGIN.toString()).allowedHeader(HttpHeaders.AUTHORIZATION.toString())
            .allowedHeader(HttpHeaders.CONTENT_TYPE.toString()).allowedHeader(HttpHeaders.COOKIE.toString())
            .exposedHeader(HttpHeaders.SET_COOKIE.toString()).allowedMethod(HttpMethod.POST)
            .allowedMethod(HttpMethod.PUT).allowedMethod(HttpMethod.GET).allowedMethod(HttpMethod.DELETE);

    // setup event bus bridge
    TicketEventbusBridge sebb = new TicketEventbusBridge(sessionStore);
    backendRouter.mountSubRouter("/eventbus", sebb.route(vertx));

    // dummy eventbus services
    vertx.eventBus().consumer("ping", (Message<JsonObject> msg) -> {
        msg.reply(new JsonObject().put("answer", "pong " + msg.body().getString("text", "")));
    });//  w w w . ja  v a 2s.c o m

    vertx.setPeriodic(5000, id -> {
        vertx.eventBus().send("topic", new JsonObject().put("timestamp", new Date().getTime()));
    });

    // session manager for login
    backendRouter.route("/api/*").handler(corsHandler);
    backendRouter.route("/api/*").method(HttpMethod.POST).method(HttpMethod.PUT).handler(BodyHandler.create());

    backendRouter.route("/api/session").handler((RoutingContext rc) -> {
        JsonObject user = rc.getBodyAsJson();
        String sessionId = rc.session().id();
        rc.session().put("user", user);
        rc.response().end(user.copy().put("sessionId", sessionId).encodePrettily());
    });

    // dummy ping REST service
    backendRouter.route("/api/ping").handler((RoutingContext rc) -> {
        JsonObject replyMsg = new JsonObject();
        replyMsg.put("timestamp", new Date().getTime());
        Cookie sessionCookie = rc.getCookie(SessionHandler.DEFAULT_SESSION_COOKIE_NAME);
        if (sessionCookie != null) {
            replyMsg.put("sessionId", sessionCookie.getValue());
        }
        rc.response().end(replyMsg.encode());
    });

    // start backend on one port
    vertx.createHttpServer().requestHandler(backendRouter::accept).listen(BACKENDSERVER_PORT,
            BACKENDSERVER_HOST, (AsyncResult<HttpServer> async) -> {
                System.out
                        .println(async.succeeded() ? "Backend Server started" : "Backend Server start FAILED");
            });

    // static files on other port
    Router staticFilesRouter = Router.router(vertx);
    staticFilesRouter.route("/*").handler(StaticHandler.create("src/main/www").setCachingEnabled(false));
    vertx.createHttpServer().requestHandler(staticFilesRouter::accept).listen(WEBSERVER_PORT, WEBSERVER_HOST,
            (AsyncResult<HttpServer> async) -> {
                System.out.println(async.succeeded()
                        ? "Web Server started\ngoto http://" + WEBSERVER_HOST + ":" + WEBSERVER_PORT + "/"
                        : "Web Server start FAILED");
            });
}

From source file:de.fraunhofer.fokus.redistest.DoInterestingThings.java

License:Creative Commons License

public void doIt(final Vertx vertx, final JsonObject redisConfig, String uuid, Logger logger,
        Handler<AsyncResult<JsonArray>> handler) {
    String zSetName = String.format(ZSET_NAME_FORMAT, uuid);
    final RangeLimitOptions rangeLimitOptions = (RangeLimitOptions) new RangeLimitOptions().setLimit(0,
            Constants.MAX_SEARCH_RESULTS);

    /*//ww  w .  jav a 2s .  c om
     * To prevent errors in streams due to empty result set and to enable subscription
     * a dummy element will be prepended to the result set and removed in the subscription
     */
    final List<JsonArray> secureResultList = new ArrayList<JsonArray>();
    secureResultList.add(new JsonArray().add("default"));

    Single.using(DisposableRedisConnection::new, f -> f.create(vertx, redisConfig, logger), f -> f.dispose())
            .subscribe(redisClient -> {
                // emulate searech time in database
                //               vertx.setTimer(40,  xx->{
                Observable.range(1, 40)
                        .map(x -> new JsonObject().put(Constants.KEY_TYPE, Constants.KEY_DICE_OBJECT)
                                .put(Constants.KEY_RECORD_ID, String.valueOf(x))
                                .put(Constants.KEY_DICE_VALUE, x * 0.1).put(Constants.KEY_FAMILYNAME, x * 0.1)
                                .put(Constants.KEY_FIRSTNAME, 1))
                        .filter(x -> x != null) //remove results where comparison has been stopped due to bad dice values
                        // side effect - store objects in redis   
                        .subscribe(res -> {
                            String handle = res.getString(Constants.KEY_RECORD_ID);
                            String hashName = String.format(HASH_NAME_FORMAT, handle);
                            Single.zip(
                                    redisClient.rxZadd(zSetName, res.getDouble(Constants.KEY_DICE_VALUE),
                                            handle),
                                    redisClient.rxExpire(hashName, Constants.EXPIRE_AFTER),
                                    redisClient.rxHmset(hashName, res), (a, b, c) -> {
                                        return res;
                                    }).subscribe(r -> {
                                        // do nothing
                                    }, t -> handler.handle(Future.failedFuture(t)));
                        }, t -> handler.handle(Future.failedFuture(t)), () -> { //set expiration and retrieve record_ids
                            Observable
                                    .zip(redisClient.rxExpire(zSetName, Constants.EXPIRE_AFTER).toObservable(), // set expiration
                                            redisClient
                                                    .rxZrevrangebyscore(zSetName, "1", "0", rangeLimitOptions)
                                                    .toObservable(), // list of record_ids as JsonArray
                                            (a, b) -> Observable.from(b))
                                    .flatMap(x -> x)
                                    .map(handle -> redisClient
                                            .rxHgetall(String.format(HASH_NAME_FORMAT, handle)).toObservable()) // retrieve hash from redis
                                    .flatMap(x -> x).map(json -> toEntry(json))
                                    .collect(() -> new JsonArray(), (eList, e) -> eList.add(e))
                                    .subscribe(collectedJson -> handler
                                            .handle(Future.succeededFuture(collectedJson)), t -> {
                                                System.out.println("XXXX: " + t);
                                                logger.error("XXX", t);
                                                handler.handle(Future.failedFuture(t));
                                            });
                            //                        });
                        });
            }, t -> {
                CharArrayWriter cw = new CharArrayWriter();
                PrintWriter w = new PrintWriter(cw);
                t.printStackTrace(w);
                w.close();
                logger.error("trace", cw.toString());
                logger.error("YYY", t);
                handler.handle(Future.failedFuture(t));
            });

}

From source file:de.neofonie.deployer.DeployerVerticle.java

License:Open Source License

/**
 * Start the deployer.//from w ww .  j  av  a2  s. c o m
 *
 * @param startFuture
 */
@Override
public void start(final Future<Void> startFuture) {

    // load the deployer.json when available
    JsonObject configuration = this.loadConfiguration();

    if (configuration != null) {

        deployed = new JsonArray();

        // assign loopback to this handler
        vertx.eventBus().localConsumer(LOOPBACK, this::deployVerticle);

        // copy the current verticle configuration
        workingCopy = configuration.getJsonObject(VERTICLES, new JsonObject()).copy();

        // set the global configuration
        globalConfig = configuration.getJsonObject(CONFIG, new JsonObject());

        // start iterations
        vertx.eventBus().send(LOOPBACK, null, (AsyncResult<Message<Boolean>> event) -> {
            if (event.succeeded() && event.result().body()) {
                LOG.log(Level.INFO, "Deployed {0} Verticles: {1}",
                        new Object[] { this.deployed.size(), deployed });
                startFuture.complete();
            } else {
                LOG.log(Level.SEVERE, "Deployment stopped: {0}", event.cause().getMessage());
                startFuture.fail(event.cause());
            }
        });
    } else {
        LOG.info("No deployer.json found on the classpath.");
    }
}

From source file:de.neofonie.deployer.DeployerVerticle.java

License:Open Source License

/**
 * Iterate and deploy verticles//www.  j ava2s  . c o  m
 */
private void deployVerticle(final Message<JsonObject> event) {

    // iterate over all candidates to be deployed
    Set<String> candidates = this.workingCopy.fieldNames();

    // detach from underlying json
    Map<String, JsonObject> initiants = new HashMap<>();
    candidates.forEach(id -> {
        JsonObject info = this.workingCopy.getJsonObject(id);
        JsonArray dependsOn = info.getJsonArray("dependsOn");
        if (dependsOn != null && deployed.getList().containsAll(dependsOn.getList()) || dependsOn == null
                || dependsOn.isEmpty()) {
            initiants.put(id, info);
        }
    });

    // remove the initiants
    initiants.keySet().forEach(id -> this.workingCopy.remove(id));

    // setup latch for the reply
    CountDownLatch latch = new CountDownLatch(initiants.size());
    if (initiants.isEmpty()) {
        event.reply(Boolean.TRUE);
        return;
    }

    // run over all dependencies
    initiants.forEach((id, info) -> {

        // get the name of the verticle
        String name = info.getString("name");
        final JsonObject localConfig = new JsonObject();
        localConfig.mergeIn(globalConfig);
        localConfig.mergeIn(info.getJsonObject("config", new JsonObject()));

        Handler<AsyncResult<String>> handler = innerEvent -> {
            if (innerEvent.succeeded()) {
                // add service to deployed-list
                deployed.add(id);

                // re-emit
                vertx.eventBus().send(LOOPBACK, workingCopy, (AsyncResult<Message<Boolean>> recursiveReply) -> {
                    // always decrease latch
                    latch.countDown();

                    if (recursiveReply.succeeded() && recursiveReply.result().body()) {
                        if (latch.getCount() == 0) {
                            event.reply(recursiveReply.result().body() & Boolean.TRUE);
                        }
                    } else {
                        event.fail(500, this.getFailure(id, recursiveReply));
                    }
                });

            } else {
                event.fail(500, id + " >> " + innerEvent.cause().getMessage());
            }
        };

        LOG.log(Level.INFO, "Deploying: ''{0}''", new Object[] { id });
        DeploymentOptions deploymentOptions = new DeploymentOptions(info);
        vertx.deployVerticle(name, deploymentOptions.setConfig(localConfig), handler);
    });
}

From source file:de.notizwerk.Consumer.java

License:Open Source License

@Override
public void start(Future<Void> startFuture) throws Exception {

    setUpFileSystem(v -> {//from  w w w.j  av  a  2  s.co  m
        vertx.eventBus().consumer("consumer", (Message<JsonObject> msg) -> {
            messagesInTick++;
            receivedMessages++;
            file.write(Buffer.buffer(msg.body().encode()));
            msg.reply("ok");
        });
        vertx.setPeriodic(REPORT_DELAY_IN_MSEC, (id) -> {
            long messageRate = Math.floorDiv(messagesInTick * 1000, REPORT_DELAY_IN_MSEC);
            messagesInTick = 0;
            JsonObject stats = new JsonObject().put("name", name).put("id", name)
                    .put("timestamp", AppStarter.TIME_FORMATTER.format(ZonedDateTime.now()))
                    .put("messageRate", messageRate).put("receivedMessages", receivedMessages);
            file.write(Buffer.buffer(stats.encode() + String.format("%n")));
            vertx.eventBus().publish("consumer.stats", stats);
        });
        startFuture.complete();
    });
}