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

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

Introduction

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

Prototype

public boolean containsKey(String key) 

Source Link

Document

Does the JSON object contain the specified key?

Usage

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

License:Apache License

/**
 * Scan for available devices on 1-wire bus. And updates our internal list of available devices. Note this is a blocking call!
 *
 *///  www .  j a  v  a 2s.com
private void scanAvailableDevices() {
    try {
        String hwId, deviceType, deviceFamily, isPowered;
        Set<String> foundDeviceIds = new HashSet<>();
        EventBus eb = vertx.eventBus();
        JsonObject device, childDevice, broadcastDevice;

        Instant startExecutionTime = Instant.now();
        logger.debug("Scanning for available devices on Owserver at {}:{} with adapter id \"{}\".", this.host,
                this.port, this.getId());
        List<String> owDevices = owserverConnection.listDirectory(true);
        logger.debug("Found {} devices on Owserver at {}:{} with adapter id \"{}\".", owDevices.size(),
                this.host, this.port, this.getId());

        for (String owDevice : owDevices) {
            hwId = owserverConnection.read(owDevice + "/id");
            deviceType = owserverConnection.read(owDevice + "/type");
            deviceFamily = owserverConnection.read(owDevice + "/family");

            foundDeviceIds.add(hwId);

            device = deviceLookup.get(hwId);
            // Device not found in existing list, this must be a newly added device. Add it to the collection and broadcast its existence.
            if (device == null) {
                if (DeviceDatabase.getDeviceTypeInfo(deviceType) != null) {
                    JsonObject typeInfo = DeviceDatabase.getDeviceTypeInfo(deviceType);

                    // For devices that need to be setup in a special state to be usable, run their init commands when added to list of available devices.
                    if (typeInfo.containsKey("initCommands")) {
                        for (Iterator it = typeInfo.getJsonArray("initCommands").iterator(); it.hasNext();) {
                            JsonObject command = (JsonObject) it.next();
                            String path = owDevice + command.getString("path");
                            logger.debug(
                                    "Running initcommand (path '{}', value '{}') for device '{}' on Owserver at {}:{} with adapter id \"{}\".",
                                    path, command.getString("value"), hwId, this.host, this.port, this.getId());

                            owserverConnection.write(path, command.getString("value"));
                        }
                    }

                    try {
                        isPowered = owserverConnection.read(owDevice + "/power");
                        if (isPowered != null && isPowered.equals("0")) {
                            logger.warn(
                                    "Device '{}' of type '{}' on Owserver at {}:{} with adapter id \"{}\" is running on parasitic power, this will slow down the 1-wire network and is less reliable than a powered device.",
                                    hwId, deviceType, this.host, this.port, this.getId());
                        }
                    } catch (OwServerConnectionException ex) {
                        // Ignore. Devices that don't support the power-property will throw an error, so we just ignore this.
                    }

                    device = new JsonObject();
                    device.put("hwId", hwId);
                    device.put("type", deviceType);
                    device.put("name", typeInfo.getString("name"));
                    device.put("family", deviceFamily);
                    device.put("path", owDevice);
                    device.put("typeInfo", typeInfo);

                    deviceLookup.put(hwId, device);
                    logger.info(
                            "New device found during scan of Owserver at {}:{} with adapter id \"{}\". Device hwId: {}, type: {}, family: {}.",
                            this.host, this.port, this.getId(), hwId, deviceType, deviceFamily);

                    // For devices that supports it.
                    //setupAlarmHandler(device);
                    broadcastDevice = new JsonObject().put("adapterId", this.getId()).put("port", this.port)
                            .put("host", this.host).put("hwId", hwId).put("type", deviceType)
                            .put("name", typeInfo.getString("name"));
                    eb.publish(AdapterEvents.EVENTBUS_ADAPTERS, broadcastDevice,
                            new DeliveryOptions().addHeader("action", AdapterEvents.EVENT_DEVICES_ADDED));

                    // Check if this device is an container for other "child-devices". In that case, add all the children too, their Id will be <parent_childnumber>.
                    if (typeInfo.containsKey("childDevices")) {
                        for (Iterator it = typeInfo.getJsonArray("childDevices").iterator(); it.hasNext();) {
                            JsonObject childType = (JsonObject) it.next();
                            String childId = String.format("%s%s%s", hwId, CHILDSEPARATOR,
                                    childType.getString("idSuffix"));

                            childDevice = new JsonObject();
                            childDevice.put("hwId", childId);
                            childDevice.put("type", deviceType);
                            childDevice.put("name", String.format("%s-%s", typeInfo.getString("name"),
                                    childType.getString("name")));

                            deviceLookup.put(childId, childDevice);
                            logger.info(
                                    "New childdevice for device {} found during scan of Owserver at {}:{} with adapter id \"{}\". Device hwId: {}, type: {}, family: {}.",
                                    hwId, this.host, this.port, this.getId(), childId, deviceType,
                                    deviceFamily);

                            broadcastDevice = new JsonObject().put("adapterId", this.getId())
                                    .put("port", this.port).put("host", this.host).put("hwId", childId)
                                    .put("type", deviceType).put("name", childDevice.getString("name"));
                            eb.publish(AdapterEvents.EVENTBUS_ADAPTERS, broadcastDevice, new DeliveryOptions()
                                    .addHeader("action", AdapterEvents.EVENT_DEVICES_ADDED));
                        }
                    }
                } else {
                    logger.info(
                            "Found unsupported devicetype for device with hwId '{}' on Owserver at {}:{} with adapter id \"{}\". Device will be ignored! Please notify developers and provide: type={}, family={}.",
                            hwId, this.host, this.port, this.getId(), deviceType, deviceFamily);
                }
            }
        }

        // Remove all devices in device list that was no longer found during this scan. They has been disconnected from the 1-wire bus.
        Set<String> tempSet = new HashSet(deviceLookup.keySet());
        tempSet.removeAll(foundDeviceIds);

        for (String removeId : tempSet) {
            // Check that it's not a childdevice, we are not interested in them right now.
            if (!removeId.contains(CHILDSEPARATOR)) {
                // If device has children, remove these first.
                List<String> childDevicesId = tempSet.stream()
                        .filter(d -> d.startsWith(removeId + CHILDSEPARATOR)).collect(Collectors.toList());
                for (String childDeviceId : childDevicesId) {
                    removeDeviceFromLookup(childDeviceId, eb);
                }
                // Then remove device.
                removeDeviceFromLookup(removeId, eb);
            }
        }

        logger.debug("Scanning bus for devices took {}ms on Owserver at {}:{} with adapter id \"{}\".",
                Duration.between(startExecutionTime, Instant.now()).toMillis(), this.host, this.port,
                this.getId());
    } catch (OwServerConnectionException ex) {
        logger.error(
                "Error while trying to scan Owserver at {}:{} with adapter id \"{}\" for available devices.",
                this.host, this.port, this.getId(), ex);
    }
}

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   w w  w. ja  v  a 2s . com*/
 */
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);
    }
}

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

License:Apache License

/**
 * Set value on device with specified hwId.
 *
 * @param hwId Id on device//  w  w w.  jav  a 2  s. co m
 * @param value value to set on device.
 * @throws DeviceMissingException throws exception if specified device does not exist.
 * @throws OwServerConnectionException throws exception if command fails for any reason.
 */
private void setDeviceValue(String hwId, String value)
        throws DeviceMissingException, OwServerConnectionException {

    if (hwId == null || !deviceLookup.containsKey(hwId)) {
        throw new DeviceMissingException("Trying to perform a action on a non existing device.", hwId);
    }

    if (hwId.contains(CHILDSEPARATOR)) {

        String parentId = hwId.split(CHILDSEPARATOR)[0];
        String childSuffix = hwId.split(CHILDSEPARATOR)[1];
        JsonObject parentDevice = deviceLookup.get(parentId);
        JsonObject typeInfo = parentDevice.getJsonObject("typeInfo");

        if (typeInfo == null) {
            throw new OwServerConnectionException(String.format("typeInfo missing for device with type '%s'",
                    parentDevice.getString("type")));
        }

        JsonArray childDevices = typeInfo.getJsonArray("childDevices");
        if (childDevices != null && childDevices.size() > 0) {
            String writePath = childDevices.stream().filter(t -> t instanceof JsonObject)
                    .map(t -> (JsonObject) t).filter((d) -> d.getString("idSuffix").equals(childSuffix))
                    .map((cd) -> cd.getString("valueWritePath")).findFirst().get();
            writePath = parentDevice.getString("path") + writePath;

            // Queue command. Record time so we could measure how long command has been queued before executed, if we want to.
            this.commandQueue.offer(new JsonObject().put("path", writePath).put("value", value).put("nanoTime",
                    System.nanoTime()));
        }

    } else {

        JsonObject device = deviceLookup.get(hwId);
        JsonObject typeInfo = device.getJsonObject("typeInfo");

        if (typeInfo == null) {
            throw new OwServerConnectionException(
                    String.format("typeInfo missing for device with type '%s'", device.getString("type")));
        }
        // Check if this type of device is writable.
        if (typeInfo.containsKey("valueWritePath")) {
            String writePath = device.getString("path") + typeInfo.getString("valueWritePath");

            // Queue command. Record time so we could measure how long command has been queued before executed, if we want to.
            this.commandQueue.offer(new JsonObject().put("path", writePath).put("value", value).put("nanoTime",
                    System.nanoTime()));
        }
    }
}

From source file:shadowsocks.util.GlobalConfig.java

License:Apache License

public static void getConfigFromFile() throws ClassCastException {
    String name = GlobalConfig.get().getConfigFile();
    if (name == null)
        return;/*www  .  j ava 2 s  . c o  m*/
    String data = GlobalConfig.readConfigFile(name);

    JsonObject jsonobj = new JsonObject(data);

    if (jsonobj.containsKey(SERVER_ADDR)) {
        String server = jsonobj.getString(SERVER_ADDR);
        log.debug("CFG:Server address: " + server);
        GlobalConfig.get().setServer(server);
    }
    if (jsonobj.containsKey(SERVER_PORT)) {
        int port = jsonobj.getInteger(SERVER_PORT).intValue();
        log.debug("CFG:Server port: " + port);
        GlobalConfig.get().setPort(port);
    }
    if (jsonobj.containsKey(LOCAL_PORT)) {
        int lport = jsonobj.getInteger(LOCAL_PORT).intValue();
        log.debug("CFG:Local port: " + lport);
        GlobalConfig.get().setLocalPort(lport);
    }
    if (jsonobj.containsKey(PASSWORD)) {
        String password = jsonobj.getString(PASSWORD);
        log.debug("CFG:Password: " + password);
        GlobalConfig.get().setPassowrd(password);
    }
    if (jsonobj.containsKey(METHOD)) {
        String method = jsonobj.getString(METHOD);
        log.debug("CFG:Crypto method: " + method);
        GlobalConfig.get().setMethod(method);
    }
    if (jsonobj.containsKey(AUTH)) {
        boolean auth = jsonobj.getBoolean(AUTH).booleanValue();
        log.debug("CFG:One time auth: " + auth);
        GlobalConfig.get().setOTAEnabled(auth);
    }
    if (jsonobj.containsKey(TIMEOUT)) {
        int timeout = jsonobj.getInteger(TIMEOUT).intValue();
        log.debug("CFG:Timeout: " + timeout);
        GlobalConfig.get().setTimeout(timeout);
    }
    if (jsonobj.containsKey(SERVER_MODE)) {
        boolean isServer = jsonobj.getBoolean(SERVER_MODE).booleanValue();
        log.debug("CFG:Running on server mode: " + isServer);
        GlobalConfig.get().setServerMode(isServer);
    }
}

From source file:studio.lysid.scales.deploy.DeploymentOptionsParser.java

License:Open Source License

private static void initializeConfigOptionDefaultValue(JsonObject config, String key, Integer defaultValue) {
    if (!config.containsKey(key)) {
        config.put(key, defaultValue);//from   w ww.ja  va  2s.c  o  m
    }
}