Example usage for java.util Dictionary get

List of usage examples for java.util Dictionary get

Introduction

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

Prototype

public abstract V get(Object key);

Source Link

Document

Returns the value to which the key is mapped in this dictionary.

Usage

From source file:org.openhab.binding.proserv.internal.ProservBinding.java

/**
 * {@inheritDoc}/*from   w  w  w. j a v a 2 s. c om*/
 */
@SuppressWarnings("rawtypes")
public void updated(Dictionary config) throws ConfigurationException {
    if (config != null) {
        boolean needsRefresh = false;
        String ip = (String) config.get("ip");
        String portString = (String) config.get("port");
        ProservBinding.mailTo = (String) config.get("mailto");

        ProservBinding.language = (String) config.get("language");
        if (ProservBinding.language != null) {
            if (!isSupportedLanguage(ProservBinding.language))
                ProservBinding.language = "en";
        } else {
            logger.error("Mising config proserv:language");
            ProservBinding.language = "en";
            ProservData.writeConfigData("proserv:language", ProservBinding.language);
        }
        if (ProservBinding.oldLanguage == null)
            needsRefresh = true;
        else if (ProservBinding.oldLanguage.compareTo(ProservBinding.language) != 0)
            needsRefresh = true;
        ProservBinding.oldLanguage = ProservBinding.language;

        ProservBinding.shellRestartCommand = (String) config.get("shellRestartCommand");

        ProservBinding.chartItemRefreshHour = (String) config.get("chartItemRefreshHour");
        ProservBinding.chartItemRefreshDay = (String) config.get("chartItemRefreshDay");
        ProservBinding.chartItemRefreshWeek = (String) config.get("chartItemRefreshWeek");
        ProservBinding.chartItemRefreshMonth = (String) config.get("chartItemRefreshMonth");
        ProservBinding.chartItemRefreshYear = (String) config.get("chartItemRefreshYear");
        if (ProservBinding.chartItemRefreshHour != null)
            if (Integer.parseInt(ProservBinding.chartItemRefreshHour) < 5000)
                ProservBinding.chartItemRefreshHour = "5000";

        if (ProservBinding.chartItemRefreshDay != null)
            if (Integer.parseInt(ProservBinding.chartItemRefreshDay) < 5000)
                ProservBinding.chartItemRefreshDay = "5000";

        if (ProservBinding.chartItemRefreshWeek != null)
            if (Integer.parseInt(ProservBinding.chartItemRefreshWeek) < 5000)
                ProservBinding.chartItemRefreshWeek = "5000";

        if (ProservBinding.chartItemRefreshMonth != null)
            if (Integer.parseInt(ProservBinding.chartItemRefreshMonth) < 5000)
                ProservBinding.chartItemRefreshMonth = "5000";

        if (ProservBinding.chartItemRefreshYear != null)
            if (Integer.parseInt(ProservBinding.chartItemRefreshYear) < 5000)
                ProservBinding.chartItemRefreshYear = "5000";

        ProservBinding.bLogHashTees = Boolean.parseBoolean((String) config.get("logHashTees"));

        int portTmp = 80;
        if (StringUtils.isNotBlank(portString)) {
            portTmp = (int) Long.parseLong(portString);
        }

        if ((StringUtils.isNotBlank(ip) && !ip.equals(ProservBinding.ip)) || portTmp != ProservBinding.port) {
            // only do something if the ip or port has changed
            needsRefresh = true;
            logger.debug("needsRefresh = true");
            ProservBinding.ip = ip;
            ProservBinding.port = portTmp;

            String refreshIntervalString = (String) config.get("refresh");
            if (StringUtils.isNotBlank(refreshIntervalString)) {
                refreshInterval = Long.parseLong(refreshIntervalString);
            }

            setProperlyConfigured(true);
        }

        // Load language strings
        Reader reader = null;
        String filename = ProservBinding.language + ".map";
        try {
            String path = ConfigDispatcher.getConfigFolder() + File.separator + "transform" + File.separator
                    + filename;
            Properties properties = new Properties();
            reader = new FileReader(path);
            properties.load(reader);

            ProservBinding.mailSubject = properties.getProperty("MAIL-SUBJECT");
            ProservBinding.mailContent = properties.getProperty("MAIL-CONTENT");

        } catch (Throwable e) {
            String message = "opening file '" + filename + "' throws exception";
            logger.error(message, e);
        } finally {
            IOUtils.closeQuietly(reader);
        }

        if (proservData != null && needsRefresh == true) {
            logger.debug("proServ force a reload of configdata!");
            proservData.refresh = true; // force a reload of configdata
            //execute();
        }
    }
}

From source file:org.openhab.binding.ecobee.internal.EcobeeBinding.java

/**
 * {@inheritDoc}/*from  w  w  w  .ja  va2  s. com*/
 */
@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 ecobee:refresh=240000
        String refreshIntervalString = (String) config.get(CONFIG_REFRESH);
        if (isNotBlank(refreshIntervalString)) {
            refreshInterval = Long.parseLong(refreshIntervalString);
        }
        // to override the default HTTP timeout one has to add a
        // parameter to openhab.cfg like ecobee:timeout=20000
        String timeoutString = (String) config.get(CONFIG_TIMEOUT);
        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 = (String) config.get(CONFIG_TEMP_SCALE);
        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 = (String) configKeys.nextElement();

            // the config-key enumeration contains additional keys that we
            // don't want to process here ...
            if (CONFIG_REFRESH.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 = (String) config.get(configKey);

            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);
    }
}

From source file:org.openhab.io.caldav.internal.CalDavLoaderImpl.java

@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    if (config != null) {
        CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true);

        // just temporary
        Map<String, CalDavConfig> configMap = new HashMap<String, CalDavConfig>();

        Enumeration<String> iter = config.keys();
        while (iter.hasMoreElements()) {
            String key = iter.nextElement();
            log.trace("configuration parameter: " + key);
            if (key.equals("service.pid")) {
                continue;
            } else if (key.equals(PROP_TIMEZONE)) {
                log.debug("overriding default timezone {} with {}", defaultTimeZone, config.get(key));
                defaultTimeZone = DateTimeZone.forID(config.get(key) + "");
                if (defaultTimeZone == null) {
                    throw new ConfigurationException(PROP_TIMEZONE,
                            "invalid timezone value: " + config.get(key));
                }//from w  w w . j av a2  s. c  o m
                log.debug("found timeZone: {}", defaultTimeZone);
                continue;
            }
            String[] keys = key.split(":");
            if (keys.length != 2) {
                throw new ConfigurationException(key, "unknown identifier");
            }
            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 = config.get(key) + "";

            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_DISABLE_CERTIFICATE_VERIFICATION)) {
                calDavConfig.setDisableCertificateVerification(BooleanUtils.toBoolean(value));
            }
        }

        // verify if all required parameters are set
        for (String id : configMap.keySet()) {
            if (configMap.get(id).getUrl() == null) {
                throw new ConfigurationException(PROP_URL, PROP_URL + " must be set");
            }
            if (configMap.get(id).getUsername() == null) {
                throw new ConfigurationException(PROP_USERNAME, PROP_USERNAME + " must be set");
            }
            if (configMap.get(id).getPassword() == null) {
                throw new ConfigurationException(PROP_PASSWORD, PROP_PASSWORD + " must be set");
            }
            log.trace("config for id '{}': {}", 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.error(
                        "cannot create directory (" + CACHE_PATH + ") for calendar caching (missing rights?)");
                continue;
            }
            EventStorage.getInstance().getEventCache().put(calDavConfig.getKey(), eventRuntime);
        }

        setProperlyConfigured(true);
        this.startLoading();
    }
}

From source file:org.liveSense.auth.ldap.LdapAuthenticationHandler.java

/**
 * Called by SCR to activate the authentication handler.
 *
 * @throws InvalidKeyException//from w  w  w.  j ava  2  s .c  o  m
 * @throws NoSuchAlgorithmException
 * @throws IllegalStateException
 * @throws UnsupportedEncodingException
 */
@Activate
protected void activate(ComponentContext componentContext) throws InvalidKeyException, NoSuchAlgorithmException,
        IllegalStateException, UnsupportedEncodingException {

    Dictionary<?, ?> properties = componentContext.getProperties();

    this.loginForm = PropertiesUtil.toString(properties.get(PAR_LOGIN_FORM),
            AuthenticationFormServlet.SERVLET_PATH);
    log.info("Login Form URL {}", loginForm);

    final String authName = PropertiesUtil.toString(properties.get(PAR_AUTH_NAME), DEFAULT_AUTH_NAME);

    String defaultCookieDomain = PropertiesUtil.toString(properties.get(PAR_DEFAULT_COOKIE_DOMAIN), "");
    if (defaultCookieDomain.length() == 0) {
        defaultCookieDomain = null;
    }

    authStorageType = PropertiesUtil.toString(properties.get(PAR_AUTH_STORAGE), DEFAULT_AUTH_STORAGE);
    if (AUTH_STORAGE_SESSION_ATTRIBUTE.equals(authStorageType)) {

        this.authStorage = new SessionStorage(authName);
        log.info("Using HTTP Session store with attribute name {}", authName);

    } else {

        this.authStorage = new CookieStorage(authName, defaultCookieDomain);
        log.info("Using Cookie store with name {}", authName);

    }

    this.attrCookieAuthData = PropertiesUtil.toString(properties.get(PAR_CREDENTIALS_ATTRIBUTE_NAME),
            DEFAULT_CREDENTIALS_ATTRIBUTE_NAME);
    log.info("Setting Auth Data attribute name {}", attrCookieAuthData);

    int timeoutMinutes = PropertiesUtil.toInteger(properties.get(PAR_AUTH_TIMEOUT), DEFAULT_AUTH_TIMEOUT);
    if (timeoutMinutes < 1) {
        timeoutMinutes = DEFAULT_AUTH_TIMEOUT;
    }
    log.info("Setting session timeout {} minutes", timeoutMinutes);
    this.sessionTimeout = MINUTES * timeoutMinutes;

    final String tokenFileName = PropertiesUtil.toString(properties.get(PAR_TOKEN_FILE), DEFAULT_TOKEN_FILE);
    final File tokenFile = getTokenFile(tokenFileName, componentContext.getBundleContext());
    final boolean fastSeed = PropertiesUtil.toBoolean(properties.get(PAR_TOKEN_FAST_SEED),
            DEFAULT_TOKEN_FAST_SEED);
    log.info("Storing tokens in {}", tokenFile.getAbsolutePath());
    this.tokenStore = new TokenStore(tokenFile, sessionTimeout, fastSeed);

    this.loginModule = null;
    try {
        this.loginModule = LdapLoginModulePlugin.register(this, componentContext.getBundleContext());
    } catch (Throwable t) {
        log.info(
                "Cannot register LdapLoginModulePlugin. This is expected if Sling LdapModulePlugin services are not supported");
        log.debug("dump", t);
    }

    this.includeLoginForm = PropertiesUtil.toBoolean(properties.get(PAR_INCLUDE_FORM), DEFAULT_INCLUDE_FORM);

    this.loginAfterExpire = PropertiesUtil.toBoolean(properties.get(PAR_LOGIN_AFTER_EXPIRE),
            DEFAULT_LOGIN_AFTER_EXPIRE);

    this.identityProperty = PropertiesUtil.toString(properties.get(PAR_LDAP_ID_IDENTIFIER_PROPERTY),
            DEFAULT_LDAP_ID_IDENTIFIER_PROPERTY);
    log.info("Setting Identity attribute name {}", identityProperty);

    this.attrLdapId = PropertiesUtil.toString(properties.get(PAR_LDAP_USER_ATTR), DEFAULT_LDAP_USER_ATTR);
    log.info("Setting Ldap Id attribute name {}", attrLdapId);

    this.ldapUrl = PropertiesUtil.toString(properties.get(PAR_LDAP_URL), DEFAULT_LDAP_URL);
    log.info("Setting Ldap Url name {}", ldapUrl);

    this.ldapBase = PropertiesUtil.toString(properties.get(PAR_LDAP_BASE), DEFAULT_LDAP_BASE);
    log.info("Setting Ldap Base name {}", ldapBase);

    this.ldapAuthenticationType = PropertiesUtil.toString(properties.get(PAR_LDAP_AUTHENTICATION_TYPE),
            DEFAULT_LDAP_AUTHENTICATION_TYPE);
    log.info("Setting Ldap Authentication Type {}", ldapAuthenticationType);

    this.autoCreateJcrUser = PropertiesUtil.toBoolean(properties.get(PAR_AUTOCREATE_JCR_USER),
            DEFAULT_AUTOCREATE_JCR_USER);
    log.info("Setting AutoCreate JCR user {}", autoCreateJcrUser);

    this.userAttributes = PropertiesUtil.toStringArray(properties.get(PAR_USER_ATTRIBUTES),
            DEFAULT_USER_ATTRIBUTES);
    log.info("Setting User Attributes {}", userAttributes);

}

From source file:org.openhab.binding.dscalarm.internal.DSCAlarmActiveBinding.java

/**
 * @{inheritDoc/*  w ww. ja  va  2s . c  om*/
 */
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    logger.debug("updated(): Configuration updated, config {}", config != null ? true : false);

    if (config != null) {

        if (StringUtils.isNotBlank((String) config.get("serialPort"))) {
            serialPort = (String) config.get("serialPort");
        }

        if (StringUtils.isNotBlank((String) config.get("ip"))) {
            ipAddress = (String) config.get("ip");
        }

        if (serialPort != null && ipAddress != null) {
            logger.error(
                    "updated(): Can only configure one connection type at a time: Serial Port or Ip Address!");
            return;
        }

        if (serialPort != null) {
            connectorType = DSCAlarmConnectorType.SERIAL;
            try {
                if (StringUtils.isNotBlank((String) config.get("baud")))
                    baudRate = Integer.parseInt((String) config.get("baud"));
            } catch (NumberFormatException numberFormatException) {
                baudRate = 0;
                logger.error("updated(): Baud Rate not configured correctly!");
                return;
            }
        }

        if (ipAddress != null) {
            connectorType = DSCAlarmConnectorType.TCP;
        }

        logger.debug("updated(): Connector Type: {}", connectorType);

        if (StringUtils.isNotBlank((String) config.get("password"))) {
            password = (String) config.get("password");
        }

        if (StringUtils.isNotBlank((String) config.get("usercode"))) {
            userCode = (String) config.get("usercode");
        }

        if (StringUtils.isNotBlank((String) config.get("pollPeriod"))) {
            try {
                pollPeriod = Integer.parseInt((String) config.get("pollperiod"));
            } catch (NumberFormatException numberFormatException) {
                logger.error("updated(): Poll Period not configured correctly!");
                return;
            }

            if (pollPeriod > 15) {
                pollPeriod = 15;
            } else if (pollPeriod < 1) {
                pollPeriod = 1;
            }
        } else {
            pollPeriod = DEFAULT_POLL_PERIOD;
        }

        if (StringUtils.isNotBlank((String) config.get("suppressAcknowledgementMsgs"))) {
            try {
                suppressAcknowledgementMsgs = Boolean
                        .parseBoolean((String) config.get("suppressAcknowledgementMsgs"));
            } catch (NumberFormatException numberFormatException) {
                suppressAcknowledgementMsgs = false;
                logger.error("updated(): Error parsing 'suppressAcknowledgementMsgs'. This must be boolean!");
            }
        }

    } else {
        logger.debug("updated(): No Configuration!");
        return;
    }

    initialize();
}

From source file:org.opennaas.extensions.quantum.capability.apiv2.QuantumAPIV2Capability.java

@Override
/**/*from  ww w . ja  v  a2  s  .com*/
 * Register the capability like a web service through DOSGi
 *
 * @param name
 * @param resourceId
 * @return
 * @throws CapabilityException
 */
protected ServiceRegistration registerService(BundleContext bundleContext, String capabilityName,
        String resourceType, String resourceName, String ifaceName, Dictionary<String, String> props)
        throws CapabilityException {
    try {
        ConfigurationAdminUtil configurationAdmin = new ConfigurationAdminUtil(bundleContext);
        String url = configurationAdmin.getProperty("org.opennaas", "ws.rest.url");
        if (props != null) {
            // Rest
            props.put("service.exported.interfaces", "*");
            props.put("service.exported.configs", "org.apache.cxf.rs");
            props.put("service.exported.intents", "HTTP");
            // props.put("org.apache.cxf.rs.httpservice.context", url + "/" + resourceType + "/" + resourceName + "/" + capabilityName);
            props.put("org.apache.cxf.rs.httpservice.context", "/networkService/v1.1");
            props.put("org.apache.cxf.rs.address", "/");
            props.put("org.apache.cxf.httpservice.requirefilter", "false");
            // JSON provider
            props.put("org.apache.cxf.rs.provider", "org.opennaas.extensions.quantum.utils.CustomJSONProvider");
        }
        log.info("Registering ws: \n " + "in url: " + props.get("org.apache.cxf.rs.address") + "\n"
                + "in context: " + props.get("org.apache.cxf.rs.httpservice.context"));
        registration = bundleContext.registerService(ifaceName, this, props);
    } catch (IOException e) {
        throw new CapabilityException(e);
    }
    return registration;
}

From source file:org.apache.sling.servlets.resolver.internal.SlingServletResolver.java

/**
 * Activate this component.//from   w  w  w  . ja  v a2s .  co m
 */
@SuppressWarnings("unchecked")
protected void activate(final ComponentContext context) throws LoginException {
    // from configuration if available
    final Dictionary<?, ?> properties = context.getProperties();
    Object servletRoot = properties.get(PROP_SERVLET_ROOT);
    if (servletRoot == null) {
        servletRoot = DEFAULT_SERVLET_ROOT;
    }

    final Collection<ServiceReference> refs;
    synchronized (this.pendingServlets) {

        refs = new ArrayList<ServiceReference>(pendingServlets);
        pendingServlets.clear();

        this.sharedScriptResolver = resourceResolverFactory
                .getAdministrativeResourceResolver(this.createAuthenticationInfo(context.getProperties()));
        this.searchPaths = this.sharedScriptResolver.getSearchPath();
        servletResourceProviderFactory = new ServletResourceProviderFactory(servletRoot, this.searchPaths);

        // register servlets immediately from now on
        this.context = context;
    }
    createAllServlets(refs);

    // execution paths
    this.executionPaths = OsgiUtil.toStringArray(properties.get(PROP_PATHS), DEFAULT_PATHS);
    if (this.executionPaths != null) {
        // if we find a string combination that basically allows all paths,
        // we simply set the array to null
        if (this.executionPaths.length == 0) {
            this.executionPaths = null;
        } else {
            boolean hasRoot = false;
            for (int i = 0; i < this.executionPaths.length; i++) {
                final String path = this.executionPaths[i];
                if (path == null || path.length() == 0 || path.equals("/")) {
                    hasRoot = true;
                    break;
                }
            }
            if (hasRoot) {
                this.executionPaths = null;
            }
        }
    }
    this.defaultExtensions = OsgiUtil.toStringArray(properties.get(PROP_DEFAULT_EXTENSIONS),
            DEFAULT_DEFAULT_EXTENSIONS);

    // create cache - if a cache size is configured
    this.cacheSize = OsgiUtil.toInteger(properties.get(PROP_CACHE_SIZE), DEFAULT_CACHE_SIZE);
    if (this.cacheSize > 5) {
        this.cache = new ConcurrentHashMap<AbstractResourceCollector, Servlet>(cacheSize);
        this.logCacheSizeWarning = true;
    } else {
        this.cacheSize = 0;
    }

    // setup default servlet
    this.getDefaultServlet();

    // and finally register as event listener
    this.eventHandlerReg = context.getBundleContext().registerService(EventHandler.class.getName(), this,
            properties);

    this.plugin = new ServletResolverWebConsolePlugin(context.getBundleContext());

    if (this.cacheSize > 0) {
        try {
            Dictionary<String, String> mbeanProps = new Hashtable<String, String>();
            mbeanProps.put("jmx.objectname",
                    "org.apache.sling:type=servletResolver,service=SlingServletResolverCache");

            ServletResolverCacheMBeanImpl mbean = new ServletResolverCacheMBeanImpl();
            mbeanRegistration = context.getBundleContext()
                    .registerService(SlingServletResolverCacheMBean.class.getName(), mbean, mbeanProps);
        } catch (Throwable t) {
            LOGGER.debug("Unable to register mbean");
        }
    }
}

From source file:org.onosproject.dhcprelay.DhcpRelayManagerTest.java

@Before
public void setup() {
    manager = new DhcpRelayManager();
    manager.cfgService = createNiceMock(NetworkConfigRegistry.class);

    expect(manager.cfgService.getConfig(APP_ID, DefaultDhcpRelayConfig.class)).andReturn(CONFIG).anyTimes();

    expect(manager.cfgService.getConfig(APP_ID, IndirectDhcpRelayConfig.class)).andReturn(CONFIG_INDIRECT)
            .anyTimes();/*from w w  w.ja v a2  s. c om*/

    manager.coreService = createNiceMock(CoreService.class);
    expect(manager.coreService.registerApplication(anyString())).andReturn(APP_ID).anyTimes();

    manager.hostService = createNiceMock(HostService.class);

    expect(manager.hostService.getHostsByIp(OUTER_RELAY_IP_V6)).andReturn(ImmutableSet.of(OUTER_RELAY_HOST))
            .anyTimes();
    expect(manager.hostService.getHostsByIp(SERVER_IP)).andReturn(ImmutableSet.of(SERVER_HOST)).anyTimes();
    expect(manager.hostService.getHostsByIp(SERVER_IP_V6)).andReturn(ImmutableSet.of(SERVER_HOST)).anyTimes();
    expect(manager.hostService.getHostsByIp(GATEWAY_IP)).andReturn(ImmutableSet.of(SERVER_HOST)).anyTimes();
    expect(manager.hostService.getHostsByIp(GATEWAY_IP_V6)).andReturn(ImmutableSet.of(SERVER_HOST)).anyTimes();
    expect(manager.hostService.getHostsByIp(CLIENT_LL_IP_V6)).andReturn(ImmutableSet.of(EXISTS_HOST))
            .anyTimes();

    expect(manager.hostService.getHost(OUTER_RELAY_HOST_ID)).andReturn(OUTER_RELAY_HOST).anyTimes();

    packetService = new MockPacketService();
    manager.packetService = packetService;
    manager.compCfgService = createNiceMock(ComponentConfigService.class);
    deviceService = createNiceMock(DeviceService.class);

    Device device = createNiceMock(Device.class);
    expect(device.is(Pipeliner.class)).andReturn(true).anyTimes();

    expect(deviceService.getDevice(DEV_1_ID)).andReturn(device).anyTimes();
    expect(deviceService.getDevice(DEV_2_ID)).andReturn(device).anyTimes();
    replay(deviceService, device);

    mockRouteStore = new MockRouteStore();
    mockDhcpRelayStore = new MockDhcpRelayStore();
    mockDhcpRelayCountersStore = new MockDhcpRelayCountersStore();

    manager.dhcpRelayStore = mockDhcpRelayStore;

    manager.deviceService = deviceService;

    manager.interfaceService = new MockInterfaceService();
    flowObjectiveService = EasyMock.niceMock(FlowObjectiveService.class);
    mockHostProviderService = createNiceMock(HostProviderService.class);
    v4Handler = new Dhcp4HandlerImpl();
    v4Handler.providerService = mockHostProviderService;
    v4Handler.dhcpRelayStore = mockDhcpRelayStore;
    v4Handler.hostService = manager.hostService;
    v4Handler.interfaceService = manager.interfaceService;
    v4Handler.packetService = manager.packetService;
    v4Handler.routeStore = mockRouteStore;
    v4Handler.coreService = createNiceMock(CoreService.class);
    v4Handler.flowObjectiveService = flowObjectiveService;
    v4Handler.appId = TestApplicationId.create(Dhcp4HandlerImpl.DHCP_V4_RELAY_APP);
    v4Handler.deviceService = deviceService;
    manager.v4Handler = v4Handler;

    v6Handler = new Dhcp6HandlerImpl();
    v6Handler.dhcpRelayStore = mockDhcpRelayStore;
    v6Handler.dhcpRelayCountersStore = mockDhcpRelayCountersStore;
    v6Handler.hostService = manager.hostService;
    v6Handler.interfaceService = manager.interfaceService;
    v6Handler.packetService = manager.packetService;
    v6Handler.routeStore = mockRouteStore;
    v6Handler.providerService = mockHostProviderService;
    v6Handler.coreService = createNiceMock(CoreService.class);
    v6Handler.flowObjectiveService = flowObjectiveService;
    v6Handler.appId = TestApplicationId.create(Dhcp6HandlerImpl.DHCP_V6_RELAY_APP);
    v6Handler.deviceService = deviceService;
    manager.v6Handler = v6Handler;

    // properties
    Dictionary<String, Object> dictionary = createNiceMock(Dictionary.class);
    expect(dictionary.get("arpEnabled")).andReturn(true).anyTimes();
    expect(dictionary.get("dhcpPollInterval")).andReturn(120).anyTimes();
    ComponentContext context = createNiceMock(ComponentContext.class);
    expect(context.getProperties()).andReturn(dictionary).anyTimes();

    replay(manager.cfgService, manager.coreService, manager.hostService, manager.compCfgService, dictionary,
            context);
    manager.activate(context);
}

From source file:org.openhab.binding.multionewire.internal.MultiOneWireBinding.java

@SuppressWarnings("rawtypes")
public void updated(Dictionary config) throws ConfigurationException {

    if (config == null)
        return;/*from w  ww  .  ja va  2 s .  c om*/

    @SuppressWarnings("unchecked")
    Enumeration<String> keys = config.keys();

    if (serverList == null) {
        serverList = new HashMap<String, ServerConfig>();
    }

    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()) {
            continue;
        }

        matcher.reset();
        matcher.find();

        String serverId = matcher.group(1);

        ServerConfig serverConfig = serverList.get(serverId);

        if (serverConfig == null) {
            serverConfig = new ServerConfig();
            serverList.put(serverId, serverConfig);
        }

        String configKey = matcher.group(2);
        String value = (String) config.get(key);

        if ("host".equals(configKey)) {
            String[] hostConfig = value.split(":");
            serverConfig.host = hostConfig[0];
            if (hostConfig.length > 1) {
                serverConfig.port = Integer.parseInt(hostConfig[1]);
            } else {
                serverConfig.port = 4304;
            }
            logger.debug("Added new Server {}:{} to serverlist",
                    new Object[] { serverConfig.host, serverConfig.port });
        } else {
            throw new ConfigurationException(configKey,
                    "The given OWServer configKey '" + configKey + "' is unknown");
        }
    }

    String refreshIntervalString = (String) config.get("refresh");
    if (StringUtils.isNotBlank(refreshIntervalString)) {
        refreshInterval = Long.parseLong(refreshIntervalString);
    }

    String retryString = (String) config.get("retry");
    if (StringUtils.isNotBlank(retryString)) {
        retry = Integer.parseInt(retryString);
    }

    String tempScaleString = (String) config.get("tempscale");
    if (StringUtils.isNotBlank(tempScaleString)) {
        try {
            tempScale = OwTemperatureScale.valueOf("OWNET_TS_" + tempScaleString);
        } catch (IllegalArgumentException iae) {
            throw new ConfigurationException("onewire:tempscale", "Unknown temperature scale '"
                    + tempScaleString + "'. Valid values are CELSIUS, FAHRENHEIT, KELVIN or RANKIN.");
        }
    }

    setProperlyConfigured(true);
}

From source file:org.openhab.binding.sonos.internal.SonosBinding.java

@SuppressWarnings("rawtypes")
public void updated(Dictionary config) throws ConfigurationException {
    if (config != null) {
        Enumeration 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;
            }/*from  w w  w.j  a va  2 s.c om*/

            if ("pollingPeriod".equals(key)) {
                pollingPeriod = Integer.parseInt((String) config.get(key));
                logger.debug("Setting polling period to {} ms", pollingPeriod);
                continue;
            }

            Matcher matcher = EXTRACT_SONOS_CONFIG_PATTERN.matcher(key);
            if (!matcher.matches()) {
                logger.debug("given sonos-config-key '" + key
                        + "' does not follow the expected pattern '<sonosId>.<udn>'");
                continue;
            }

            matcher.reset();
            matcher.find();

            String sonosID = matcher.group(1);

            SonosZonePlayer sonosConfig = sonosZonePlayerCache.getById(sonosID);
            if (sonosConfig == null) {
                sonosConfig = new SonosZonePlayer(sonosID, self);
                sonosZonePlayerCache.add(sonosConfig);
            }

            String configKey = matcher.group(2);
            String value = (String) config.get(key);

            if ("udn".equals(configKey)) {
                sonosConfig.setUdn(new UDN(value));
                logger.debug("Add predefined Sonos device with UDN {}", sonosConfig.getUdn());
            } else {
                throw new ConfigurationException(configKey,
                        "the given configKey '" + configKey + "' is unknown");
            }
        }
    }

    setProperlyConfigured(true);

}