Search in sources :

Example 21 with ConfigurationException

use of org.osgi.service.cm.ConfigurationException in project openhab1-addons by openhab.

the class KNXConnection method updated.

/*
     * (non-Javadoc)
     * 
     * @see org.osgi.service.cm.ManagedService#updated(java.util.Dictionary)
     */
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    if (config != null) {
        sLogger.debug("KNXBinding configuration present. Setting up KNX bus connection.");
        sIp = (String) config.get("ip");
        String readingBusAddrString = (String) config.get("busaddr");
        if (StringUtils.isNotBlank(readingBusAddrString)) {
            sLocalSourceAddr = readingBusAddrString;
        }
        String readingIgnLocEv = (String) config.get("ignorelocalevents");
        if (StringUtils.isNotBlank(readingIgnLocEv)) {
            sIgnoreLocalSourceEvents = readingIgnLocEv.equalsIgnoreCase("true");
        }
        String connectionTypeString = (String) config.get("type");
        if (StringUtils.isNotBlank(connectionTypeString)) {
            if ("TUNNEL".equals(connectionTypeString)) {
                sIpConnectionType = KNXNetworkLinkIP.TUNNELING;
            } else if ("ROUTER".equals(connectionTypeString)) {
                sIpConnectionType = KNXNetworkLinkIP.ROUTING;
                if (StringUtils.isBlank(sIp)) {
                    sIp = DEFAULT_MULTICAST_IP;
                }
            } else {
                throw new ConfigurationException("type", "unknown IP connection type '" + connectionTypeString + "'! Known types are either 'TUNNEL' or 'ROUTER'");
            }
        } else {
            sIpConnectionType = KNXNetworkLinkIP.TUNNELING;
        }
        String portConfig = (String) config.get("port");
        if (StringUtils.isNotBlank(portConfig)) {
            sPort = Integer.parseInt(portConfig);
        } else {
            sPort = KNXnetIPConnection.DEFAULT_PORT;
        }
        sLocalIp = (String) config.get("localIp");
        sSerialPort = (String) config.get("serialPort");
        String readingPauseString = (String) config.get("pause");
        if (StringUtils.isNotBlank(readingPauseString)) {
            sReadingPause = Long.parseLong(readingPauseString);
        }
        String responseTimeoutString = (String) config.get("timeout");
        if (StringUtils.isNotBlank(responseTimeoutString)) {
            long timeout = Long.parseLong(responseTimeoutString);
            if (timeout > 0) {
                sResponseTimeout = timeout;
            }
        }
        String readRetriesLimitString = (String) config.get("readRetries");
        if (StringUtils.isNotBlank(readRetriesLimitString)) {
            int readRetries = Integer.parseInt(readRetriesLimitString);
            if (readRetries > 0) {
                sReadRetriesLimit = readRetries;
            }
        }
        String autoReconnectPeriodString = (String) config.get("autoReconnectPeriod");
        if (StringUtils.isNotBlank(autoReconnectPeriodString)) {
            int autoReconnectPeriodValue = Integer.parseInt(autoReconnectPeriodString);
            if (autoReconnectPeriodValue >= 0) {
                sAutoReconnectPeriod = autoReconnectPeriodValue;
            }
        }
        String maxRefreshQueueEntriesString = (String) config.get("maxRefreshQueueEntries");
        if (StringUtils.isNotBlank(maxRefreshQueueEntriesString)) {
            try {
                int maxRefreshQueueEntriesValue = Integer.parseInt(maxRefreshQueueEntriesString);
                if (maxRefreshQueueEntriesValue >= 0) {
                    sMaxRefreshQueueEntries = maxRefreshQueueEntriesValue;
                }
            } catch (NumberFormatException e) {
                sLogger.warn("Error when trying to read parameter 'maxRefreshQueueEntries' from configuration. '{}' is not a number: using default.", maxRefreshQueueEntriesString);
            }
        }
        String numberOfThreadsString = (String) config.get("numberOfThreads");
        if (StringUtils.isNotBlank(numberOfThreadsString)) {
            try {
                int numberOfThreadsValue = Integer.parseInt(numberOfThreadsString);
                if (numberOfThreadsValue >= 0) {
                    sNumberOfThreads = numberOfThreadsValue;
                }
            } catch (NumberFormatException e) {
                sLogger.warn("Error when trying to read parameter 'numberOfThreads' from configuration. '{}' is not a number: using default.", numberOfThreadsString);
            }
        }
        String scheduledExecutorServiceShutdownTimeoutString = (String) config.get("scheduledExecutorServiceShutdownTimeout");
        if (StringUtils.isNotBlank(scheduledExecutorServiceShutdownTimeoutString)) {
            try {
                int scheduledExecutorServiceShutdownTimeoutValue = Integer.parseInt(scheduledExecutorServiceShutdownTimeoutString);
                if (scheduledExecutorServiceShutdownTimeoutValue >= 0) {
                    sScheduledExecutorServiceShutdownTimeout = scheduledExecutorServiceShutdownTimeoutValue;
                }
            } catch (NumberFormatException e) {
                sLogger.warn("Error when trying to read parameter 'scheduledExecutorServiceShutdownTimeout' from configuration. '{}' is not a number: using default.", scheduledExecutorServiceShutdownTimeoutString);
            }
        }
        String shouldUseNAT = (String) config.get("useNAT");
        sUseNAT = StringUtils.isNotBlank(shouldUseNAT) && shouldUseNAT.equalsIgnoreCase("true");
        if (sPC == null) {
            sLogger.debug("Not connected yet. Trying to connect.");
            if (!connect()) {
                sLogger.warn("Initial connection to KNX bus failed!");
                if (sAutoReconnectPeriod > 0) {
                    sLogger.info("KNX link will be retried in {} seconds", sAutoReconnectPeriod);
                    final Timer timer = new Timer();
                    TimerTask timerTask = new ConnectTimerTask(timer);
                    timer.schedule(timerTask, sAutoReconnectPeriod * 1000, sAutoReconnectPeriod * 1000);
                }
            } else {
                sLogger.debug("Success: connected.");
            }
        }
    } else {
        sLogger.info("KNXBinding configuration is not present. Please check your configuration file or if not needed remove the KNX addon.");
    }
}
Also used : Timer(java.util.Timer) TimerTask(java.util.TimerTask) ConfigurationException(org.osgi.service.cm.ConfigurationException)

Example 22 with ConfigurationException

use of org.osgi.service.cm.ConfigurationException in project openhab1-addons by openhab.

the class SamsungTvBinding method updated.

/**
     * @{inheritDoc
     */
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    if (config != null) {
        Enumeration<String> keys = config.keys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            // don't want to process here ...
            if ("service.pid".equals(key)) {
                continue;
            }
            Matcher matcher = EXTRACT_TV_CONFIG_PATTERN.matcher(key);
            if (!matcher.matches()) {
                logger.debug("given config key '" + key + "' does not follow the expected pattern '<id>.<host|port>'");
                continue;
            }
            matcher.reset();
            matcher.find();
            String deviceId = matcher.group(1);
            DeviceConfig deviceConfig = deviceConfigCache.get(deviceId);
            if (deviceConfig == null) {
                deviceConfig = new DeviceConfig(deviceId);
                deviceConfigCache.put(deviceId, deviceConfig);
            }
            String configKey = matcher.group(2);
            String value = (String) config.get(key);
            if ("host".equals(configKey)) {
                deviceConfig.host = value;
            } else if ("port".equals(configKey)) {
                deviceConfig.port = Integer.valueOf(value);
            } else {
                throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown");
            }
        }
    }
}
Also used : Matcher(java.util.regex.Matcher) ConfigurationException(org.osgi.service.cm.ConfigurationException)

Example 23 with ConfigurationException

use of org.osgi.service.cm.ConfigurationException in project openhab1-addons by openhab.

the class EBusBinding method updated.

/*
     * (non-Javadoc)
     *
     * @see org.osgi.service.cm.ManagedService#updated(java.util.Dictionary)
     */
@Override
public void updated(Dictionary<String, ?> properties) throws ConfigurationException {
    logger.info("Update eBus Binding configuration ...");
    if (properties == null || properties.isEmpty()) {
        throw new RuntimeException("No properties in openhab.cfg set!");
    }
    try {
        // stop last connector-thread if active
        stopConnector();
        // check to ensure that it is available
        checkConfigurationProvider();
        // clear current configuration
        configurationProvider.clear();
        // load parser from default url
        parser = new EBusTelegramParser(configurationProvider);
        URL configurationUrl = null;
        String parsers = (String) properties.get("parsers");
        if (StringUtils.isEmpty(parsers)) {
            // set to current stable configurations as default
            parsers = "common";
        }
        for (String elem : parsers.split(",")) {
            configurationUrl = null;
            // check for keyword custom to load custom configuration
            if (elem.trim().equals("custom")) {
                String parserUrl = (String) properties.get("parserUrl");
                if (parserUrl != null) {
                    logger.debug("Load custom eBus Parser with url {}", parserUrl);
                    configurationUrl = new URL(parserUrl);
                }
            } else {
                logger.debug("Load eBus Parser Configuration \"{}\" ...", elem.trim());
                String filename = "src/main/resources/" + elem.trim() + "-configuration.json";
                Bundle bundle = FrameworkUtil.getBundle(EBusBinding.class);
                configurationUrl = bundle.getResource(filename);
                if (configurationUrl == null) {
                    logger.error("Unable to load file {} ...", elem.trim() + "-configuration.json");
                }
            }
            if (configurationUrl != null) {
                configurationProvider.loadConfigurationFile(configurationUrl);
            }
        }
        // check minimal config
        if (properties.get("serialPort") != null && properties.get("hostname") != null) {
            throw new ConfigurationException("hostname", "Set property serialPort or hostname, not both!");
        }
        // use the serial connector
        if (StringUtils.isNotEmpty((String) properties.get("serialPort"))) {
            try {
                // load class by reflection to keep gnu.io (serial) optional. Declarative Services causes an
                // class not found exception, also if serial is not used!
                // FIXME: Is there a better way to avoid that a class not found exception?
                @SuppressWarnings("unchecked") Class<AbstractEBusWriteConnector> _tempClass = (Class<AbstractEBusWriteConnector>) EBusBinding.class.getClassLoader().loadClass("org.openhab.binding.ebus.internal.connection.EBusSerialConnector");
                Constructor<AbstractEBusWriteConnector> constructor = _tempClass.getDeclaredConstructor(String.class);
                connector = constructor.newInstance((String) properties.get("serialPort"));
            } catch (ClassNotFoundException e) {
                logger.error(e.toString(), e);
            } catch (NoSuchMethodException e) {
                logger.error(e.toString(), e);
            } catch (SecurityException e) {
                logger.error(e.toString(), e);
            } catch (InstantiationException e) {
                logger.error(e.toString(), e);
            } catch (IllegalAccessException e) {
                logger.error(e.toString(), e);
            } catch (IllegalArgumentException e) {
                logger.error(e.toString(), e);
            } catch (InvocationTargetException e) {
                logger.error(e.toString(), e);
            }
        } else if (StringUtils.isNotEmpty((String) properties.get("hostname"))) {
            // use the tcp-ip connector
            connector = new EBusTCPConnector((String) properties.get("hostname"), Integer.parseInt((String) properties.get("port")));
        }
        // Set eBus sender id or default 0xFF
        if (StringUtils.isNotEmpty((String) properties.get("senderId"))) {
            connector.setSenderId(EBusUtils.toByte((String) properties.get("senderId")));
        }
        if (properties.get("record") != null) {
            String debugWriterMode = (String) properties.get("record");
            logger.info("Enable CSV writer for eBUS {}", debugWriterMode);
            debugWriter = new EBusTelegramCSVWriter();
            debugWriter.openInUserData("ebus-" + debugWriterMode + ".csv");
            parser.setDebugCSVWriter(debugWriter, debugWriterMode);
        }
        // add event listener
        connector.addEBusEventListener(this);
        // start thread
        connector.start();
        // set the new connector
        commandProcessor.setConnector(connector);
        commandProcessor.setConfigurationProvider(configurationProvider);
    } catch (MalformedURLException e) {
        logger.error(e.toString(), e);
    } catch (IOException e) {
        throw new ConfigurationException("general", e.toString(), e);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) Bundle(org.osgi.framework.Bundle) IOException(java.io.IOException) URL(java.net.URL) InvocationTargetException(java.lang.reflect.InvocationTargetException) EBusTelegramParser(org.openhab.binding.ebus.internal.parser.EBusTelegramParser) AbstractEBusWriteConnector(org.openhab.binding.ebus.internal.connection.AbstractEBusWriteConnector) ConfigurationException(org.osgi.service.cm.ConfigurationException) EBusTCPConnector(org.openhab.binding.ebus.internal.connection.EBusTCPConnector) EBusTelegramCSVWriter(org.openhab.binding.ebus.internal.parser.EBusTelegramCSVWriter)

Example 24 with ConfigurationException

use of org.osgi.service.cm.ConfigurationException in project openhab1-addons by openhab.

the class EcobeeBinding method updated.

/**
     * {@inheritDoc}
     */
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    if (config != null) {
        // to override the default granularity one has to add a
        // parameter to openhab.cfg like ecobee:granularity=2000
        String granularityString = Objects.toString(config.get(CONFIG_GRANULARITY), null);
        granularity = isNotBlank(granularityString) ? Long.parseLong(granularityString) : DEFAULT_GRANULARITY;
        // to override the default refresh interval one has to add a
        // parameter to openhab.cfg like ecobee:refresh=240000
        String refreshIntervalString = Objects.toString(config.get(CONFIG_REFRESH), null);
        refreshInterval = isNotBlank(refreshIntervalString) ? Long.parseLong(refreshIntervalString) : DEFAULT_REFRESH;
        // to override the default quickPoll interval one has to add a
        // parameter to openhab.cfg like ecobee:quickpoll=4000
        String quickPollIntervalString = Objects.toString(config.get(CONFIG_QUICKPOLL), null);
        quickPollInterval = isNotBlank(quickPollIntervalString) ? Long.parseLong(quickPollIntervalString) : DEFAULT_QUICKPOLL;
        // to override the default HTTP timeout one has to add a
        // parameter to openhab.cfg like ecobee:timeout=20000
        String timeoutString = Objects.toString(config.get(CONFIG_TIMEOUT), null);
        if (isNotBlank(timeoutString)) {
            AbstractRequest.setHttpRequestTimeout(Integer.parseInt(timeoutString));
        }
        // to override the default usage of Fahrenheit one has to add a
        // parameter to openhab.cfg, as in ecobee:tempscale=C
        String tempScaleString = Objects.toString(config.get(CONFIG_TEMP_SCALE), null);
        if (isNotBlank(tempScaleString)) {
            try {
                Temperature.setLocalScale(Temperature.Scale.forValue(tempScaleString));
            } catch (IllegalArgumentException iae) {
                throw new ConfigurationException(CONFIG_TEMP_SCALE, "Unsupported temperature scale '" + tempScaleString + "'.");
            }
        }
        Enumeration<String> configKeys = config.keys();
        while (configKeys.hasMoreElements()) {
            String configKey = configKeys.nextElement();
            // don't want to process here ...
            if (CONFIG_GRANULARITY.equals(configKey) || CONFIG_REFRESH.equals(configKey) || CONFIG_QUICKPOLL.equals(configKey) || CONFIG_TIMEOUT.equals(configKey) || CONFIG_TEMP_SCALE.equals(configKey) || "service.pid".equals(configKey)) {
                continue;
            }
            String userid;
            String configKeyTail;
            if (configKey.contains(".")) {
                String[] keyElements = configKey.split("\\.");
                userid = keyElements[0];
                configKeyTail = keyElements[1];
            } else {
                userid = DEFAULT_USER_ID;
                configKeyTail = configKey;
            }
            OAuthCredentials credentials = credentialsCache.get(userid);
            if (credentials == null) {
                credentials = new OAuthCredentials(userid);
                credentialsCache.put(userid, credentials);
            }
            String value = Objects.toString(config.get(configKey), null);
            if (CONFIG_APP_KEY.equals(configKeyTail)) {
                credentials.appKey = value;
            } else if (CONFIG_SCOPE.equals(configKeyTail)) {
                credentials.scope = value;
            } else {
                throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown");
            }
        }
        // Verify the completeness of each OAuthCredentials entry
        // to make sure we can get started.
        boolean properlyConfigured = true;
        for (String userid : credentialsCache.keySet()) {
            OAuthCredentials oauthCredentials = getOAuthCredentials(userid);
            String userString = (DEFAULT_USER_ID.equals(userid)) ? "" : (userid + ".");
            if (oauthCredentials.appKey == null) {
                logger.error("Required ecobee:{}{} is missing.", userString, CONFIG_APP_KEY);
                properlyConfigured = false;
                break;
            }
            if (oauthCredentials.scope == null) {
                logger.error("Required ecobee:{}{} is missing.", userString, CONFIG_SCOPE);
                properlyConfigured = false;
                break;
            }
            // Knowing this OAuthCredentials object is complete, load its tokens from persistent storage.
            oauthCredentials.load();
        }
        setProperlyConfigured(properlyConfigured);
    }
}
Also used : ConfigurationException(org.osgi.service.cm.ConfigurationException)

Example 25 with ConfigurationException

use of org.osgi.service.cm.ConfigurationException in project openhab1-addons by openhab.

the class LgtvBinding method updated.

/**
     * {@inheritDoc}
     */
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    logger.debug("Configuration updated, config {}", config != null ? true : false);
    if (config != null) {
        Enumeration<String> keys = config.keys();
        if (deviceConfigCache == null) {
            deviceConfigCache = new HashMap<String, DeviceConfig>();
        }
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            // don't want to process here ...
            if ("service.pid".equals(key)) {
                continue;
            }
            Matcher matcher = EXTRACT_CONFIG_PATTERN.matcher(key);
            if (!matcher.matches()) {
                logger.debug("given config key '" + key + "' does not follow the expected pattern '<id>.<host|port>'");
                continue;
            }
            matcher.reset();
            matcher.find();
            String deviceId = matcher.group(1);
            DeviceConfig deviceConfig = deviceConfigCache.get(deviceId);
            if (deviceConfig == null) {
                deviceConfig = new DeviceConfig(deviceId);
                deviceConfigCache.put(deviceId, deviceConfig);
            }
            String configKey = matcher.group(2);
            String value = (String) config.get(key);
            if ("host".equals(configKey)) {
                deviceConfig.host = value;
            } else if ("port".equals(configKey)) {
                deviceConfig.port = Integer.valueOf(value);
            } else if ("serverport".equals(configKey)) {
                deviceConfig.localport = Integer.valueOf(value);
            } else if ("pairkey".equals(configKey)) {
                deviceConfig.pairkey = value;
            } else if ("xmldatafiles".equals(configKey)) {
                deviceConfig.xmldatafiles = value;
            } else if ("checkalive".equals(configKey)) {
                deviceConfig.checkalive = Integer.valueOf(value);
            } else {
                throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown");
            }
        }
    }
    // open connection to all receivers
    for (String device : deviceConfigCache.keySet()) {
        LgtvConnection connection = deviceConfigCache.get(device).getConnection();
        if (connection != null) {
            // MF25012014
            connection.addEventListener(this);
            connection.openConnection();
        }
    }
// initializeallitems();
}
Also used : Matcher(java.util.regex.Matcher) ConfigurationException(org.osgi.service.cm.ConfigurationException)

Aggregations

ConfigurationException (org.osgi.service.cm.ConfigurationException)190 Activate (org.apache.felix.scr.annotations.Activate)31 ServiceReference (org.osgi.framework.ServiceReference)30 Matcher (java.util.regex.Matcher)28 Hashtable (java.util.Hashtable)26 Properties (java.util.Properties)22 IOException (java.io.IOException)21 Test (org.junit.Test)21 ManagedService (org.osgi.service.cm.ManagedService)20 FooService (org.apache.felix.ipojo.runtime.core.services.FooService)19 HashMap (java.util.HashMap)17 File (java.io.File)11 URISyntaxException (java.net.URISyntaxException)11 Collection (java.util.Collection)11 HashSet (java.util.HashSet)11 ServiceTracker (org.osgi.util.tracker.ServiceTracker)10 URI (java.net.URI)9 Dictionary (java.util.Dictionary)9 Map (java.util.Map)9 NotFoundException (org.opencastproject.util.NotFoundException)9