Search in sources :

Example 6 with ConfigurationException

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

the class PrimareBinding method updated.

/**
     * {@inheritDoc}
     */
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    logger.debug("Configuration updated, valid configuration {}", (config != null ? "exists" : "does not exist"));
    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|model>'");
                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 ("serial".equals(configKey)) {
                deviceConfig.serialport = value;
            } else if ("model".equals(configKey)) {
                String model = value.toUpperCase();
                deviceConfig.model = value.toUpperCase();
            } else {
                throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown");
            }
        }
        // open connection to all receivers
        for (String device : deviceConfigCache.keySet()) {
            PrimareConnector connector = deviceConfigCache.get(device).getInitializedConnector();
            if (connector != null) {
                try {
                    connector.connect();
                    connector.addEventListener(this);
                } catch (Exception e) {
                    logger.warn("failed to connect to {} after configuration update", device.toString());
                }
            }
        }
        for (PrimareBindingProvider provider : this.providers) {
            for (String itemName : provider.getItemNames()) {
                initializeItem(itemName);
            }
        }
    }
}
Also used : PrimareBindingProvider(org.openhab.binding.primare.PrimareBindingProvider) Matcher(java.util.regex.Matcher) ConfigurationException(org.osgi.service.cm.ConfigurationException) PrimareConnector(org.openhab.binding.primare.internal.protocol.PrimareConnector) ConfigurationException(org.osgi.service.cm.ConfigurationException)

Example 7 with ConfigurationException

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

the class PowerMaxBinding method updated.

/**
     * {@inheritDoc}
     */
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    logger.debug("updated(): updating configuration");
    closeConnection();
    serialPort = null;
    ipAddress = null;
    tcpPort = 0;
    motionOffDelay = DEFAULT_MOTION_OFF_DELAY;
    allowArming = false;
    allowDisarming = false;
    forceStandardMode = false;
    panelType = PowerMaxPanelType.POWERMAX_PRO;
    autoSyncTime = false;
    pinCode = null;
    PowerMaxReceiveType.POWERLINK.setHandlerClass(PowerMaxPowerlinkMessage.class);
    if (config != null) {
        String serialPortString = Objects.toString(config.get("serialPort"), null);
        if (StringUtils.isNotBlank(serialPortString)) {
            serialPort = serialPortString;
        }
        String ipString = Objects.toString(config.get("ip"), null);
        if (StringUtils.isNotBlank(ipString)) {
            ipAddress = ipString;
        }
        if (serialPort == null && ipAddress == null) {
            logger.warn("PowerMax alarm binding: one connection type (Serial Port or IP Address) must be defined");
            this.setProperlyConfigured(false);
            throw new ConfigurationException(null, "one connection type (Serial Port or IP Address) must be defined");
        }
        if (serialPort != null && ipAddress != null) {
            logger.warn("PowerMax alarm binding: can only configure one connection type at a time: Serial Port or IP Address");
            this.setProperlyConfigured(false);
            throw new ConfigurationException(null, "can only configure one connection type at a time: Serial Port or IP Address");
        }
        if (ipAddress != null) {
            String tcpPortString = Objects.toString(config.get("tcpPort"), null);
            if (StringUtils.isNotBlank(tcpPortString)) {
                try {
                    tcpPort = Integer.parseInt(tcpPortString);
                } catch (NumberFormatException numberFormatException) {
                    tcpPort = 0;
                    logger.warn("PowerMax alarm binding: TCP port not configured correctly (number expected, received '{}')", tcpPortString);
                    this.setProperlyConfigured(false);
                    throw new ConfigurationException("tcpPort", "TCP port not configured correctly (number expected, received '" + tcpPortString + "')");
                }
            }
        }
        String motionOffDelayString = Objects.toString(config.get("motionOffDelay"), null);
        if (StringUtils.isNotBlank(motionOffDelayString)) {
            try {
                motionOffDelay = Integer.parseInt(motionOffDelayString) * 60000;
            } catch (NumberFormatException numberFormatException) {
                motionOffDelay = DEFAULT_MOTION_OFF_DELAY;
                logger.warn("PowerMax alarm binding: motion off delay not configured correctly (number expected, received '{}')", motionOffDelayString);
            }
        }
        String allowArmingString = Objects.toString(config.get("allowArming"), null);
        if (StringUtils.isNotBlank(allowArmingString)) {
            allowArming = Boolean.valueOf(allowArmingString);
        }
        String allowDisarmingString = Objects.toString(config.get("allowDisarming"), null);
        if (StringUtils.isNotBlank(allowDisarmingString)) {
            allowDisarming = Boolean.valueOf(allowDisarmingString);
        }
        String forceStandardModeString = Objects.toString(config.get("forceStandardMode"), null);
        if (StringUtils.isNotBlank(forceStandardModeString)) {
            forceStandardMode = Boolean.valueOf(forceStandardModeString);
            PowerMaxReceiveType.POWERLINK.setHandlerClass(forceStandardMode ? PowerMaxBaseMessage.class : PowerMaxPowerlinkMessage.class);
        }
        String panelTypeString = Objects.toString(config.get("panelType"), null);
        if (StringUtils.isNotBlank(panelTypeString)) {
            try {
                panelType = PowerMaxPanelType.fromLabel(panelTypeString);
            } catch (IllegalArgumentException exception) {
                panelType = PowerMaxPanelType.POWERMAX_PRO;
                logger.warn("PowerMax alarm binding: panel type not configured correctly");
            }
        }
        PowerMaxPanelSettings.initPanelSettings(panelType);
        String autoSyncTimeString = Objects.toString(config.get("autoSyncTime"), null);
        if (StringUtils.isNotBlank(autoSyncTimeString)) {
            autoSyncTime = Boolean.valueOf(autoSyncTimeString);
        }
        String pinCodeString = Objects.toString(config.get("pinCode"), null);
        if (StringUtils.isNotBlank(pinCodeString)) {
            pinCode = pinCodeString;
        }
        this.setProperlyConfigured(true);
    }
}
Also used : ConfigurationException(org.osgi.service.cm.ConfigurationException) PowerMaxBaseMessage(org.openhab.binding.powermax.internal.message.PowerMaxBaseMessage) PowerMaxPowerlinkMessage(org.openhab.binding.powermax.internal.message.PowerMaxPowerlinkMessage)

Example 8 with ConfigurationException

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

the class CalDavLoaderImpl method updated.

@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    if (config == null) {
        log.debug("Update was called with a null configuration for CalDAV IO.");
        return;
    }
    log.debug("Update was called for CalDAV IO.");
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true);
    Map<String, CalDavConfig> configMap = new HashMap<String, CalDavConfig>();
    Enumeration<String> iter = config.keys();
    while (iter.hasMoreElements()) {
        String key = iter.nextElement();
        if (key.equals("service.pid")) {
            continue;
        }
        log.trace("processing configuration parameter: {}", key);
        if (key.equals(PROP_TIMEZONE)) {
            String newTimeZoneStr = Objects.toString(config.get(key), null);
            if (StringUtils.isBlank(newTimeZoneStr)) {
                log.info("The {} setting was configured with an empty value. Default value '{}' will be used instead.", PROP_TIMEZONE, defaultTimeZone);
                continue;
            }
            DateTimeZone newTimeZone = DateTimeZone.forID(newTimeZoneStr);
            if (newTimeZone == null) {
                log.warn("Invalid timezone value: {}", newTimeZoneStr);
                throw new ConfigurationException(PROP_TIMEZONE, "Invalid timezone value: " + newTimeZoneStr);
            }
            log.debug("Overriding default timezone {} with {}", defaultTimeZone, newTimeZone);
            defaultTimeZone = newTimeZone;
            continue;
        }
        String[] keys = key.split(":");
        if (keys.length != 2) {
            log.warn("Unable to parse configuration parameter: {}", key);
            throw new ConfigurationException("CalDAV IO", "Unable to parse configuration parameter: " + key);
        }
        String id = keys[0];
        String paramKey = keys[1];
        CalDavConfig calDavConfig = configMap.get(id);
        if (calDavConfig == null) {
            calDavConfig = new CalDavConfig();
            configMap.put(id, calDavConfig);
        }
        String value = Objects.toString(config.get(key), null);
        calDavConfig.setKey(id);
        if (paramKey.equals(PROP_USERNAME)) {
            calDavConfig.setUsername(value);
        } else if (paramKey.equals(PROP_PASSWORD)) {
            calDavConfig.setPassword(value);
        } else if (paramKey.equals(PROP_URL)) {
            calDavConfig.setUrl(value);
        } else if (paramKey.equals(PROP_RELOAD_INTERVAL)) {
            calDavConfig.setReloadMinutes(Integer.parseInt(value));
        } else if (paramKey.equals(PROP_PRELOAD_TIME)) {
            calDavConfig.setPreloadMinutes(Integer.parseInt(value));
        } else if (paramKey.equals(PROP_HISTORIC_LOAD_TIME)) {
            calDavConfig.setHistoricLoadMinutes(Integer.parseInt(value));
        } else if (paramKey.equals(PROP_LAST_MODIFIED_TIMESTAMP_VALID)) {
            calDavConfig.setLastModifiedFileTimeStampValid(BooleanUtils.toBoolean(value));
        } else if (paramKey.equals(PROP_DISABLE_CERTIFICATE_VERIFICATION)) {
            calDavConfig.setDisableCertificateVerification(BooleanUtils.toBoolean(value));
        } else if (paramKey.equals(PROP_CHARSET)) {
            try {
                Charset.forName(value);
                calDavConfig.setCharset(value);
            } catch (UnsupportedCharsetException e) {
                log.warn("Character set not valid: {}", value);
            }
        }
    }
    // verify if all required parameters are set
    for (String id : configMap.keySet()) {
        if (StringUtils.isEmpty(configMap.get(id).getUrl())) {
            log.warn("A URL must be configured for calendar '{}'", id);
            throw new ConfigurationException("CalDAV IO", "A URL must be configured for calendar '" + id + "'");
        }
        log.trace("config for calendar '{}': {}", id, configMap.get(id));
    }
    // initialize event cache
    for (CalDavConfig calDavConfig : configMap.values()) {
        final CalendarRuntime eventRuntime = new CalendarRuntime();
        eventRuntime.setConfig(calDavConfig);
        File cachePath = Util.getCachePath(calDavConfig.getKey());
        if (!cachePath.exists() && !cachePath.mkdirs()) {
            log.warn("cannot create directory ({}) for calendar caching (missing rights?)", cachePath.getAbsoluteFile());
            continue;
        }
        EventStorage.getInstance().getEventCache().put(calDavConfig.getKey(), eventRuntime);
    }
    log.info("CalDAV IO is properly configured.");
    setProperlyConfigured(true);
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConfigurationException(org.osgi.service.cm.ConfigurationException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) CalendarRuntime(org.openhab.io.caldav.internal.EventStorage.CalendarRuntime) File(java.io.File) DateTimeZone(org.joda.time.DateTimeZone)

Example 9 with ConfigurationException

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

the class DropboxSynchronizer method updated.

@SuppressWarnings("rawtypes")
@Override
public void updated(Dictionary config) throws ConfigurationException {
    if (config == null) {
        logger.debug("Updated() was called with a null config!");
        return;
    }
    isProperlyConfigured = false;
    String appKeyString = Objects.toString(config.get("appkey"), null);
    if (isNotBlank(appKeyString)) {
        DropboxSynchronizer.appKey = appKeyString;
    }
    String appSecretString = Objects.toString(config.get("appsecret"), null);
    if (isNotBlank(appSecretString)) {
        DropboxSynchronizer.appSecret = appSecretString;
    }
    String pat = Objects.toString(config.get("personalAccessToken"), null);
    if (isNotBlank(pat)) {
        DropboxSynchronizer.personalAccessToken = pat;
    }
    if (logger.isDebugEnabled()) {
        StringBuffer message = new StringBuffer();
        message.append("Authentication parameters to be used:\r\n");
        if (isNotBlank(pat)) {
            message.append("     Personal access token = " + pat + "\r\n");
        } else {
            message.append("     appkey = " + appKeyString + "\r\n");
            message.append("  appsecret = " + appSecretString + "\r\n");
        }
        logger.debug(message.toString());
    }
    if (isBlank(pat) && (isBlank(appKeyString) || isBlank(appSecretString))) {
        throw new ConfigurationException("dropbox:authentication", "The Dropbox authentication parameters are incorrect!  The parameter 'personalAccesstoken' must be set, or both of the parameters 'appkey' and 'appsecret' must be set. Please check your configuration.");
    }
    String fakeModeString = Objects.toString(config.get("fakemode"), null);
    if (isNotBlank(fakeModeString)) {
        DropboxSynchronizer.fakeMode = BooleanUtils.toBoolean(fakeModeString);
    }
    String contentDirString = Objects.toString(config.get("contentdir"), null);
    if (isNotBlank(contentDirString)) {
        DropboxSynchronizer.contentDir = contentDirString;
    }
    logger.debug("contentdir: {}", contentDir);
    String uploadIntervalString = Objects.toString(config.get("uploadInterval"), null);
    if (isNotBlank(uploadIntervalString)) {
        DropboxSynchronizer.uploadInterval = uploadIntervalString;
    }
    String downloadIntervalString = Objects.toString(config.get("downloadInterval"), null);
    if (isNotBlank(downloadIntervalString)) {
        DropboxSynchronizer.downloadInterval = downloadIntervalString;
    }
    String syncModeString = Objects.toString(config.get("syncmode"), null);
    if (isNotBlank(syncModeString)) {
        try {
            DropboxSynchronizer.syncMode = DropboxSyncMode.valueOf(syncModeString.toUpperCase());
        } catch (IllegalArgumentException iae) {
            throw new ConfigurationException("dropbox:syncmode", "Unknown SyncMode '" + syncModeString + "'. Valid SyncModes are 'DROPBOX_TO_LOCAL', 'LOCAL_TO_DROPBOX' and 'BIDIRECTIONAL'.");
        }
    }
    String uploadFilterString = Objects.toString(config.get("uploadfilter"), null);
    if (isNotBlank(uploadFilterString)) {
        String[] newFilterElements = uploadFilterString.split(",");
        uploadFilterElements = Arrays.asList(newFilterElements);
    }
    String downloadFilterString = Objects.toString(config.get("downloadfilter"), null);
    if (isNotBlank(downloadFilterString)) {
        String[] newFilterElements = downloadFilterString.split(",");
        downloadFilterElements = Arrays.asList(newFilterElements);
    }
    // we got this far, so we define this synchronizer as properly configured ...
    isProperlyConfigured = true;
    logger.debug("Bundle is properly configured. Activating synchronizer.");
    activateSynchronizer();
}
Also used : ConfigurationException(org.osgi.service.cm.ConfigurationException)

Example 10 with ConfigurationException

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

the class GPIOLinux method updated.

/**
     * Called when <code>Configuration Admin</code> detects configuration
     * change. Sets manually configured mount points for <code>sysfs</code>
     * pseudo file systems, overwrites this what was discovered. Also set
     * default debounce interval if exist.
     */
public void updated(Dictionary<String, ?> properties) throws ConfigurationException {
    if (properties != null) {
        String propSysFS = Objects.toString(properties.get(SYSFS_VFSTYPE), null);
        if (propSysFS != null) {
            try {
                if (isFSMounted(SYSFS_VFSTYPE, propSysFS)) {
                    sysFS = propSysFS;
                } else {
                    logger.error("Configured mount point is invalid, '" + SYSFS_VFSTYPE + "' isn't mounted at '" + propSysFS + "'");
                    throw new ConfigurationException(SYSFS_VFSTYPE, "Configured mount point is invalid, '" + SYSFS_VFSTYPE + "' isn't mounted at '" + propSysFS + "'");
                }
            } catch (IOException e) {
                logger.error("Checking whether pseudo file system '" + SYSFS_VFSTYPE + "' is mounted or not failed. " + "If 'procfs' isn't mounted this error can be omitted. Error: " + e.getMessage());
                sysFS = propSysFS;
            }
        }
        String propDebounceInterval = Objects.toString(properties.get(PROP_DEBOUNCE_INTERVAL), null);
        if (propDebounceInterval != null) {
            try {
                long debounceInterval = Long.parseLong(propDebounceInterval);
                if (debounceInterval >= 0) {
                    defaultDebounceInterval = debounceInterval;
                } else {
                    logger.error("Configured " + PROP_DEBOUNCE_INTERVAL + " is invalid, must not be negative value");
                    throw new ConfigurationException(PROP_DEBOUNCE_INTERVAL, "Configured " + PROP_DEBOUNCE_INTERVAL + " is invalid, must not be negative value");
                }
            } catch (NumberFormatException e) {
                logger.error("Configured " + PROP_DEBOUNCE_INTERVAL + " is invalid, must be numeric value");
                throw new ConfigurationException(PROP_DEBOUNCE_INTERVAL, "Configured " + PROP_DEBOUNCE_INTERVAL + " is invalid, must be numeric value");
            }
        }
        String propForce = Objects.toString(properties.get(PROP_FORCE), null);
        if (propForce != null) {
            defaultForce = Boolean.parseBoolean(propForce);
        }
    }
}
Also used : ConfigurationException(org.osgi.service.cm.ConfigurationException) IOException(java.io.IOException)

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