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

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

Introduction

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

Prototype

public String getString(String key) 

Source Link

Document

Get the string value with the specified key, special cases are addressed for extended JSON types Instant , byte[] and Enum which can be converted to String.

Usage

From source file:fr.wseduc.webdav.WebDav.java

License:Apache License

private Sardine getSardine(String uri, Message<JsonObject> message) {
    String host;/*  ww w. j a v a2  s . c o m*/
    try {
        host = new URI(uri).getHost();
    } catch (URISyntaxException e) {
        sendError(message, e.getMessage(), e);
        return null;
    }
    JsonObject credential = credentials.getJsonObject(host);
    Sardine sardine;
    if (credential != null) {
        if (credential.getBoolean("insecure", false)) {
            sardine = new SardineImpl() {
                @Override
                protected ConnectionSocketFactory createDefaultSecureSocketFactory() {
                    SSLConnectionSocketFactory sf = null;
                    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }

                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] certs,
                                String authType) {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] certs,
                                String authType) {
                        }
                    } };
                    try {
                        SSLContext context = SSLContext.getInstance("TLS");
                        context.init(null, trustAllCerts, null);

                        sf = new SSLConnectionSocketFactory(context,
                                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                    } catch (NoSuchAlgorithmException | KeyManagementException e) {
                        logger.error(e.getMessage(), e);
                    }
                    return sf;
                }
            };
            sardine.setCredentials(credential.getString("username"), credential.getString("password"));
        } else {
            sardine = SardineFactory.begin(credential.getString("username"), credential.getString("password"));
        }
        sardine.enablePreemptiveAuthentication(host);
    } else {
        sardine = SardineFactory.begin();
    }
    return sardine;
}

From source file:hu.elte.ik.robotika.futar.vertx.backend.verticle.HTTPVerticle.java

private SockJSHandler eventBusHandler() {
    BridgeOptions options = new BridgeOptions()
            .addOutboundPermitted(new PermittedOptions().setAddressRegex("new.robot"));
    options.addOutboundPermitted(new PermittedOptions().setAddressRegex("logout.robot"));
    options.addOutboundPermitted(new PermittedOptions().setAddressRegex("new.bt.device"));
    options.addOutboundPermitted(new PermittedOptions().setAddressRegex("placed.bt.device"));
    options.addOutboundPermitted(new PermittedOptions().setAddressRegex("robot.position"));
    options.addInboundPermitted(new PermittedOptions().setAddressRegex("login.robot"));
    options.addInboundPermitted(new PermittedOptions().setAddressRegex("login.client"));
    options.addInboundPermitted(new PermittedOptions().setAddressRegex("robot.\\.[0-9]+"));
    options.addInboundPermitted(new PermittedOptions().setAddressRegex("place.bt.device"));
    // use this to send message to the clients:
    // routingContext.vertx().eventBus().publish("muhaha", routingContext.getBodyAsString());
    return SockJSHandler.create(vertx).bridge(options, event -> {
        if (event.type() == BridgeEventType.SOCKET_CREATED) {
            log.info("A socket was created");
        }//from w ww  .j  a  v  a  2 s .c  o  m
        if (event.type() == BridgeEventType.SOCKET_CLOSED) {
            log.info("A socket was closed");
            if (activeRobots.contains(event.socket().writeHandlerID())) {
                log.info("Robot logged out");
                activeRobots.remove(event.socket().writeHandlerID());
                JsonObject response = new JsonObject();
                response.put("robotId", event.socket().writeHandlerID());
                vertx.eventBus().publish("logout.robot", Json.encode(response));
            }
        }
        if (event.type() == BridgeEventType.REGISTER) {
            log.info("A handler was registered");
            log.info(event.rawMessage());
        }
        if (event.type() == BridgeEventType.SEND) {
            log.info("Client sent a message: " + event.rawMessage());
            if (event.rawMessage().getString("address").equals("login.robot")
                    && !activeRobots.contains(event.socket().writeHandlerID())) {
                log.info("Robot logged in");
                activeRobots.add(event.socket().writeHandlerID());
                JsonObject response = new JsonObject();
                response.put("robotId", event.socket().writeHandlerID());
                vertx.eventBus().publish("new.robot", Json.encode(response));
            } else if (event.rawMessage().getString("address").equals("login.robot")) {
                log.info("Robot already logged in");
            }

            if (event.rawMessage().getString("address").equals("login.client")) {
                for (String key : sockets.keySet()) {
                    log.info("Send active robots");
                    JsonObject response = new JsonObject();
                    response.put("robotId", key);
                    vertx.eventBus().publish("new.robot", Json.encode(response));
                }

                for (JsonObject value : placedBTDevices.values()) {
                    vertx.eventBus().publish("placed.bt.device", Json.encode(value));
                }

                for (JsonObject value : newBTDevices.values()) {
                    vertx.eventBus().publish("new.bt.device", Json.encode(value));
                }

                for (JsonObject value : positionedRobots.values()) {
                    vertx.eventBus().publish("robot.position", Json.encode(value));
                }
            }

            if (event.rawMessage().getString("address").equals("place.bt.device")) {

                JsonObject data = event.rawMessage().getJsonObject("body");
                log.info("Place bt device: " + data.getString("address"));
                placedBTDevices.remove(data.getString("address"));
                placedBTDevices.put(data.getString("address"), data);
                newBTDevices.remove(data.getString("address"));
                vertx.eventBus().publish("placed.bt.device", Json.encode(data));
            }
        }
        event.complete(true);
    });
}

From source file:hu.elte.ik.robotika.futar.vertx.backend.verticle.HTTPVerticle.java

@Override
public void start() {

    init();//  w  w  w.  j  a  v a  2s .  c  o  m
    HttpServer http = vertx.createHttpServer();
    Router router = Router.router(vertx);

    // Setup websocket connection handling
    router.route("/eventbus/*").handler(eventBusHandler());

    router.route("/ws").handler(this::handleWebSocketConnection);

    // Handle robot position data
    router.route("/api/robotposition/:data").handler(this::handleRobotPositionData);

    // Setup http session auth handling
    router.route().handler(CookieHandler.create());
    router.route().handler(BodyHandler.create());
    router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx)));

    // Simple auth service which uses a properties file for user/role info
    AuthProvider authProvider = ShiroAuth.create(vertx, ShiroAuthRealmType.PROPERTIES, new JsonObject());

    // We need a user session handler too to make sure the user is stored in
    // the session between requests
    router.route().handler(UserSessionHandler.create(authProvider));

    // Any requests to URI starting '/rest/' require login
    router.route("/rest/*").handler(SimpleAuthHandler.create(authProvider));

    // Serve the static private pages from directory 'rest'
    // user/getAll TEST page
    router.route("/rest/user/getAll").handler(this::getAllUser);

    // Preload
    router.route("/rest/info").handler(this::getInfo);

    router.route("/loginhandler").handler(SimpleLoginHandler.create(authProvider));

    router.route("/logout").handler(context -> {
        context.clearUser();
        // Status OK
        context.response().setStatusCode(HttpStatus.SC_OK).end();
    });

    router.route().handler(StaticHandler.create().setWebRoot(webRoot));
    http.websocketHandler(ws -> {
        String id = java.util.UUID.randomUUID().toString();
        ws.handler(buffer -> {
            try {
                JsonObject response = new JsonObject(buffer.toString());
                if (response.getString("action") != null && response.getString("action").equals("login.robot")
                        && sockets.get(id) == null) {
                    log.info("robot logged in:" + id);
                    sockets.put(id, ws);
                    JsonObject pb = new JsonObject();
                    pb.put("robotId", id);
                    vertx.eventBus().publish("new.robot", Json.encode(pb));
                } else if (response.getString("action") != null
                        && response.getString("action").equals("found.bluetooth")) {
                    log.info("found.bluetooth");
                    JsonObject pb = response.getJsonObject("data");
                    if (placedBTDevices.get(pb.getString("address")) == null
                            && newBTDevices.get(pb.getString("address")) == null) {
                        JsonObject data = new JsonObject(Json.encode(pb));
                        data.remove("rssi");
                        newBTDevices.put(pb.getString("address"), data);
                        log.info("New bt device: " + buffer);
                        vertx.eventBus().publish("new.bt.device", Json.encode(data));
                    }

                    btData.get(id).remove(pb.getString("address"));

                    log.info("Update bt data: " + id + " " + pb.getString("address") + " "
                            + pb.getInteger("rssi"));
                    double x = (pb.getInteger("rssi") - (-40.0)) / ((-10.0) * 2.0);
                    log.info("sub calc res: " + x);
                    double d = Math.pow(10.0, x);
                    //RSSI (dBm) = -10n log10(d) + A
                    log.info("the calculated distance is around: " + d + "m");
                    btData.get(id).put(pb.getString("address"), d * 27);
                } else if (response.getString("action") != null
                        && response.getString("action").equals("start.bluetooth.scan")) {
                    log.info("start.bluetooth.scan");
                    btData.remove(id);
                    btData.put(id, new LinkedHashMap<String, Double>());

                } else if (response.getString("action") != null
                        && response.getString("action").equals("finished.bluetooth.scan")) {
                    log.info("finished.bluetooth.scan");
                    if (btData.get(id).size() >= 3) {
                        double x0 = 0, y0 = 0, r0 = 0, x1 = 0, y1 = 0, r1 = 0, x2 = 0, y2 = 0, r2 = 0;
                        int i = 0;
                        for (Map.Entry<String, Double> entry : btData.get(id).entrySet()) {
                            String key = entry.getKey();
                            JsonObject placedBT = placedBTDevices.get(key);
                            if (placedBT == null) {
                                log.info("placedBT is null, the key was: " + key);
                                continue;
                            }
                            double value = entry.getValue();
                            if (i == 0) {

                                x0 = placedBT.getDouble("x");
                                y0 = placedBT.getDouble("y");
                                r0 = value;
                                log.info("fill first circle x: " + x0 + " y: " + y0 + " r: " + r0);
                            } else if (i == 1) {

                                x1 = placedBT.getDouble("x");
                                y1 = placedBT.getDouble("y");
                                r1 = value;
                                log.info("fill second circle x: " + x1 + " y: " + y1 + " r: " + r1);
                            } else if (i == 2) {

                                x2 = placedBT.getDouble("x");
                                y2 = placedBT.getDouble("y");
                                r2 = value;
                                log.info("fill third circle x: " + x2 + " y: " + y2 + " r: " + r2);
                            } else {
                                break;
                            }
                            i++;
                        }

                        if (i == 3) {
                            log.info("start calculation");
                            if (calculateThreeCircleIntersection(x0, y0, r0, x1, y1, r1, x2, y2, r2, id)) {
                                log.info("solved circle intersection");
                            } else {
                                log.info("cannot solve circle interseciton");
                            }
                        } else {
                            log.info("there was not enough BT device: " + i);
                        }

                    } else {
                        log.info("There is not enough BT data to calculate the location of the robot.");
                    }
                }

                log.info("got the following message from " + id + ": " + Json.encode(response));

            } catch (Exception e) {
                log.info("Cannot process the following buffer: " + buffer);
                log.error(e);
            }
        });
        ws.endHandler(e -> {
            JsonObject response = new JsonObject();
            response.put("robotId", id);
            vertx.eventBus().publish("logout.robot", Json.encode(response));
            sockets.remove(id);
            positionedRobots.remove(id);
            btData.remove(id);
            log.info("The following robot logged out: " + id);
        });
    }).requestHandler(router::accept).listen(Integer.getInteger("http.port"),
            System.getProperty("http.address", "0.0.0.0"));
}

From source file:io.apiman.gateway.platforms.vertx3.api.auth.BasicAuth.java

License:Apache License

private static AuthProvider authenticateBasic(JsonObject apimanConfig) {
    return (authInfo, resultHandler) -> {
        String storedUsername = apimanConfig.getString("username");
        String storedPassword = apimanConfig.getString("password");

        if (storedUsername == null || storedPassword == null) {
            resultHandler.handle(Future.failedFuture("Credentials not set in configuration."));
            return;
        }/*from w w w .  ja  v a2  s  . c  o  m*/

        String username = authInfo.getString("username");
        String password = StringUtils.chomp(authInfo.getString("password"));

        if (storedUsername.equals(username) && storedPassword.equals(password)) {
            resultHandler.handle(Future.succeededFuture());
        } else {
            resultHandler.handle(Future.failedFuture("No such user, or password incorrect."));
        }
    };
}

From source file:io.apiman.gateway.platforms.vertx3.api.auth.KeycloakOAuthFactory.java

License:Apache License

public static AuthHandler create(Vertx vertx, Router router, VertxEngineConfig apimanConfig,
        JsonObject authConfig) {
    OAuth2FlowType flowType = toEnum(authConfig.getString("flowType"));
    String role = authConfig.getString("requiredRole");

    Objects.requireNonNull(flowType, String.format("flowType must be specified and valid. Flows: %s.",
            Arrays.asList(OAuth2FlowType.values())));
    Objects.requireNonNull(role, "requiredRole must be non-null.");

    if (flowType != OAuth2FlowType.AUTH_CODE) {
        return directGrant(vertx, apimanConfig, authConfig, flowType, role);
    } else {/*from   w  w w . j  a v  a 2s. c o m*/
        return standardAuth(vertx, router, apimanConfig, authConfig, flowType);
    }
}

From source file:io.apiman.gateway.platforms.vertx3.config.VertxEngineConfig.java

License:Apache License

public Map<String, String> getBasicAuthCredentials() {
    if (!basicAuthMap.isEmpty())
        return basicAuthMap;

    JsonObject pairs = config.getJsonObject(API_AUTH).getJsonObject("basic");

    for (String username : pairs.fieldNames()) {
        basicAuthMap.put(username, pairs.getString(username));
    }// w  ww . ja v  a  2s .c  o m

    return basicAuthMap;
}

From source file:io.engagingspaces.graphql.events.SchemaReferenceData.java

License:Open Source License

/**
 * Creates a new {@link SchemaReferenceData} from
 * its json representation./*w  w  w.  j  a va2s  .c  o  m*/
 *
 * @param json the json object
 */
public SchemaReferenceData(JsonObject json) {
    this.id = json.getString("id");
    this.record = new Record(json.getJsonObject("record"));
    this.status = "bind".equals(json.getValue("type")) ? Status.BOUND : Status.RELEASED;
}

From source file:io.engagingspaces.graphql.marshaller.schema.decorators.DataFetcherDO.java

License:Open Source License

private DataFetcherDO(DataFetcher dataFetcher, JsonObject dataFetcherJson, GraphQLFieldDefinition parent,
        SchemaContext schemaContext) {//w w w  .j a v  a 2  s  .co  m
    this.dataFetcherJson = dataFetcherJson;
    this.parent = parent;
    this.context = schemaContext;
    this.id = dataFetcherJson == null ? UUID.randomUUID().toString() : dataFetcherJson.getString(ID);
    if (dataFetcher == null) {
        if (id != null && context.getDataFetchers().containsKey(id)) {
            this.dataFetcher = context.getDataFetchers().get(id);
        } else {
            this.dataFetcher = (environment -> null);
        }
    } else {
        this.dataFetcher = dataFetcher;
    }
    if (dataFetcherJson == null) {
        this.staticValue = dataFetcher instanceof StaticDataFetcher
                ? new JsonObject().put(STATIC_VALUE, dataFetcher.get(null))
                : null;
    } else {
        this.staticValue = dataFetcherJson.getJsonObject(STATIC_VALUE);
    }
    this.jsonReference = context.registerDataFetcher(this);
}

From source file:io.engagingspaces.graphql.marshaller.schema.decorators.TypeResolverDO.java

License:Open Source License

private TypeResolverDO(TypeResolver resolver, JsonObject resolverJson, GraphQLType parent,
        SchemaContext context) {/*from ww w.  j  av  a  2  s.  c om*/
    this.resolverJson = resolverJson;
    this.parent = parent;
    this.context = context;
    this.id = resolverJson == null ? UUID.randomUUID().toString() : resolverJson.getString(PropNames.ID);
    if (resolver == null) {
        if (id != null && context.getTypeResolvers().containsKey(id)) {
            this.resolver = context.getTypeResolvers().get(id);
        } else {
            this.resolver = (object -> null);
        }
    } else {
        this.resolver = resolver;
    }
    this.jsonReference = context.registerTypeResolver(this);
}

From source file:io.engagingspaces.graphql.marshaller.schema.impl.SchemaContextImpl.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public <T extends SchemaDecorator, U extends SchemaDecorator> T dereference(Object jsonData, U parent) {
    if (decoratedTypes.containsKey(jsonData)) {
        return (T) decoratedTypes.get(jsonData);
    } else {/*from   w w  w. j a va  2s  .co  m*/
        JsonObject json = (JsonObject) jsonData;
        String reference = json.getString(REF_KEY);
        if (reference != null) {
            String[] referencePath = json.getString(REF_KEY).substring(ROOT_REFERENCE.length()).split(SLASH);
            json = rootJson;
            for (String ref : referencePath) {
                json = json.getJsonObject(ref);
            }
            return unmarshall(json, parent);
        }
    }
    return null;
}