List of usage examples for java.util Dictionary keys
public abstract Enumeration<K> keys();
From source file:org.openhab.binding.netatmo.internal.NetatmoBinding.java
/** * {@inheritDoc}//from www . ja v a 2 s . c o m */ @Override public void updated(final Dictionary<String, ?> config) throws ConfigurationException { if (config != null) { final String refreshIntervalString = (String) config.get(CONFIG_REFRESH); if (isNotBlank(refreshIntervalString)) { this.refreshInterval = Long.parseLong(refreshIntervalString); } Enumeration<String> configKeys = config.keys(); while (configKeys.hasMoreElements()) { String configKey = configKeys.nextElement(); // the config-key enumeration contains additional keys that we // don't want to process here ... if (CONFIG_REFRESH.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(); credentialsCache.put(userid, credentials); } String value = (String) config.get(configKeyTail); if (CONFIG_CLIENT_ID.equals(configKeyTail)) { credentials.clientId = value; } else if (CONFIG_CLIENT_SECRET.equals(configKeyTail)) { credentials.clientSecret = value; } else if (CONFIG_REFRESH_TOKEN.equals(configKeyTail)) { credentials.refreshToken = value; } else if (CONFIG_PRESSURE_UNIT.equals(configKeyTail)) { try { pressureUnit = NetatmoPressureUnit.fromString(value); } catch (IllegalArgumentException e) { throw new ConfigurationException(configKey, "the value '" + value + "' is not valid for the configKey '" + configKey + "'"); } } else if (CONFIG_UNIT_SYSTEM.equals(configKeyTail)) { try { unitSystem = NetatmoUnitSystem.fromString(value); } catch (IllegalArgumentException e) { throw new ConfigurationException(configKey, "the value '" + value + "' is not valid for the configKey '" + configKey + "'"); } } else { throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown"); } } setProperlyConfigured(true); } }
From source file:org.openhab.binding.nest.internal.NestBinding.java
/** * {@inheritDoc}/*from w ww .j a va 2 s .c o m*/ */ @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 nest:refresh=120000 String refreshIntervalString = (String) config.get(CONFIG_REFRESH); if (isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } Enumeration<String> configKeys = config.keys(); while (configKeys.hasMoreElements()) { String configKey = (String) configKeys.nextElement(); // the config-key enumeration contains additional keys that we // don't want to process here ... if (CONFIG_REFRESH.equals(configKey) || "service.pid".equals(configKey)) { continue; } String userid = DEFAULT_USER_ID; String configKeyTail = configKey; OAuthCredentials credentials = credentialsCache.get(userid); if (credentials == null) { credentials = new OAuthCredentials(userid); credentialsCache.put(userid, credentials); } String value = (String) config.get(configKey); if (CONFIG_CLIENT_ID.equals(configKeyTail)) { credentials.clientId = value; } else if (CONFIG_CLIENT_SECRET.equals(configKeyTail)) { credentials.clientSecret = value; } else if (CONFIG_PIN_CODE.equals(configKeyTail)) { credentials.pinCode = 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.clientId == null) { logger.error("Required nest:{}{} is missing.", userString, CONFIG_CLIENT_ID); properlyConfigured = false; break; } if (oauthCredentials.clientSecret == null) { logger.error("Required nest:{}{} is missing.", userString, CONFIG_CLIENT_SECRET); properlyConfigured = false; break; } if (oauthCredentials.pinCode == null) { logger.error("Required nest:{}{} is missing.", userString, CONFIG_PIN_CODE); properlyConfigured = false; break; } // Load persistently stored values for this credential set oauthCredentials.load(); } setProperlyConfigured(properlyConfigured); } }
From source file:org.openhab.binding.epsonprojector.internal.EpsonProjectorBinding.java
/** * @{inheritDoc/*from w w w . j a v a2s . co m*/ */ @Override public void updated(Dictionary<String, ?> config) throws ConfigurationException { logger.debug("Configuration updated, config {}", config != null ? true : false); if (config != null) { if (deviceConfigCache == null) { deviceConfigCache = new HashMap<String, DeviceConfig>(); } String granularityString = (String) config.get("granularity"); if (StringUtils.isNotBlank(granularityString)) { granularity = Integer.parseInt(granularityString); } 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 matcher = EXTRACT_CONFIG_PATTERN.matcher(key); if (!matcher.matches()) { logger.warn("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) { logger.debug("Added new device {}", deviceId); deviceConfig = new DeviceConfig(deviceId); deviceConfigCache.put(deviceId, deviceConfig); } String configKey = matcher.group(2); String value = (String) config.get(key); if ("serialPort".equals(configKey)) { deviceConfig.serialPort = value; } else 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"); } } setProperlyConfigured(true); } }
From source file:org.openhab.binding.http.internal.HttpBinding.java
/** * {@inheritDoc}/*from w w w .j a va 2 s . c o m*/ */ @SuppressWarnings("rawtypes") public void updated(Dictionary config) throws ConfigurationException { synchronized (itemCacheLock) { // clear any existing cache item configs itemCache.clear(); if (config != null) { String timeoutString = (String) config.get(CONFIG_TIMEOUT); if (StringUtils.isNotBlank(timeoutString)) { timeout = Integer.parseInt(timeoutString); } String granularityString = (String) config.get(CONFIG_GRANULARITY); if (StringUtils.isNotBlank(granularityString)) { granularity = Integer.parseInt(granularityString); } // Parse page cache config @SuppressWarnings("unchecked") 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 (CONFIG_TIMEOUT.equals(key) || CONFIG_GRANULARITY.equals(key) || "service.pid".equals(key)) { continue; } Matcher matcher = EXTRACT_CACHE_CONFIG_PATTERN.matcher(key); if (!matcher.matches()) { logger.error("given config key '" + key + "' does not follow the expected pattern '<id>.<url|updateInterval>'"); continue; } matcher.reset(); matcher.find(); String cacheId = matcher.group(1); CacheConfig cacheConfig = itemCache.get(cacheId); if (cacheConfig == null) { cacheConfig = new CacheConfig(cacheId); itemCache.put(cacheId, cacheConfig); } String configKey = matcher.group(2); String value = (String) config.get(key); if ("url".equals(configKey)) { matcher = EXTRACT_CACHE_CONFIG_URL.matcher(value); if (!matcher.matches()) { throw new ConfigurationException(configKey, "given config url '" + configKey + "' does not follow the expected pattern '<id>.url[{<headers>}]'"); } cacheConfig.url = matcher.group(1); cacheConfig.headers = parseHttpHeaders(matcher.group(2)); } else if ("updateInterval".equals(configKey)) { cacheConfig.updateInterval = Integer.valueOf(value); } else { throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown"); } } } } }
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/*from w w w. j a v a 2s .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.codice.ddf.ui.admin.api.ConfigurationAdminTest.java
/** * Tests the {@link ConfigurationAdmin#getProperties(String)} and * {@link ConfigurationAdmin#getPropertiesForLocation(String, String)} methods * * @throws Exception//from w ww . j a v a2 s.c o m */ @Test public void testGetProperties() throws Exception { org.osgi.service.cm.ConfigurationAdmin testConfigAdmin = mock(org.osgi.service.cm.ConfigurationAdmin.class); ConfigurationAdmin configAdmin = new ConfigurationAdmin(testConfigAdmin); Configuration testConfig = mock(Configuration.class); Dictionary<String, Object> testProp = mock(Dictionary.class); Enumeration<String> testKeys = mock(Enumeration.class); when(testConfig.getProperties()).thenReturn(testProp); when(testProp.get(TEST_KEY)).thenReturn(TEST_VALUE); when(testProp.keys()).thenReturn(testKeys); when(testKeys.hasMoreElements()).thenReturn(true).thenReturn(false); when(testKeys.nextElement()).thenReturn(TEST_KEY); when(testConfigAdmin.getConfiguration(TEST_PID, null)).thenReturn(testConfig); Map<String, Object> result = configAdmin.getProperties(TEST_PID); assertThat("Should return the given properties.", (String) result.get(TEST_KEY), is(TEST_VALUE)); }
From source file:org.codice.ddf.admin.core.impl.AdminConsoleServiceTest.java
/** * Tests the {@link AdminConsoleService#getProperties(String)} and {@link * AdminConsoleService#getPropertiesForLocation(String, String)} methods * * @throws Exception//w w w . java 2 s . c o m */ @Test public void testGetProperties() throws Exception { org.osgi.service.cm.ConfigurationAdmin testConfigAdmin = mock(org.osgi.service.cm.ConfigurationAdmin.class); AdminConsoleService configAdmin = new AdminConsoleService(testConfigAdmin, configurationAdminImpl) { @Override public boolean isPermittedToViewService(String servicePid) { return true; } }; Configuration testConfig = mock(Configuration.class); Dictionary<String, Object> testProp = mock(Dictionary.class); Enumeration<String> testKeys = mock(Enumeration.class); when(testConfig.getProperties()).thenReturn(testProp); when(testProp.get(TEST_KEY)).thenReturn(TEST_VALUE); when(testProp.keys()).thenReturn(testKeys); when(testKeys.hasMoreElements()).thenReturn(true).thenReturn(false); when(testKeys.nextElement()).thenReturn(TEST_KEY); when(testConfigAdmin.getConfiguration(TEST_PID, null)).thenReturn(testConfig); Map<String, Object> result = configAdmin.getProperties(TEST_PID); assertThat("Should return the given properties.", result.get(TEST_KEY), is(TEST_VALUE)); }
From source file:org.energy_home.jemma.ah.internal.configurator.Configuratore.java
public void exportConfiguration(OutputStream os) throws Exception { // Ottiene un riferimento al servizio Configuration Admin ServiceReference sr = bc.getServiceReference(ConfigurationAdmin.class.getName()); ConfigurationAdmin configurationAdmin = (ConfigurationAdmin) bc.getService(sr); // test();//w w w . j av a 2 s .co m // Ottiene un array contenente tutte le configurazioni salvate nel // Configuration Admin Configuration[] configs = configurationAdmin.listConfigurations(null); // Stampa nello stream di output il file XML PrintWriter pw = new PrintWriter(os); pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"); pw.println("<configurations>"); // Export delle categories if (hacService != null) { ICategory[] categories = hacService.getCategories(); if (categories != null) { pw.println("<categories>"); for (int i = 0; i < categories.length; i++) { ICategory c = categories[i]; pw.println("<category icon=\"" + c.getIconName() + "\" name = \"" + c.getName() + "\" pid = \"" + c.getPid() + "\"/>"); } pw.println("</categories>"); } } // Export delle rules if (connAdmin != null) { ArrayList rules = connAdmin.getBindRules(); if (rules != null) { pw.println("<rules>"); for (int i = 0; i < rules.size(); i++) { Filter f = (Filter) rules.get(i); pw.println("<rule filter =\"" + this.xmlContentEscape(f.toString()) + "\"/>"); } pw.println("</rules>"); } } // Export delle configurazioni if (configs != null && configs.length > 0) { Set factories = new HashSet(); SortedMap sm = new TreeMap(); for (int i = 0; i < configs.length; i++) { sm.put(configs[i].getPid(), configs[i]); String fpid = configs[i].getFactoryPid(); if (null != fpid) { factories.add(fpid); } } for (Iterator mi = sm.values().iterator(); mi.hasNext();) { Configuration config = (Configuration) mi.next(); pw.println("<configuration>"); // Emette una ad una le proprieta' della configurazione Dictionary props = config.getProperties(); if (props != null) { SortedSet keys = new TreeSet(); for (Enumeration ke = props.keys(); ke.hasMoreElements();) keys.add(ke.nextElement()); for (Iterator ki = keys.iterator(); ki.hasNext();) { String key = (String) ki.next(); pw.print("<property type=\"" + props.get(key).getClass().getSimpleName() + "\" name=\"" + key + "\">"); if (props.get(key).getClass().isArray() == true) { pw.println(); Object value = props.get(key); int len = Array.getLength(value); for (int i = 0; i < len; i++) { Object element = Array.get(value, i); pw.print("<item>" + element.toString() + "</item>"); } } else pw.print(props.get(key)); pw.println("</property>"); } } pw.println("</configuration>"); } } pw.println("</configurations>"); pw.flush(); }
From source file:org.wso2.carbon.ui.deployment.UIBundleDeployer.java
public void registerServlet(Servlet servlet, String urlPattern, Dictionary params, Dictionary servletAttrs, int event, javax.servlet.Filter associatedFilter) throws CarbonException { HttpService httpService;/*from ww w .ja v a2 s. c o m*/ try { httpService = CarbonUIServiceComponent.getHttpService(); } catch (Exception e) { throw new CarbonException("An instance of HttpService is not available"); } try { if (event == ServiceEvent.REGISTERED) { Servlet adaptedJspServlet = new ContextPathServletAdaptor(servlet, urlPattern); if (associatedFilter == null) { httpService.registerServlet(urlPattern, adaptedJspServlet, params, httpContext); } else { httpService.registerServlet(urlPattern, new FilterServletAdaptor(associatedFilter, null, adaptedJspServlet), params, httpContext); } if (servletAttrs != null) { for (Enumeration enm = servletAttrs.keys(); enm.hasMoreElements();) { String key = (String) enm.nextElement(); adaptedJspServlet.getServletConfig().getServletContext().setAttribute(key, servletAttrs.get(key)); } } } else if (event == ServiceEvent.UNREGISTERING) { httpService.unregister(urlPattern); } } catch (Exception e) { log.error("Error occurred while registering servlet", e); } }
From source file:org.openhab.binding.gpsd.internal.GPSdBinding.java
/** * @{inheritDoc//from w w w . ja v a2s.c om */ @Override public void updated(Dictionary config) throws ConfigurationException { logger.debug("GPSd Updated"); if (config != null) { logger.debug("GPSD Configuration not null"); if (config != null) { String hostnameString = (String) config.get("hostname"); if (StringUtils.isNotBlank(hostnameString)) { hostname = hostnameString; } String portString = (String) config.get("port"); if (StringUtils.isNotBlank(portString)) { port = Integer.parseInt(portString); } //setProperlyConfigured(true); } HashMap<String, GPSdParserRule> parsingRules = new HashMap<String, GPSdParserRule>(); 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; } if ("simulate".equals(key)) { continue; } String value = (String) config.get(key); if (key.equals("connectionretrycount")) { this.setConnectionRetryCount(Integer.parseInt(value)); } if ("hostname".equals(key)) { if (StringUtils.isNotBlank(value)) { hostname = value; logger.info("Hostname set to {}", hostname); } } else if ("port".equals(key)) { port = Integer.parseInt(value); logger.info("Port set to {}", port); } else if (key.equals("connectionretrytime")) { this.setConnectionRetryTime(Integer.parseInt(value)); logger.info("connectionretrytime set to {}", value); } else if (key.equals("movementtracking")) { this.setMovementTrack(value.toLowerCase().equalsIgnoreCase("true") ? true : false); logger.info("trackMovement set to {}", this.movementTrack); } else if (key.equals("maxchangethres")) { this.maxChangeThres = Double.parseDouble(value); logger.info("Movement Threshold set to {}", this.maxChangeThres); } else if (key.equals("movementitem")) { if (StringUtils.isNotBlank(value)) { this.setMovementItem(value); } logger.info("movementitem set to {}", value); } else if (key.equals("refresh")) { this.setRefresh(Integer.parseInt(value)); logger.info("Refresh set to {}", value); } else if (key.equals("connectionretrycount")) { this.setConnectionRetryCount(Integer.parseInt(value)); logger.info("connectionretrycount set to {}", value); } else { // process all data parsing rules try { GPSdParserRule rule = new GPSdParserRule(value); parsingRules.put(key, rule); } catch (GPSdException e) { throw new ConfigurationException(key, "invalid parser rule", e); } } } if (parsingRules != null) { logger.debug("GPSd Data Parser called"); // dataParser = new GPSdDataParser(parsingRules); } if (messageListener != null) { logger.debug("Close previous message listener"); messageListener.setInterrupted(true); try { messageListener.join(); } catch (InterruptedException e) { logger.info("Previous message listener closing interrupted", e); } } if (simulate == true) connector = new GPSdSimulator(); else connector = new GPSd4JavaConnector(hostname); try { int count = 0; while (!connector.isConnected() && connectionRetryCount > count) { count++; connector.connect(); if (!connector.isConnected()) { if (connectionRetryCount == count) { throw new GPSdException("Out of retries"); } else { Thread.sleep(connectionRetryTime); } } } messageListener = new MessageListener(); messageListener.start(); } catch (Exception e) { logger.error("Error occured when connecting GPSD device", e); logger.warn("Closing GPSd message listener"); } } }