Search in sources :

Example 31 with ConfigurationException

use of org.osgi.service.cm.ConfigurationException in project sling by apache.

the class ConfigAnnotationUtil method verifyValueType.

private static <T> void verifyValueType(final Class<T> clazz, final String propertyName, final Object value) throws ConfigurationException {
    final Method method = getDeclaredMethodByName(clazz, toMethodName(propertyName));
    if (method != null) {
        final Class<?> returnType = method.getReturnType();
        final Class<?> valueClass = value.getClass();
        if (!isAssignable(returnType, valueClass)) {
            LOG.error("Invalid value type for {} ({} instead of {})", propertyName, valueClass, returnType);
            throw new ConfigurationException(propertyName, "Value of incorrect type " + valueClass.getName() + " instead of " + returnType.getName());
        }
    }
}
Also used : ConfigurationException(org.osgi.service.cm.ConfigurationException) Method(java.lang.reflect.Method)

Example 32 with ConfigurationException

use of org.osgi.service.cm.ConfigurationException in project aries by apache.

the class DSLTest method testConfigurationsAndRegistrations.

@Test
public void testConfigurationsAndRegistrations() throws InvalidSyntaxException, IOException, InterruptedException {
    ServiceReference<ConfigurationAdmin> serviceReference = bundleContext.getServiceReference(ConfigurationAdmin.class);
    ConfigurationAdmin configurationAdmin = bundleContext.getService(serviceReference);
    /*  For each factory configuration register a service with the property
            key set to the value of the property key that comes with the
            configuration */
    OSGi<ServiceRegistration<Service>> program = configurations("test.configuration").map(d -> d.get("key")).flatMap(key -> register(Service.class, new Service(), new HashMap<String, Object>() {

        {
            put("key", key);
        }
    }));
    OSGiResult<ServiceRegistration<Service>> result = program.run(bundleContext);
    assertEquals(0, bundleContext.getServiceReferences(Service.class, "(test.configuration=*)").size());
    CountDownLatch addedLatch = new CountDownLatch(3);
    ServiceRegistration<?> addedServiceRegistration = bundleContext.registerService(ManagedServiceFactory.class, new ManagedServiceFactory() {

        @Override
        public String getName() {
            return "";
        }

        @Override
        public void updated(String s, Dictionary<String, ?> dictionary) throws ConfigurationException {
            addedLatch.countDown();
        }

        @Override
        public void deleted(String s) {
        }
    }, new Hashtable<String, Object>() {

        {
            put("service.pid", "test.configuration");
        }
    });
    CountDownLatch deletedLatch = new CountDownLatch(3);
    ServiceRegistration<?> deletedServiceRegistration = bundleContext.registerService(ManagedServiceFactory.class, new ManagedServiceFactory() {

        @Override
        public String getName() {
            return "";
        }

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

        @Override
        public void deleted(String s) {
            deletedLatch.countDown();
        }
    }, new Hashtable<String, Object>() {

        {
            put("service.pid", "test.configuration");
        }
    });
    Configuration configuration = configurationAdmin.createFactoryConfiguration("test.configuration");
    configuration.update(new Hashtable<String, Object>() {

        {
            put("key", "service one");
        }
    });
    Configuration configuration2 = configurationAdmin.createFactoryConfiguration("test.configuration");
    configuration2.update(new Hashtable<String, Object>() {

        {
            put("key", "service two");
        }
    });
    Configuration configuration3 = configurationAdmin.createFactoryConfiguration("test.configuration");
    configuration3.update(new Hashtable<String, Object>() {

        {
            put("key", "service three");
        }
    });
    assertTrue(addedLatch.await(10, TimeUnit.SECONDS));
    assertEquals(1, bundleContext.getServiceReferences(Service.class, "(key=service one)").size());
    assertEquals(1, bundleContext.getServiceReferences(Service.class, "(key=service two)").size());
    assertEquals(1, bundleContext.getServiceReferences(Service.class, "(key=service three)").size());
    configuration3.delete();
    configuration2.delete();
    configuration.delete();
    assertTrue(deletedLatch.await(10, TimeUnit.SECONDS));
    assertEquals(0, bundleContext.getServiceReferences(Service.class, "(test.configuration=*)").size());
    addedServiceRegistration.unregister();
    deletedServiceRegistration.unregister();
    result.close();
    bundleContext.ungetService(serviceReference);
}
Also used : OSGi.configurations(org.apache.aries.osgi.functional.OSGi.configurations) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) OSGi.onClose(org.apache.aries.osgi.functional.OSGi.onClose) OSGi.register(org.apache.aries.osgi.functional.OSGi.register) HighestRankingRouter.highest(org.apache.aries.osgi.functional.test.HighestRankingRouter.highest) Configuration(org.osgi.service.cm.Configuration) ConfigurationException(org.osgi.service.cm.ConfigurationException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) OSGi.configuration(org.apache.aries.osgi.functional.OSGi.configuration) ServiceReference(org.osgi.framework.ServiceReference) Hashtable(java.util.Hashtable) ServiceRegistration(org.osgi.framework.ServiceRegistration) ManagedServiceFactory(org.osgi.service.cm.ManagedServiceFactory) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) OSGi.serviceReferences(org.apache.aries.osgi.functional.OSGi.serviceReferences) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) BundleContext(org.osgi.framework.BundleContext) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) OSGi.just(org.apache.aries.osgi.functional.OSGi.just) Assert.assertNull(org.junit.Assert.assertNull) Assert.assertFalse(org.junit.Assert.assertFalse) OSGi.services(org.apache.aries.osgi.functional.OSGi.services) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) OSGi(org.apache.aries.osgi.functional.OSGi) FrameworkUtil(org.osgi.framework.FrameworkUtil) OSGiResult(org.apache.aries.osgi.functional.OSGiResult) Dictionary(java.util.Dictionary) Assert.assertEquals(org.junit.Assert.assertEquals) Configuration(org.osgi.service.cm.Configuration) HashMap(java.util.HashMap) CountDownLatch(java.util.concurrent.CountDownLatch) ManagedServiceFactory(org.osgi.service.cm.ManagedServiceFactory) ConfigurationException(org.osgi.service.cm.ConfigurationException) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) ServiceRegistration(org.osgi.framework.ServiceRegistration) Test(org.junit.Test)

Example 33 with ConfigurationException

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

the class OpenWebIfActionService method updated.

/**
     * {@inheritDoc}
     */
@Override
public void updated(Dictionary<String, ?> properties) throws ConfigurationException {
    if (properties != null) {
        Enumeration<String> keys = properties.keys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            String value = StringUtils.trimToNull((String) properties.get(key));
            if (StringUtils.startsWithIgnoreCase(key, "receiver")) {
                parseConfig(key, value);
            }
        }
        for (OpenWebIfConfig config : OpenWebIf.getConfigs().values()) {
            if (!config.isValid()) {
                throw new ConfigurationException("openwebif", "Invalid OpenWebIf receiver configuration: " + config.toString());
            }
            logger.info("{}", config.toString());
        }
    }
}
Also used : ConfigurationException(org.osgi.service.cm.ConfigurationException) OpenWebIfConfig(org.openhab.action.openwebif.internal.impl.config.OpenWebIfConfig)

Example 34 with ConfigurationException

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

the class ModbusBinding method updated.

@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    try {
        // remove all known items if configuration changed
        clear();
        reconstructConnectionPool();
        if (config == null) {
            logger.debug("Got null config!");
            return;
        }
        Enumeration<String> keys = config.keys();
        Map<String, EndpointPoolConfiguration> slavePoolConfigs = new HashMap<String, EndpointPoolConfiguration>();
        Map<ModbusSlaveEndpoint, EndpointPoolConfiguration> endpointPoolConfigs = new HashMap<ModbusSlaveEndpoint, EndpointPoolConfiguration>();
        while (keys.hasMoreElements()) {
            final String key = keys.nextElement();
            final String value = (String) config.get(key);
            try {
                // don't want to process here ...
                if ("service.pid".equals(key)) {
                    continue;
                }
                Matcher matcher = EXTRACT_MODBUS_CONFIG_PATTERN.matcher(key);
                if (!matcher.matches()) {
                    if ("poll".equals(key)) {
                        if (StringUtils.isNotBlank((String) config.get(key))) {
                            pollInterval = Integer.valueOf((String) config.get(key));
                        }
                    } else if ("writemultipleregisters".equals(key)) {
                        // XXX: ugly to touch base class but kept here for backwards compat
                        // FIXME: should this be deprecated as introduced as slave specific parameter?
                        ModbusSlave.setWriteMultipleRegisters(Boolean.valueOf(config.get(key).toString()));
                    } else {
                        logger.debug("given modbus-slave-config-key '{}' does not follow the expected pattern or 'serial.<slaveId>.<{}>'", key, VALID_CONFIG_KEYS);
                    }
                    continue;
                }
                matcher.reset();
                matcher.find();
                String slave = matcher.group(2);
                ModbusSlave modbusSlave = modbusSlaves.get(slave);
                EndpointPoolConfiguration endpointPoolConfig = slavePoolConfigs.get(slave);
                if (modbusSlave == null) {
                    if (matcher.group(1).equals(TCP_PREFIX)) {
                        modbusSlave = new ModbusTcpSlave(slave, connectionPool);
                    } else if (matcher.group(1).equals(UDP_PREFIX)) {
                        modbusSlave = new ModbusUdpSlave(slave, connectionPool);
                    } else if (matcher.group(1).equals(SERIAL_PREFIX)) {
                        modbusSlave = new ModbusSerialSlave(slave, connectionPool);
                    } else {
                        throw new ConfigurationException(slave, "the given slave type '" + slave + "' is unknown");
                    }
                    endpointPoolConfig = new EndpointPoolConfiguration();
                    // Do not give up if the connection attempt fails on the first time...
                    endpointPoolConfig.setConnectMaxTries(Modbus.DEFAULT_RETRIES);
                    logger.debug("modbusSlave '{}' instanciated", slave);
                    modbusSlaves.put(slave, modbusSlave);
                }
                String configKey = matcher.group(3);
                if ("connection".equals(configKey)) {
                    String[] chunks = value.split(":");
                    Iterator<String> settingIterator = stringArrayIterator(chunks);
                    if (modbusSlave instanceof ModbusIPSlave) {
                        ((ModbusIPSlave) modbusSlave).setHost(settingIterator.next());
                        //
                        // Defaults for endpoint and slave
                        //
                        modbusSlave.setRetryDelayMillis(DEFAULT_TCP_INTER_TRANSACTION_DELAY_MILLIS);
                        endpointPoolConfig.setPassivateBorrowMinMillis(DEFAULT_TCP_INTER_TRANSACTION_DELAY_MILLIS);
                        //
                        try {
                            ((ModbusIPSlave) modbusSlave).setPort(Integer.valueOf(settingIterator.next()));
                            long passivateBorrowMinMillis = Long.parseLong(settingIterator.next());
                            modbusSlave.setRetryDelayMillis(passivateBorrowMinMillis);
                            endpointPoolConfig.setPassivateBorrowMinMillis(passivateBorrowMinMillis);
                            endpointPoolConfig.setReconnectAfterMillis(Integer.parseInt(settingIterator.next()));
                            // time to wait before trying connect closed connection. Note that
                            // ModbusSlaveConnectionFactoryImpl makes sure that max{passivateBorrowMinMillis, this
                            // parameter} is waited between connection attempts
                            endpointPoolConfig.setInterConnectDelayMillis(Long.parseLong(settingIterator.next()));
                            endpointPoolConfig.setConnectMaxTries(Integer.parseInt(settingIterator.next()));
                            endpointPoolConfig.setConnectTimeoutMillis(Integer.parseInt(settingIterator.next()));
                        } catch (NoSuchElementException e) {
                        // Some of the optional parameters are missing -- it's ok!
                        }
                        if (settingIterator.hasNext()) {
                            String errMsg = String.format("%s Has too many colon (:) separated connection settings for a tcp/udp modbus slave. " + "Expecting at most 6 parameters: hostname (mandatory) and " + "optionally (in this order) port number, " + "interTransactionDelayMillis, reconnectAfterMillis," + "interConnectDelayMillis, connectMaxTries, connectTimeout.", key);
                            throw new ConfigurationException(key, errMsg);
                        }
                    } else if (modbusSlave instanceof ModbusSerialSlave) {
                        SerialParameters serialParameters = new SerialParameters();
                        serialParameters.setPortName(settingIterator.next());
                        //
                        // Defaults for endpoint and slave
                        //
                        // never "disconnect" (close/open serial
                        endpointPoolConfig.setReconnectAfterMillis(-1);
                        // port)
                        // serial connection between borrows
                        modbusSlave.setRetryDelayMillis(DEFAULT_SERIAL_INTER_TRANSACTION_DELAY_MILLIS);
                        endpointPoolConfig.setPassivateBorrowMinMillis(DEFAULT_SERIAL_INTER_TRANSACTION_DELAY_MILLIS);
                        //
                        try {
                            serialParameters.setBaudRate(settingIterator.next());
                            serialParameters.setDatabits(settingIterator.next());
                            serialParameters.setParity(settingIterator.next());
                            serialParameters.setStopbits(settingIterator.next());
                            serialParameters.setEncoding(settingIterator.next());
                            // time to wait between connection passive+borrow, i.e. time to wait between
                            // transactions
                            long passivateBorrowMinMillis = Long.parseLong(settingIterator.next());
                            modbusSlave.setRetryDelayMillis(passivateBorrowMinMillis);
                            endpointPoolConfig.setPassivateBorrowMinMillis(passivateBorrowMinMillis);
                            serialParameters.setReceiveTimeoutMillis(settingIterator.next());
                            serialParameters.setFlowControlIn(settingIterator.next());
                            serialParameters.setFlowControlOut(settingIterator.next());
                        } catch (NoSuchElementException e) {
                        // Some of the optional parameters are missing -- it's ok!
                        }
                        if (settingIterator.hasNext()) {
                            String errMsg = String.format("%s Has too many colon (:) separated connection settings for a serial modbus slave. " + "Expecting at most 9 parameters (got %d): devicePort (mandatory), " + "and 0 or more optional parameters (in this order): " + "baudRate, dataBits, parity, stopBits, " + "encoding, interTransactionWaitMillis, " + "receiveTimeoutMillis, flowControlIn, flowControlOut", key, chunks.length);
                            throw new ConfigurationException(key, errMsg);
                        }
                        ((ModbusSerialSlave) modbusSlave).setSerialParameters(serialParameters);
                    }
                } else if ("start".equals(configKey)) {
                    modbusSlave.setStart(Integer.valueOf(value));
                } else if ("length".equals(configKey)) {
                    modbusSlave.setLength(Integer.valueOf(value));
                } else if ("id".equals(configKey)) {
                    modbusSlave.setId(Integer.valueOf(value));
                } else if ("type".equals(configKey)) {
                    if (ArrayUtils.contains(ModbusBindingProvider.SLAVE_DATA_TYPES, value)) {
                        modbusSlave.setType(value);
                    } else {
                        throw new ConfigurationException(configKey, "the given slave type '" + value + "' is invalid");
                    }
                } else if ("valuetype".equals(configKey)) {
                    if (ArrayUtils.contains(ModbusBindingProvider.VALUE_TYPES, value)) {
                        modbusSlave.setValueType(value);
                    } else {
                        throw new ConfigurationException(configKey, "the given value type '" + value + "' is invalid");
                    }
                } else if ("rawdatamultiplier".equals(configKey)) {
                    modbusSlave.setRawDataMultiplier(Double.valueOf(value.toString()));
                } else if ("updateunchangeditems".equals(configKey)) {
                    modbusSlave.setUpdateUnchangedItems(Boolean.valueOf(value.toString()));
                } else if ("postundefinedonreaderror".equals(configKey)) {
                    modbusSlave.setPostUndefinedOnReadError(Boolean.valueOf(value.toString()));
                } else {
                    throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown");
                }
                modbusSlaves.put(slave, modbusSlave);
                slavePoolConfigs.put(slave, endpointPoolConfig);
            } catch (Exception e) {
                String errMsg = String.format("Exception when parsing configuration parameter %s = %s  --  %s %s", key, value, e.getClass().getName(), e.getMessage());
                logger.error(errMsg);
                throw new ConfigurationException(key, errMsg);
            }
        }
        // Finally, go through each slave definition, and combine the slave pool configurations
        for (Entry<String, EndpointPoolConfiguration> slaveEntry : slavePoolConfigs.entrySet()) {
            String slave = slaveEntry.getKey();
            EndpointPoolConfiguration poolConfiguration = slaveEntry.getValue();
            ModbusSlaveEndpoint endpoint = modbusSlaves.get(slave).getEndpoint();
            EndpointPoolConfiguration existingPoolConfiguration = endpointPoolConfigs.get(endpoint);
            // Do we have two slaves with same endpoint, but different pool configuration parameters? Warn if we do.
            if (existingPoolConfiguration != null && !existingPoolConfiguration.equals(poolConfiguration)) {
                logger.warn("Slave {} (endpoint {}) has different retry/connection delay " + "(EndpointPoolConfiguration) etc. settings. Replacing {} with {}", slave, endpoint, existingPoolConfiguration, poolConfiguration);
            }
            endpointPoolConfigs.put(endpoint, poolConfiguration);
        }
        connectionFactory.applyEndpointPoolConfigs(endpointPoolConfigs);
        logger.debug("Parsed the following slave->endpoint configurations: {}. If the endpoint is same, " + "connections are shared between the instances.", slavePoolConfigs);
        logger.debug("Parsed the following pool configurations: {}", endpointPoolConfigs);
        logger.debug("config looked good");
        setProperlyConfigured(true);
    } catch (ConfigurationException ce) {
        setProperlyConfigured(false);
        throw ce;
    }
}
Also used : HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ModbusSlaveEndpoint(org.openhab.binding.modbus.internal.pooling.ModbusSlaveEndpoint) Matcher(java.util.regex.Matcher) ConfigurationException(org.osgi.service.cm.ConfigurationException) NoSuchElementException(java.util.NoSuchElementException) SerialParameters(net.wimpi.modbus.util.SerialParameters) EndpointPoolConfiguration(org.openhab.binding.modbus.internal.pooling.EndpointPoolConfiguration) ConfigurationException(org.osgi.service.cm.ConfigurationException) NoSuchElementException(java.util.NoSuchElementException)

Example 35 with ConfigurationException

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

the class MyStromEcoPowerBinding method updated.

/**
     * {@inheritDoc}
     */
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    if (config != null) {
        // to override the default refresh interval one has to add a
        // parameter to openhab.cfg like
        // <bindingName>:refresh=<intervalInMs>
        String refreshIntervalString = (String) config.get("refresh");
        if (StringUtils.isNotBlank(refreshIntervalString)) {
            refreshInterval = Long.parseLong(refreshIntervalString);
        }
        // read further config parameters here ...
        // read user name
        String userName = (String) config.get("userName");
        if (StringUtils.isNotBlank(userName)) {
            this.userName = userName;
        } else {
            throw new ConfigurationException("userName", "The userName to connect to myStrom must be specified in config file");
        }
        String password = (String) config.get("password");
        if (StringUtils.isNotBlank(password)) {
            this.password = password;
        } else {
            throw new ConfigurationException("password", "The password to connect to myStrom must be specified in config file");
        }
        if (this.devMode) {
            this.mystromClient = new MockMystromClient();
        } else {
            this.mystromClient = new MystromClient(this.userName, this.password, logger);
        }
        if (ChangeStateJob.MystromClient == null) {
            ChangeStateJob.MystromClient = this.mystromClient;
        }
        setProperlyConfigured(true);
        // do a discovery of all mystrom eco power to get id of devices
        try {
            this.mystromDiscovery();
        } catch (IOException e) {
            logger.error("Error doing discovery of your devices", e);
        }
    }
}
Also used : MockMystromClient(org.openhab.binding.mystromecopower.internal.api.mock.MockMystromClient) IMystromClient(org.openhab.binding.mystromecopower.internal.api.IMystromClient) MystromClient(org.openhab.binding.mystromecopower.internal.api.MystromClient) ConfigurationException(org.osgi.service.cm.ConfigurationException) MockMystromClient(org.openhab.binding.mystromecopower.internal.api.mock.MockMystromClient) 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