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:org.sfs.auth.SimpleAuthProvider.java

License:Apache License

@Override
public Observable<Void> open(VertxContext<Server> vertxContext) {
    JsonObject config = vertxContext.verticle().config();
    JsonObject jsonObject = config.getJsonObject("auth");
    if (jsonObject != null) {
        for (String roleName : jsonObject.fieldNames()) {
            Role role = fromValueIfExists(roleName);
            checkState(role != null, "%s is not a valid role", roleName);
            JsonArray jsonUsers = jsonObject.getJsonArray(roleName);
            if (jsonUsers != null) {
                for (Object o : jsonUsers) {
                    JsonObject jsonUser = (JsonObject) o;
                    String id = getField(jsonUser, "id");
                    String username = getField(jsonUser, "username");
                    String password = getField(jsonUser, "password");
                    roles.put(role, new User(id, username, password));
                }//from  w  ww  . j av a 2s. c  o m
            }
        }
    } else {
        roles.clear();
    }
    return aVoid();
}

From source file:org.sfs.auth.SimpleAuthProvider.java

License:Apache License

@Override
public void handleOpenstackKeystoneAuth(SfsRequest httpServerRequest) {
    httpServerRequest.pause();//from w w  w  .  j a  v  a 2s . c  om
    VertxContext<Server> vertxContext = httpServerRequest.vertxContext();

    aVoid().flatMap(aVoid -> {
        final BufferWriteEndableWriteStream bufferWriteStream = new BufferWriteEndableWriteStream();
        LimitedWriteEndableWriteStream limitedWriteStream = new LimitedWriteEndableWriteStream(
                bufferWriteStream, MAX_AUTH_REQUEST_SIZE);
        return pump(httpServerRequest, limitedWriteStream).map(aVoid1 -> bufferWriteStream.toBuffer());
    }).map(new HttpBodyLogger()).map(new BufferToJsonObject()).map(jsonObject -> {
        JsonObject authJsonObject = jsonObject.getJsonObject("auth");
        JsonObject passwordCredentialsJson = authJsonObject.getJsonObject("passwordCredentials");
        String username = passwordCredentialsJson.getString("username");
        String password = passwordCredentialsJson.getString("password");
        String tenantName = authJsonObject.getString("tenantName");
        if (tenantName == null) {
            tenantName = "default";
        }

        Set<String> selectedRoles = new HashSet<>();

        for (Map.Entry<Role, Collection<User>> entry : roles.asMap().entrySet()) {
            Role role = entry.getKey();
            Collection<User> users = entry.getValue();
            for (User user : users) {
                if (equal(user.getUsername(), username) && equal(user.getPassword(), password)) {
                    selectedRoles.add(role.value());
                }
            }
        }

        if (selectedRoles.isEmpty()) {
            JsonObject errorJson = new JsonObject().put("message", "Invalid Credentials");
            throw new HttpRequestValidationException(HTTP_FORBIDDEN, errorJson);
        }

        Escaper escaper = urlPathSegmentEscaper();

        String serviceUrl = getRemoteServiceUrl(httpServerRequest);
        serviceUrl = format("%s/openstackswift001/%s", serviceUrl, escaper.escape(tenantName));

        JsonObject endpointJsonObject = new JsonObject().put("region", "ORD").put("tenantId", tenantName)
                .put("publicURL", serviceUrl).put("internalURL", serviceUrl);

        JsonArray endpointsJsonArray = new JsonArray().add(endpointJsonObject);

        JsonObject serviceCatalogJsonObject = new JsonObject().put("type", "object-store")
                .put("name", "openstackswift001").put("endpoints", endpointsJsonArray);

        JsonArray serviceCatalogJsonArray = new JsonArray().add(serviceCatalogJsonObject);

        JsonObject userJsonObject = new JsonObject().put("username", username)
                .put("roles_links", new JsonArray()).put("id", username);

        JsonArray roles = new JsonArray();
        for (String selectedRole : selectedRoles) {
            roles.add(selectedRole);
        }

        userJsonObject = userJsonObject.put("roles", roles);

        Calendar expiresDt = getInstance();
        expiresDt.setTimeInMillis(currentTimeMillis() + 86400000);

        JsonObject tokenJsonObject = new JsonObject().put("audit_ids", new JsonArray())
                .put("expires", toDateTimeString(expiresDt)).put("issued_at", toDateTimeString(getInstance()))
                .put("id", base64().encode((username + ":" + password).getBytes(UTF_8)));

        JsonObject metadataJsonObject = new JsonObject().put("is_admin", 0).put("roles", new JsonArray());

        return new JsonObject().put("access", new JsonObject().put("serviceCatalog", serviceCatalogJsonArray)
                .put("token", tokenJsonObject).put("user", userJsonObject).put("metadata", metadataJsonObject));
    }).single().subscribe(new ConnectionCloseTerminus<JsonObject>(httpServerRequest) {
        @Override
        public void onNext(JsonObject authenticationResponse) {
            Buffer buffer = buffer(authenticationResponse.encode(), UTF_8.toString());
            httpServerRequest.response().setStatusCode(HTTP_OK)
                    .putHeader(CONTENT_LENGTH, valueOf(buffer.length())).write(buffer);
        }
    });
}

From source file:org.sfs.vo.PersistentMasterKey.java

License:Apache License

public static PersistentMasterKey fromSearchHit(JsonObject searchHit) {
    return new PersistentMasterKey(searchHit.getString("_id"), searchHit.getLong("_version"))
            .merge(searchHit.getJsonObject("_source"));
}

From source file:org.sfs.vo.PersistentObject.java

License:Apache License

public static PersistentObject fromSearchHit(PersistentContainer container, JsonObject searchHit) {
    JsonObject document = searchHit.getJsonObject("_source");
    return new PersistentObject(container, searchHit.getString("_id"), searchHit.getLong("_version"))
            .merge(document);/*from  www . j  ava  2s.  c om*/
}

From source file:org.sfs.vo.ServiceDef.java

License:Apache License

public T merge(JsonObject jsonObject) {
    this.id = jsonObject.getString("id");
    this.lastUpdate = fromDateTimeString(jsonObject.getString("update_ts"));
    this.master = jsonObject.getBoolean("master_node");
    this.dataNode = jsonObject.getBoolean("data_node");
    this.documentCount = jsonObject.getLong("document_count");
    this.availableProcessors = jsonObject.getInteger("available_processors");
    this.freeMemory = jsonObject.getLong("free_memory");
    this.maxMemory = jsonObject.getLong("max_memory");
    this.totalMemory = jsonObject.getLong("total_memory");

    JsonObject jsonFileSystem = jsonObject.getJsonObject("file_system");
    if (jsonFileSystem != null) {
        this.fileSystem = new TransientXFileSystem().merge(jsonFileSystem);
    } else {/* w  w  w . j a v a2s  .c  o  m*/
        this.fileSystem = null;
    }

    JsonArray jsonListeners = jsonObject.getJsonArray("publish_addresses");
    this.publishAddresses.clear();
    if (jsonListeners != null) {
        for (Object o : jsonListeners) {
            String jsonListener = (String) o;
            this.publishAddresses.add(HostAndPort.fromString(jsonListener));
        }
    }

    JsonArray jsonVolumes = jsonObject.getJsonArray("volumes");
    this.volumes.clear();
    if (jsonVolumes != null) {
        for (Object o : jsonVolumes) {
            JsonObject jsonVolume = (JsonObject) o;
            TransientXVolume transientXVolume = new TransientXVolume().merge(jsonVolume);
            this.volumes.add(transientXVolume);
        }
    }
    return (T) this;
}

From source file:org.sfs.vo.XVolume.java

License:Apache License

public T merge(JsonObject jsonObject) {
    this.id = jsonObject.getString("id");
    JsonObject jsonFileSystem = jsonObject.getJsonObject("file_system");
    if (jsonFileSystem != null) {
        this.fileSystem = new TransientXFileSystem().merge(jsonFileSystem);
    } else {//from ww w. ja  v  a2 s.  co m
        this.fileSystem = null;
    }
    JsonObject jsonIndexFile = jsonObject.getJsonObject("index_file");
    if (jsonIndexFile != null) {
        this.indexFile = new TransientXAllocatedFile().merge(jsonIndexFile);
    } else {
        this.indexFile = null;
    }
    JsonObject jsonDataFile = jsonObject.getJsonObject("data_file");
    if (jsonDataFile != null) {
        this.dataFile = new TransientXAllocatedFile().merge(jsonDataFile);
    }
    this.status = fromNameIfExists(jsonObject.getString("status"));
    this.usableSpace = jsonObject.getLong("usable_space");
    return (T) this;
}

From source file:org.sub.bug.BugCRUDServiceVertxProxyHandler.java

License:Apache License

public void handle(Message<JsonObject> msg) {
    try {//  w ww  . jav a2 s . c  o  m
        JsonObject json = msg.body();
        String action = msg.headers().get("action");
        if (action == null) {
            throw new IllegalStateException("action not specified");
        }
        accessed();
        switch (action) {
        case "saveBug": {
            service.saveBug(json.getJsonObject("bug") == null ? null
                    : new org.sub.bug.entity.Bug(json.getJsonObject("bug")), createHandler(msg));
            break;
        }
        case "retrieveBug": {
            service.retrieveBug((java.lang.String) json.getValue("bugId"), 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 "removeBug": {
            service.removeBug((java.lang.String) json.getValue("bugId"), 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:se.liquidbytes.jel.owfs.OwfsAdapter.java

License:Apache License

/**
 * Add alarm monitoring for device.// ww  w  . j  a v  a2s.  c om
 *
 * @param device device to add alarm monitor for. Gets added only if device supports it.
 */
private void setupAlarmHandler(JsonObject device) {

    String alarmingMask = device.getJsonObject("typeInfo").getString("alarmingMask");

    /* We might see these exceptions in the log:
    "org.owfs.jowfsclient.alarm.AlarmingDevicesReader - Exception occured java.lang.NullPointerException"
    The problem is that line #11, "if (devicePath.endsWith(SLASH)) {", in file OWFSUtils of the JOwfsClient-library is feed with a null devicePath.
    Probably Owserver delivers one or more nulls in the collection of alarming devices due to some sort of timeout.
     */
    if (alarmingMask != null && !alarmingMask.isEmpty()) {
        AlarmingDevicesScanner alarmingDevicesScanner = owserverConnection.getAlarmingDevicesScanner();

        SwitchAlarmingDeviceListener alarmingDeviceHandler = new SwitchAlarmingDeviceListener(
                device.getString("path"), alarmingMask) {
            @Override
            public void handleAlarm(SwitchAlarmingDeviceEvent event) {
                logger.info("Alarm '" + getDeviceName() + "' : latch:;" + event.latchStatus + "', sensed:'"
                        + event.sensedStatus + "'");
            }
        };

        try {
            alarmingDevicesScanner.addAlarmingDeviceHandler(alarmingDeviceHandler);
        } catch (OwfsException ex) {
            logger.error(
                    "Failed to setup alarm handler on device \"{}\" on Owserver running at {}:{}, got errorcode: {}.",
                    device.getString("path"), this.host, this.port, ex.getErrorCode(), ex);
        } catch (IOException ex) {
            logger.error("Failed to setup alarm handler on device \"{}\" on Owserver running at {}:{}.",
                    device.getString("path"), this.host, this.port, ex);
        }
    }
}

From source file:se.liquidbytes.jel.owfs.OwfsAdapter.java

License:Apache License

/**
 * Returns a list of all supported devices by this adapter.
 *
 * @param message eventbus message./*ww  w .  j a  va  2s.  c  om*/
 */
private void getSupportedDevices(Message message) {

    JsonArray result = new JsonArray();

    for (JsonObject device : DeviceDatabase.getSuportedDeviceTypes()) {
        result.add(new JsonObject().put("typeId", device.getString("typeId"))
                .put("name", device.getString("name")).put("description", device.getString("description"))
                .put("manufacturer", device.getJsonObject("manufacturer")));
    }

    message.reply(constructReply(result));
}

From source file:se.liquidbytes.jel.owfs.OwfsAdapter.java

License:Apache License

/**
 * Read the current value from a device.
 *
 * @param device Existing device objekt.
 * @return Current value.//from  www  . ja  va 2 s . c o  m
 */
private String readValue(JsonObject device) {
    String hwId = device.getString("hwId");

    try {

        JsonObject typeInfo = device.getJsonObject("typeInfo");
        if (!typeInfo.containsKey("valueReadPath")) {
            // We can't read this kind of device.
            return null;
        }

        String path = device.getString("path") + typeInfo.getString("valueReadPath");
        String value = this.owserverConnection.read(path).trim();

        return value;
    } catch (DeviceMissingException ex) {
        throw new PluginException(
                String.format("Failed to read value from device with hwId '%s', device is reported missing.",
                        ex.getHardwareId()),
                ex);
    } catch (OwServerConnectionException ex) {
        throw new PluginException(String.format("Failed to read value from device with hwId '%s'.", hwId), ex);
    }
}