Example usage for java.util Dictionary isEmpty

List of usage examples for java.util Dictionary isEmpty

Introduction

In this page you can find the example usage for java.util Dictionary isEmpty.

Prototype

public abstract boolean isEmpty();

Source Link

Document

Tests if this dictionary maps no keys to value.

Usage

From source file:org.openhab.binding.km200.internal.KM200Binding.java

/**
 * {@inheritDoc}// w  w  w  .  j  a va 2 s.c  o m
 */
@Override
@SuppressWarnings("rawtypes")
public void updated(Dictionary config) throws ConfigurationException {

    if (config == null) {
        return;
    } else {
        if (config.isEmpty()) {
            return;
        }
        logger.info("Update KM200 Binding configuration, it takes a minute....");
        String ip = Objects.toString(config.get("ip4_address"), null);
        if (StringUtils.isNotBlank(ip)) {
            try {
                InetAddresses.forString(ip);
            } catch (IllegalArgumentException e) {
                logger.error("IP4_address in openhab.cfg is not valid!");
                throw new ConfigurationException("ip4_address", "ip4_address in openhab.cfg is not valid!");
            }
            device.setIP4Address(ip);
        } else {
            logger.error("No ip4_address in openhab.cfg set!");
            throw new ConfigurationException("ip4_address", "No ip4_address in openhab.cfg set!");
        }
        /* There a two possibilities of configuratiom */
        /* 1. With a private key */
        String PrivKey = Objects.toString(config.get("PrivKey"), null);
        if (StringUtils.isNotBlank(PrivKey)) {
            device.setCryptKeyPriv(PrivKey);

        } else { /* 2. With the MD5Salt, the device and user private password */
            String MD5Salt = Objects.toString(config.get("MD5Salt"), null);
            if (StringUtils.isNotBlank(MD5Salt)) {
                device.setMD5Salt(MD5Salt);
            } else {
                logger.error("No MD5Salt in openhab.cfg set!");
                throw new ConfigurationException("MD5Salt", "No MD5Salt in openhab.cfg set!");
            }

            String gpassword = Objects.toString(config.get("GatewayPassword"), null);
            if (StringUtils.isNotBlank(gpassword)) {
                device.setGatewayPassword(gpassword);
            } else {
                logger.error("No GatewayPassword in openhab.cfg set!");
                throw new ConfigurationException("GatewayPassword", "No GatewayPassword in openhab.cfg set!");
            }

            String ppassword = Objects.toString(config.get("PrivatePassword"), null);
            if (StringUtils.isNotBlank(ppassword)) {
                device.setPrivatePassword(ppassword);
            } else {
                logger.error("No PrivatePassword in openhab.cfg set!");
                throw new ConfigurationException("PrivatePassword", "No PrivatePassword in openhab.cfg set!");
            }
        }
        logger.info("Starting communication test..");
        /* Get HTTP Data from device */
        byte[] recData = comm.getDataFromService("/gateway/DateTime");
        if (recData == null) {
            throw new RuntimeException("Communication is not possible!");
        }
        if (recData.length == 0) {
            throw new RuntimeException("No reply from KM200!");
        }
        logger.info("Received data..");
        /* Derypt the message */
        String decodedData = comm.decodeMessage(recData);
        if (decodedData == null) {
            throw new RuntimeException("Decoding of the KM200 message is not possible!");
        }

        if (decodedData == "SERVICE NOT AVAILABLE") {
            logger.error("/gateway/DateTime: SERVICE NOT AVAILABLE");
        } else {
            logger.info("Test of the communication to the gateway was successful..");
        }
        logger.info("Init services..");
        /* communication is working */
        /* Checking of the devicespecific services and creating of a service list */
        for (KM200ServiceTypes service : KM200ServiceTypes.values()) {
            try {
                logger.debug(service.getDescription());
                comm.initObjects(service.getDescription());
            } catch (Exception e) {
                logger.error("Couldn't init service: {} error: {}", service, e.getMessage());
            }
        }
        /* Now init the virtual services */
        logger.debug("init Virtual Objects");
        try {
            comm.initVirtualObjects();
        } catch (Exception e) {
            logger.error("Couldn't init virtual services: {}", e.getMessage());
        }
        /* Output all availible services in the log file */
        /* Now init the virtual services */
        logger.debug("list All Services");
        device.listAllServices();
        logger.info("... Update of the KM200 Binding configuration completed");

        device.setInited(true);
        setProperlyConfigured(true);
    }

}

From source file:org.openhab.binding.mqtt.internal.MqttEventBusBinding.java

@Override
public void updated(Dictionary<String, ?> properties) throws ConfigurationException {

    // load event bus pubish/subscribe configuration from configuration file
    if (properties == null || properties.isEmpty()) {
        logger.trace("No mqtt-eventbus properties configured.");
        return;/* w  w w . ja va 2s .c  o m*/
    }

    logger.debug("Initializing MQTT Event Bus Binding");

    // stop existing publishers/subscribers
    deactivate();

    brokerName = (String) properties.get("broker");
    if (StringUtils.isEmpty(brokerName)) {
        logger.debug("No broker name configured for MQTT EventBusBinding");
        return;
    }

    setupEventBusStatePublisher((String) properties.get("statePublishTopic"));
    setupEventBusStateSubscriber((String) properties.get("stateSubscribeTopic"));
    setupEventBusCommandPublisher((String) properties.get("commandPublishTopic"));
    setupEventBusCommandSubscriber((String) properties.get("commandSubscribeTopic"));

    logger.debug("MQTT Event Bus Binding initialization completed.");
}

From source file:org.openhab.binding.stiebelheatpump.internal.StiebelHeatPumpBinding.java

/**
 * {@inheritDoc}// w  w w  .  ja  v  a 2 s  .c  o m
 */
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {

    String serialPort = null;
    int baudRate = DEFAULT_BAUD_RATE;
    serialTimeout = DEFAULT_SERIAL_TIMEOUT;
    String host = null;
    int port = 0;

    logger.debug("Loading stiebelheatpump binding configuration.");

    if (config == null || config.isEmpty()) {
        logger.warn("Empty or null configuration. Ignoring.");
        return;
    }

    if (config != null) {
        // to override the default refresh interval one has to add a
        // parameter to openhab.cfg like
        // <bindingName>:refresh=<intervalInMs>
        if (StringUtils.isNotBlank((String) config.get("refresh"))) {
            refreshInterval = Long.parseLong((String) config.get("refresh"));
        }
        if (StringUtils.isNotBlank((String) config.get("serialPort"))) {
            serialPort = (String) config.get("serialPort");
        }
        if (StringUtils.isNotBlank((String) config.get("baudRate"))) {
            baudRate = Integer.parseInt((String) config.get("baudRate"));
        }
        if (StringUtils.isNotBlank((String) config.get("host"))) {
            host = (String) config.get("host");
        }
        if (StringUtils.isNotBlank((String) config.get("port"))) {
            port = Integer.parseInt((String) config.get("port"));
        }
        if (StringUtils.isNotBlank((String) config.get("serialTimeout"))) {
            serialTimeout = Integer.parseInt((String) config.get("serialTimeout"));
        }
        if (StringUtils.isNotBlank((String) config.get("version"))) {
            version = (String) config.get("version");
        }
        try {
            if (host != null) {
                this.connector = new TcpConnector(host, port);
            } else {
                this.connector = new SerialPortConnector(serialPort, baudRate);
            }
            boolean isInitialized = getInitialHeatPumpSettings();
            setTime();
            if (host != null) {
                logger.info("Created heatpump configuration with tcp {}:{}, version:{} ", host, port, version);
            } else {
                logger.info("Created heatpump configuration with serialport:{}, baudrate:{}, version:{} ",
                        serialPort, baudRate, version);
            }
            setProperlyConfigured(isInitialized);
        } catch (RuntimeException e) {
            logger.warn(e.getMessage(), e);
            throw e;
        }

    }
}

From source file:org.openhab.io.squeezeserver.SqueezeServer.java

@Override
public synchronized void updated(Dictionary<String, ?> config) throws ConfigurationException {
    // disconnect first in case the config has changed for an existing
    // instance// w w  w.  j a  v a2s.co  m
    disconnect();

    host = null;
    cliPort = DEFAULT_CLI_PORT;
    webPort = DEFAULT_WEB_PORT;
    language = DEFAULT_LANGUAGE;

    playersById.clear();
    playersByMacAddress.clear();

    if (config == null || config.isEmpty()) {
        logger.warn("Empty or null configuration. Ignoring.");
        return;
    }

    Enumeration<String> keys = config.keys();
    while (keys.hasMoreElements()) {

        String key = (String) keys.nextElement();

        // the config-key enumeration contains additional keys that we
        // don't want to process here ...
        if ("service.pid".equals(key)) {
            continue;
        }

        Matcher serverMatcher = SERVER_CONFIG_PATTERN.matcher(key);
        Matcher playerMatcher = PLAYER_CONFIG_PATTERN.matcher(key);
        Matcher languageMatcher = LANGUAGE_CONFIG_PATTERN.matcher(key);

        String value = (String) config.get(key);

        if (serverMatcher.matches()) {
            String serverConfig = serverMatcher.group(2);
            if (serverConfig.equals("host") && StringUtils.isNotBlank(value)) {
                host = value;
            } else if (serverConfig.equals("cliport") && StringUtils.isNotBlank(value)) {
                cliPort = Integer.valueOf(value);
            } else if (serverConfig.equals("webport") && StringUtils.isNotBlank(value)) {
                webPort = Integer.valueOf(value);
            }
        } else if (playerMatcher.matches()) {
            String playerId = playerMatcher.group(1);
            String macAddress = value;

            SqueezePlayer player = new SqueezePlayer(this, playerId, macAddress);
            playersById.put(playerId.toLowerCase(), player);
            playersByMacAddress.put(macAddress.toLowerCase(), player);
        } else if (languageMatcher.matches() && StringUtils.isNotBlank(value)) {
            language = value;
        } else {
            logger.warn("Unexpected or unsupported configuration: " + key + ". Ignoring.");
        }
    }

    if (StringUtils.isEmpty(host))
        throw new ConfigurationException("host",
                "No Squeeze Server host specified - this property is mandatory");
    if (playersById.size() == 0)
        throw new ConfigurationException("host",
                "No Squeezebox players specified - there must be at least one player");

    // attempt to connect using our new config
    connect();
}

From source file:org.openhab.io.transport.mqtt.MqttService.java

@Override
public void updated(Dictionary<String, ?> properties) throws ConfigurationException {

    // load broker configurations from configuration file
    if (properties == null || properties.isEmpty()) {
        return;/* w  w w  .j  a v  a 2s .co m*/
    }

    Enumeration<String> keys = properties.keys();
    while (keys.hasMoreElements()) {

        String key = keys.nextElement();

        if (key.equals("service.pid")) {
            // ignore the only non-broker property..
            continue;
        }

        String[] subkeys = key.split("\\.");
        if (subkeys.length != 2) {
            logger.debug("MQTT Broker property '{}' should have the format 'broker.propertykey'", key);
            continue;
        }

        String value = (String) properties.get(key);
        String name = subkeys[0].toLowerCase();
        String property = subkeys[1];

        if (StringUtils.isBlank(value)) {
            logger.trace("Property is empty: {}", key);
            continue;
        } else {
            logger.trace("Processing property: {} = {}", key, value);
        }

        MqttBrokerConnection conn = brokerConnections.get(name);
        if (conn == null) {
            conn = new MqttBrokerConnection(name);
            brokerConnections.put(name, conn);
        }

        if (property.equals("url")) {
            conn.setUrl(value);
        } else if (property.equals("user")) {
            conn.setUser(value);
        } else if (property.equals("pwd")) {
            conn.setPassword(value);
        } else if (property.equals("qos")) {
            conn.setQos(Integer.parseInt(value));
        } else if (property.equals("retain")) {
            conn.setRetain(Boolean.parseBoolean(value));
        } else if (property.equals("async")) {
            conn.setAsync(Boolean.parseBoolean(value));
        } else if (property.equals("clientId")) {
            conn.setClientId(value);
        } else if (property.equals("lwt")) {
            MqttWillAndTestament will = MqttWillAndTestament.fromString(value);
            logger.debug("Setting last will: {}", will);
            conn.setLastWill(will);
        } else if (property.equals("keepAlive")) {
            conn.setKeepAliveInterval(Integer.parseInt(value));
        } else {
            logger.warn("Unrecognized property: {}", key);
        }
    }
    logger.info("MQTT Service initialization completed.");

    for (MqttBrokerConnection con : brokerConnections.values()) {
        try {
            con.start();
        } catch (Exception e) {
            logger.error("Error starting broker connection", e);
        }
    }
}

From source file:org.openhab.persistence.ibmiot.internal.IbmIotPersistenceService.java

@Override
public void updated(Dictionary<String, ?> properties) throws ConfigurationException {

    if (properties == null || properties.isEmpty()) {
        logger.trace("No config properties available.");
        return;/*from  w ww.  java  2  s  . c o m*/
    }

    brokerName = getProperty(properties, "broker");
    topic = getProperty(properties, "topic");
    configured = true;

    logger.debug("Configuration updated for IBM IoT Persistence.");

    deactivate();
    activate();
}

From source file:org.opentaps.notes.repository.impl.NoteRepositoryImpl.java

private static BasicDBObject noteToDbObject(Note note) {
    if (note == null) {
        return null;
    }//from  w ww  . j a  v a  2s  . c o m
    BasicDBObject noteDoc = (BasicDBObject) BasicDBObjectBuilder.start()
            .add(Note.Fields.noteId.getName(), note.getNoteId())
            .add(Note.Fields.noteText.getName(), note.getNoteText())
            .add(Note.Fields.clientDomain.getName(), note.getClientDomain()).get();

    User user = note.getCreatedByUser();
    if (user != null) {
        BasicDBObject userDoc = (BasicDBObject) BasicDBObjectBuilder.start().get();
        @SuppressWarnings("unchecked")
        Dictionary<String, Object> props = user.getProperties();
        if (props != null && !props.isEmpty()) {
            Enumeration<String> keys = props.keys();
            while (keys.hasMoreElements()) {
                String key = keys.nextElement();
                userDoc.append(key, props.get(key));
            }
        }
        noteDoc.append(Note.Fields.createdByUser.getName(), userDoc);
    }

    // look for custom fields
    for (String field : note.getAttributeNames()) {
        noteDoc.put(field, note.getAttribute(field));
    }

    return noteDoc;
}

From source file:org.ops4j.pax.web.service.internal.Activator.java

private void determineServiceProperties(final Dictionary managedConfig, final Configuration config,
        final Integer httpPort, final Integer httpSecurePort) {
    final Hashtable<String, Object> toPropagate = new Hashtable<String, Object>();
    // first store all configuration properties as received via managed service
    if (managedConfig != null && !managedConfig.isEmpty()) {
        final Enumeration enumeration = managedConfig.keys();
        while (enumeration.hasMoreElements()) {
            String key = (String) enumeration.nextElement();
            toPropagate.put(key, managedConfig.get(key));
        }//  www. j  a  v  a2 s  .c  om
    }

    // then add/replace configuration properties
    setProperty(toPropagate, PROPERTY_HTTP_ENABLED, config.isHttpEnabled());
    setProperty(toPropagate, PROPERTY_HTTP_PORT, config.getHttpPort());
    setProperty(toPropagate, PROPERTY_HTTP_SECURE_ENABLED, config.isHttpEnabled());
    setProperty(toPropagate, PROPERTY_HTTP_SECURE_PORT, config.getHttpSecurePort());
    setProperty(toPropagate, PROPERTY_HTTP_USE_NIO, config.useNIO());
    setProperty(toPropagate, PROPERTY_SSL_CLIENT_AUTH_NEEDED, config.isClientAuthNeeded());
    setProperty(toPropagate, PROPERTY_SSL_CLIENT_AUTH_WANTED, config.isClientAuthWanted());
    setProperty(toPropagate, PROPERTY_SSL_KEYSTORE, config.getSslKeystore());
    setProperty(toPropagate, PROPERTY_SSL_KEYSTORE_TYPE, config.getSslKeystoreType());
    //store( toPropagate, PROPERTY_SSL_PASSWORD, config.getSslPassword());
    setProperty(toPropagate, PROPERTY_SSL_PASSWORD, null);
    //store( toPropagate, PROPERTY_SSL_KEYPASSWORD, config.getSslKeyPassword());
    setProperty(toPropagate, PROPERTY_SSL_KEYPASSWORD, null);
    setProperty(toPropagate, PROPERTY_TEMP_DIR, config.getTemporaryDirectory());
    setProperty(toPropagate, PROPERTY_SESSION_TIMEOUT, config.getSessionTimeout());
    setProperty(toPropagate, PROPERTY_SESSION_URL, config.getSessionUrl());
    setProperty(toPropagate, PROPERTY_SESSION_COOKIE, config.getSessionCookie());
    setProperty(toPropagate, PROPERTY_WORKER_NAME, config.getWorkerName());
    setProperty(toPropagate, PROPERTY_LISTENING_ADDRESSES, config.getListeningAddresses());

    // then replace ports
    setProperty(toPropagate, PROPERTY_HTTP_PORT, httpPort);
    setProperty(toPropagate, PROPERTY_HTTP_SECURE_PORT, httpSecurePort);

    m_httpServiceFactoryProps = toPropagate;
}