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.codice.ddf.ui.admin.api.ConfigurationAdmin.java

public Map<String, Object> enableConfiguration(String servicePid) throws IOException {
    if (StringUtils.isEmpty(servicePid)) {
        throw new IOException(
                "Service PID of Source to be disabled must be specified.  Service PID provided: " + servicePid);
    }/*from   ww w. ja  v a 2  s .c om*/

    Configuration disabledConfig = configurationAdminExt.getConfiguration(servicePid);

    if (disabledConfig == null) {
        throw new IOException("No Source exists with the service PID: " + servicePid);
    }

    Dictionary<String, Object> properties = disabledConfig.getProperties();
    String disabledFactoryPid = (String) properties
            .get(org.osgi.service.cm.ConfigurationAdmin.SERVICE_FACTORYPID);
    if (!StringUtils.endsWith(disabledFactoryPid, DISABLED)) {
        throw new IOException("Source is already enabled.");
    }

    String enabledFactoryPid = StringUtils.removeEnd(disabledFactoryPid, DISABLED);
    properties.put(org.osgi.service.cm.ConfigurationAdmin.SERVICE_FACTORYPID, enabledFactoryPid);
    Configuration enabledConfiguration = configurationAdmin.createFactoryConfiguration(enabledFactoryPid, null);
    enabledConfiguration.update(properties);

    disabledConfig.delete();

    Map<String, Object> rval = new HashMap<>();
    rval.put(ORIGINAL_PID, servicePid);
    rval.put(ORIGINAL_FACTORY_PID, disabledFactoryPid);
    rval.put(NEW_PID, enabledConfiguration.getPid());
    rval.put(NEW_FACTORY_PID, enabledFactoryPid);
    return rval;
}

From source file:org.openhab.binding.ihc.internal.IhcBinding.java

public void updated(Dictionary<String, ?> config) throws ConfigurationException {

    logger.debug("Configuration updated, config {}", config != null ? true : false);

    if (config != null) {
        ip = (String) config.get("ip");
        username = (String) config.get("username");
        password = (String) config.get("password");
        timeout = Integer.parseInt((String) config.get("timeout"));
        projectFile = (String) config.get("projectFile");
        dumpResourceFile = (String) config.get("dumpResourceFile");
        setProperlyConfigured(true);//from  w w w  .  j a  v  a 2  s.co m
        setReconnectRequest(true);
    }
}

From source file:org.codice.ddf.ui.admin.api.ConfigurationAdmin.java

public Map<String, Object> disableConfiguration(String servicePid) throws IOException {
    if (StringUtils.isEmpty(servicePid)) {
        throw new IOException(
                "Service PID of Source to be disabled must be specified.  Service PID provided: " + servicePid);
    }//from ww  w. j a  va  2  s.  c  om

    Configuration originalConfig = configurationAdminExt.getConfiguration(servicePid);

    if (originalConfig == null) {
        throw new IOException("No Source exists with the service PID: " + servicePid);
    }

    Dictionary<String, Object> properties = originalConfig.getProperties();
    String originalFactoryPid = (String) properties
            .get(org.osgi.service.cm.ConfigurationAdmin.SERVICE_FACTORYPID);
    if (StringUtils.endsWith(originalFactoryPid, DISABLED)) {
        throw new IOException("Source is already disabled.");
    }

    // Copy configuration from the original configuration and change its factory PID to end with
    // "disabled"
    String disabledServiceFactoryPid = originalFactoryPid + DISABLED;
    properties.put(org.osgi.service.cm.ConfigurationAdmin.SERVICE_FACTORYPID, disabledServiceFactoryPid);
    Configuration disabledConfig = configurationAdmin.createFactoryConfiguration(disabledServiceFactoryPid,
            null);
    disabledConfig.update(properties);

    // remove original configuration
    originalConfig.delete();

    Map<String, Object> rval = new HashMap<>();
    rval.put(ORIGINAL_PID, servicePid);
    rval.put(ORIGINAL_FACTORY_PID, originalFactoryPid);
    rval.put(NEW_PID, disabledConfig.getPid());
    rval.put(NEW_FACTORY_PID, disabledServiceFactoryPid);
    return rval;
}

From source file:org.openhab.binding.http.internal.HttpBinding.java

/**
 * {@inheritDoc}/*from   w w  w .  jav  a  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.opencastproject.publication.youtube.YouTubePublicationServiceImpl.java

/**
 * {@inheritDoc}//from   w w  w  .  j ava2 s.  co  m
 * 
 * @see org.osgi.service.cm.ManagedService#updated(java.util.Dictionary)
 */
@Override
public synchronized void updated(Dictionary properties) throws ConfigurationException {
    logger.info("Update method from managed service");

    String username = StringUtils
            .trimToNull((String) properties.get("org.opencastproject.publication.youtube.username"));
    String password = StringUtils
            .trimToNull((String) properties.get("org.opencastproject.publication.youtube.password"));
    String clientid = StringUtils
            .trimToNull((String) properties.get("org.opencastproject.publication.youtube.clientid"));
    String developerkey = StringUtils
            .trimToNull((String) properties.get("org.opencastproject.publication.youtube.developerkey"));
    String category = StringUtils
            .trimToNull((String) properties.get("org.opencastproject.publication.youtube.category"));
    String keywords = StringUtils
            .trimToNull((String) properties.get("org.opencastproject.publication.youtube.keywords"));

    String privacy = StringUtils
            .trimToNull((String) properties.get("org.opencastproject.publication.youtube.private"));

    String isChunked = StringUtils
            .trimToNull((String) properties.get("org.opencastproject.publication.youtube.chunked"));

    defaultPlaylist = StringUtils
            .trimToNull((String) properties.get("org.opencastproject.publication.youtube.default.playlist"));

    // Setup configuration from properties
    if (StringUtils.isBlank(clientid))
        throw new IllegalArgumentException("Youtube clientid must be specified");
    if (StringUtils.isBlank(developerkey))
        throw new IllegalArgumentException("Youtube developerkey must be specified");
    if (StringUtils.isBlank(username))
        throw new IllegalArgumentException("Youtube username must be specified");
    if (StringUtils.isBlank(password))
        throw new IllegalArgumentException("Youtube password must be specified");
    if (StringUtils.isBlank(category))
        throw new IllegalArgumentException("Youtube category must be specified");
    if (StringUtils.isBlank(keywords))
        throw new IllegalArgumentException("Youtube keywords must be specified");
    if (StringUtils.isBlank(privacy))
        throw new IllegalArgumentException("Youtube privacy must be specified");

    String uploadUrl = VIDEO_ENTRY_URL.replaceAll("\\{username\\}", username);

    config.setClientId(clientid);
    config.setDeveloperKey(developerkey);
    config.setUserId(username);
    config.setUploadUrl(uploadUrl);
    config.setPassword(password);
    config.setKeywords(keywords);
    config.setCategory(category);
    config.setVideoPrivate(Boolean.getBoolean(privacy));

    if (StringUtils.isNotBlank(isChunked))
        isDefaultChunked = Boolean.getBoolean(isChunked);
}

From source file:org.openhab.binding.knx.internal.connection.KNXConnection.java

@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    if (config != null) {
        sLogger.debug("KNXBinding configuration present. Setting up KNX bus connection.");
        sIp = (String) config.get("ip");

        String readingBusAddrString = (String) config.get("busaddr");
        if (StringUtils.isNotBlank(readingBusAddrString)) {
            sLocalSourceAddr = readingBusAddrString;
        }/*w  ww  . jav a  2  s  .c  o  m*/

        String readingIgnLocEv = (String) config.get("ignorelocalevents");
        if (StringUtils.isNotBlank(readingIgnLocEv)) {
            sIgnoreLocalSourceEvents = readingIgnLocEv.equalsIgnoreCase("true");
        }

        String connectionTypeString = (String) config.get("type");
        if (StringUtils.isNotBlank(connectionTypeString)) {
            if ("TUNNEL".equals(connectionTypeString)) {
                sIpConnectionType = KNXNetworkLinkIP.TUNNELING;
            } else if ("ROUTER".equals(connectionTypeString)) {
                sIpConnectionType = KNXNetworkLinkIP.ROUTING;
                if (StringUtils.isBlank(sIp)) {
                    sIp = DEFAULT_MULTICAST_IP;
                }
            } else {
                throw new ConfigurationException("type", "unknown IP connection type '" + connectionTypeString
                        + "'! Known types are either 'TUNNEL' or 'ROUTER'");
            }
        } else {
            sIpConnectionType = KNXNetworkLinkIP.TUNNELING;
        }

        String portConfig = (String) config.get("port");
        if (StringUtils.isNotBlank(portConfig)) {
            sPort = Integer.parseInt(portConfig);
        } else {
            sPort = KNXnetIPConnection.DEFAULT_PORT;
        }

        sLocalIp = (String) config.get("localIp");

        sSerialPort = (String) config.get("serialPort");

        String readingPauseString = (String) config.get("pause");
        if (StringUtils.isNotBlank(readingPauseString)) {
            sReadingPause = Long.parseLong(readingPauseString);
        }

        String responseTimeoutString = (String) config.get("timeout");
        if (StringUtils.isNotBlank(responseTimeoutString)) {
            long timeout = Long.parseLong(responseTimeoutString);
            if (timeout > 0) {
                sResponseTimeout = timeout;
            }
        }

        String readRetriesLimitString = (String) config.get("readRetries");
        if (StringUtils.isNotBlank(readRetriesLimitString)) {
            int readRetries = Integer.parseInt(readRetriesLimitString);
            if (readRetries > 0) {
                sReadRetriesLimit = readRetries;
            }
        }

        String autoReconnectPeriodString = (String) config.get("autoReconnectPeriod");
        if (StringUtils.isNotBlank(autoReconnectPeriodString)) {
            int autoReconnectPeriodValue = Integer.parseInt(autoReconnectPeriodString);
            if (autoReconnectPeriodValue >= 0) {
                sAutoReconnectPeriod = autoReconnectPeriodValue;
            }
        }

        String maxRefreshQueueEntriesString = (String) config.get("maxRefreshQueueEntries");
        if (StringUtils.isNotBlank(maxRefreshQueueEntriesString)) {
            try {
                int maxRefreshQueueEntriesValue = Integer.parseInt(maxRefreshQueueEntriesString);
                if (maxRefreshQueueEntriesValue >= 0) {
                    sMaxRefreshQueueEntries = maxRefreshQueueEntriesValue;
                }
            } catch (NumberFormatException e) {
                sLogger.warn(
                        "Error when trying to read parameter 'maxRefreshQueueEntries' from configuration. '{}' is not a number: using default.",
                        maxRefreshQueueEntriesString);
            }
        }

        String numberOfThreadsString = (String) config.get("numberOfThreads");
        if (StringUtils.isNotBlank(numberOfThreadsString)) {
            try {
                int numberOfThreadsValue = Integer.parseInt(numberOfThreadsString);
                if (numberOfThreadsValue >= 0) {
                    sNumberOfThreads = numberOfThreadsValue;
                }
            } catch (NumberFormatException e) {
                sLogger.warn(
                        "Error when trying to read parameter 'numberOfThreads' from configuration. '{}' is not a number: using default.",
                        numberOfThreadsString);
            }
        }

        String scheduledExecutorServiceShutdownTimeoutString = (String) config
                .get("scheduledExecutorServiceShutdownTimeout");
        if (StringUtils.isNotBlank(scheduledExecutorServiceShutdownTimeoutString)) {
            try {
                int scheduledExecutorServiceShutdownTimeoutValue = Integer
                        .parseInt(scheduledExecutorServiceShutdownTimeoutString);
                if (scheduledExecutorServiceShutdownTimeoutValue >= 0) {
                    sScheduledExecutorServiceShutdownTimeout = scheduledExecutorServiceShutdownTimeoutValue;
                }
            } catch (NumberFormatException e) {
                sLogger.warn(
                        "Error when trying to read parameter 'scheduledExecutorServiceShutdownTimeout' from configuration. '{}' is not a number: using default.",
                        scheduledExecutorServiceShutdownTimeoutString);
            }
        }

        if (sPC == null) {
            sLogger.debug("Not connected yet. Trying to connect.");
            if (!connect()) {
                sLogger.warn("Inital connection to KNX bus failed!");
                if (sAutoReconnectPeriod > 0) {
                    sLogger.info("KNX link will be retried in {} seconds", sAutoReconnectPeriod);
                    final Timer timer = new Timer();
                    TimerTask timerTask = new ConnectTimerTask(timer);
                    timer.schedule(timerTask, sAutoReconnectPeriod * 1000, sAutoReconnectPeriod * 1000);
                }
            } else {
                sLogger.debug("Success: connected.");
            }
        }
    } else {
        sLogger.info(
                "KNXBinding configuration is not present. Please check your configuration file or if not needed remove the KNX addon.");
    }
}

From source file:ch.entwine.weblounge.contentrepository.impl.ContentRepositoryServiceFactory.java

/**
 * {@inheritDoc}/*from w  ww. j  av  a 2  s.  co m*/
 * 
 * @see org.osgi.service.cm.ManagedServiceFactory#updated(java.lang.String,
 *      java.util.Dictionary)
 */
public void updated(String pid, Dictionary properties) throws ConfigurationException {

    // is this an update to an existing service?
    if (services.containsKey(pid)) {
        ServiceRegistration registration = services.get(pid);
        ManagedService service = (ManagedService) bundleCtx.getService(registration.getReference());
        service.updated(properties);
    }

    // Create a new content repository service instance
    else {
        String className = (String) properties.get(OPT_TYPE);
        if (StringUtils.isBlank(className)) {
            className = repositoryType;
        }
        Class<ContentRepository> repositoryImplementation;
        ContentRepository repository = null;
        try {
            repositoryImplementation = (Class<ContentRepository>) Class.forName(className);
            repository = repositoryImplementation.newInstance();
            repository.setEnvironment(environment);
            repository.setSerializer(serializer);

            // If this is a managed service, make sure it's configured properly
            // before the site is connected

            if (repository instanceof ManagedService) {
                Dictionary<Object, Object> finalProperties = new Hashtable<Object, Object>();

                // Add the default configuration according to the repository type
                Dictionary<Object, Object> configuration = loadConfiguration(repository.getType());
                if (configuration != null) {
                    for (Enumeration<Object> keys = configuration.keys(); keys.hasMoreElements();) {
                        Object key = keys.nextElement();
                        Object value = configuration.get(key);
                        if (value instanceof String)
                            value = ConfigurationUtils.processTemplate((String) value);
                        finalProperties.put(key, value);
                    }
                }

                // Overwrite the default configuration with what was passed in
                for (Enumeration<Object> keys = properties.keys(); keys.hasMoreElements();) {
                    Object key = keys.nextElement();
                    Object value = properties.get(key);
                    if (value instanceof String)
                        value = ConfigurationUtils.processTemplate((String) value);
                    finalProperties.put(key, value);
                }

                // push the repository configuration
                ((ManagedService) repository).updated(finalProperties);
            }

            // Register the service
            String serviceType = ContentRepository.class.getName();
            properties.put("service.pid", pid);
            services.put(pid, bundleCtx.registerService(serviceType, repository, properties));
        } catch (ClassNotFoundException e) {
            throw new ConfigurationException(OPT_TYPE,
                    "Repository implementation class " + className + " not found", e);
        } catch (InstantiationException e) {
            throw new ConfigurationException(OPT_TYPE,
                    "Error instantiating repository implementation class " + className + " not found", e);
        } catch (IllegalAccessException e) {
            throw new ConfigurationException(OPT_TYPE,
                    "Error accessing repository implementation class " + className + " not found", e);
        }

    }
}

From source file:org.opencastproject.fileupload.service.FileUploadServiceImpl.java

@Override
public synchronized void updated(Dictionary properties) throws ConfigurationException {
    // try to get time-to-live threshold for jobs, use default if not configured
    String dir = (String) properties.get(PROPKEY_UPLOAD_WORKDIR);
    if (dir != null) {
        workRoot = new File(dir);
        log.info("Configuration updated. Upload working directory set to {}.", dir);
    }/*w  ww  .ja  v a 2 s .  c  o  m*/
    try {
        jobMaxTTL = Integer.parseInt(((String) properties.get(PROPKEY_CLEANER_MAXTTL)).trim());
    } catch (Exception e) {
        jobMaxTTL = DEFAULT_CLEANER_MAXTTL;
        log.warn("Unable to update configuration. {}", e.getMessage());
    }
    log.info("Configuration updated. Jobs older than {} hours are deleted.", jobMaxTTL);
}

From source file:org.ops4j.pax.web.service.internal.Activator.java

private void determineServiceProperties(final Dictionary managedConfig, final Configuration config,
        final Integer httpPort, final Integer httpSecurePort) {
    final Hashtable<String, Object> toPropagate = new Hashtable<String, Object>();
    // first store all configuration properties as received via managed service
    if (managedConfig != null && !managedConfig.isEmpty()) {
        final Enumeration enumeration = managedConfig.keys();
        while (enumeration.hasMoreElements()) {
            String key = (String) enumeration.nextElement();
            toPropagate.put(key, managedConfig.get(key));
        }//from ww w  . j  a va2s .c o m
    }

    // then add/replace configuration properties
    setProperty(toPropagate, PROPERTY_HTTP_ENABLED, config.isHttpEnabled());
    setProperty(toPropagate, PROPERTY_HTTP_PORT, config.getHttpPort());
    setProperty(toPropagate, PROPERTY_HTTP_SECURE_ENABLED, config.isHttpEnabled());
    setProperty(toPropagate, PROPERTY_HTTP_SECURE_PORT, config.getHttpSecurePort());
    setProperty(toPropagate, PROPERTY_HTTP_USE_NIO, config.useNIO());
    setProperty(toPropagate, PROPERTY_SSL_CLIENT_AUTH_NEEDED, config.isClientAuthNeeded());
    setProperty(toPropagate, PROPERTY_SSL_CLIENT_AUTH_WANTED, config.isClientAuthWanted());
    setProperty(toPropagate, PROPERTY_SSL_KEYSTORE, config.getSslKeystore());
    setProperty(toPropagate, PROPERTY_SSL_KEYSTORE_TYPE, config.getSslKeystoreType());
    //store( toPropagate, PROPERTY_SSL_PASSWORD, config.getSslPassword());
    setProperty(toPropagate, PROPERTY_SSL_PASSWORD, null);
    //store( toPropagate, PROPERTY_SSL_KEYPASSWORD, config.getSslKeyPassword());
    setProperty(toPropagate, PROPERTY_SSL_KEYPASSWORD, null);
    setProperty(toPropagate, PROPERTY_TEMP_DIR, config.getTemporaryDirectory());
    setProperty(toPropagate, PROPERTY_SESSION_TIMEOUT, config.getSessionTimeout());
    setProperty(toPropagate, PROPERTY_SESSION_URL, config.getSessionUrl());
    setProperty(toPropagate, PROPERTY_SESSION_COOKIE, config.getSessionCookie());
    setProperty(toPropagate, PROPERTY_WORKER_NAME, config.getWorkerName());
    setProperty(toPropagate, PROPERTY_LISTENING_ADDRESSES, config.getListeningAddresses());

    // then replace ports
    setProperty(toPropagate, PROPERTY_HTTP_PORT, httpPort);
    setProperty(toPropagate, PROPERTY_HTTP_SECURE_PORT, httpSecurePort);

    m_httpServiceFactoryProps = toPropagate;
}

From source file:org.apache.sling.discovery.etcd.EtcdDiscoveryService.java

@Activate
protected void activate(ComponentContext cc) {

    final ThreadPoolManager threadPoolManager = this.threadPoolManager;
    if (threadPoolManager == null) {
        throw new IllegalStateException("ThreadPoolManager service not found");
    }//from   ww  w .j  a va 2s. c  o m

    final SlingSettingsService slingSettingsService = this.slingSettingsService;
    if (slingSettingsService == null) {
        throw new IllegalStateException("SlingSettingsService service not found");
    }

    final EtcdClientFactory etcdClientFactory = this.etcdClientFactory;
    if (etcdClientFactory == null) {
        throw new IllegalStateException("EtcdClientFactory service not found");
    }

    Dictionary props = cc.getProperties();
    String rootKey = PropertiesUtil.toString(props.get(ROOT_KEY), DEFAULT_ROOT_KEY);
    if (rootKey.endsWith("/") && rootKey.length() > 1) {
        rootKey = rootKey.substring(0, rootKey.length() - 1);
        LOG.debug("Chopped last slash from rootKey: {}", rootKey);
    }
    socketTimeout = PropertiesUtil.toInteger(props.get(SOCKET_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
    connectionTimeout = PropertiesUtil.toInteger(props.get(CONNECTION_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
    String slingId = slingSettingsService.getSlingId();
    String serverInfo = getServerInfo(cc);
    LOG.debug("slingId: {} serverInfo: {}", new String[] { slingId, serverInfo });
    BackOff announceRenewalPeriod = build(
            PropertiesUtil.toString(props.get(ANNOUNCE_RENEWAL_PERIOD), DEFAULT_ANNOUNCE_RENEWAL_PERIOD),
            DEFAULT_ANNOUNCE_RENEWAL_PERIOD);
    LOG.debug("announce renewal period: {}", announceRenewalPeriod);
    BackOff topologyUpdatePeriod = build(
            PropertiesUtil.toString(props.get(TOPOLOGY_UPDATE_PERIOD), DEFAULT_TOPOLOGY_UPDATE_PERIOD),
            DEFAULT_TOPOLOGY_UPDATE_PERIOD);
    LOG.debug("topology update period: {}", topologyUpdatePeriod);
    BackOff viewUpdatePeriod = build(
            PropertiesUtil.toString(props.get(VIEW_UPDATE_PERIOD), DEFAULT_VIEW_UPDATE_PERIOD),
            DEFAULT_VIEW_UPDATE_PERIOD);
    LOG.debug("view update period: {}", viewUpdatePeriod);
    BackOff etcdBackOff = build(PropertiesUtil.toString(props.get(ETCD_BACK_OFF), DEFAULT_ETCD_BACK_OFF),
            DEFAULT_ETCD_BACK_OFF);
    LOG.debug("etcd back-off: {}", etcdBackOff);
    BackOff ioErrorBackOff = build(
            PropertiesUtil.toString(props.get(IO_ERROR_BACK_OFF), DEFAULT_IO_ERROR_BACK_OFF),
            DEFAULT_IO_ERROR_BACK_OFF);
    LOG.debug("I/O error back-off: {}", ioErrorBackOff);
    int maxAnnounceTtl = new BigDecimal(
            announceRenewalPeriod.max() * EtcdDiscoveryService.ANNOUNCE_TTL_LEEWAY / 1000.0D)
                    .setScale(0, BigDecimal.ROUND_UP).intValue();
    LOG.debug("max announce ttl in second: {}", maxAnnounceTtl);
    String clusterId = PropertiesUtil.toString(props.get(CLUSTER_ID), DEFAULT_CLUSTER_ID);
    String clusteringMode = PropertiesUtil.toString(props.get(CLUSTERING_MODE), AUTOMATIC_CLUSTERING);
    final Clustering clustering;
    if (AUTOMATIC_CLUSTERING.equals(clusteringMode)) {

        final SlingRepository slingRepository = this.slingRepository;
        if (slingRepository == null) {
            throw new IllegalStateException("SlingRepository service not found");
        }

        final ResourceResolverFactory resourceResolverFactory = this.resourceResolverFactory;
        if (resourceResolverFactory == null) {
            throw new IllegalStateException("ResourceResolverFactory service not found");
        }

        Clustering automatic = new AutomaticClustering(slingRepository, resourceResolverFactory,
                DISCOVERY_PATH);
        if (automatic.isSupported()) {
            // repository mode supported.
            // we don't get the cluster id here,
            // as the method call may take time.
            clustering = automatic;
            LOG.info("Clustering mode 'Automatic' enabled.");
        } else {
            LOG.warn(
                    "The repository does not support 'Automatic' clustering mode. Falling back to 'Configuration' clustering mode.");
            clustering = buildConfigClustering(clusterId);
        }
    } else {
        clustering = buildConfigClustering(clusterId);
    }

    buildHttpClient(PropertiesUtil.toString(props.get(KEYSTORE_FILE_PATH), "").trim(),
            PropertiesUtil.toString(props.get(KEYSTORE_PWD_FILE_PATH), "").trim());
    URI endpoint = parseEndpoint(PropertiesUtil.toString(props.get(ENDPOINT), DEFAULT_ENDPOINT));
    EtcdClient etcdClient = etcdClientFactory.create(httpClient, endpoint);
    etcdStats = new EtcdStats(etcdClient);
    PropertiesMap propertiesMap = new PropertiesMap(slingId);
    Announce initAnnounce = buildInitAnnounce(slingId, serverInfo);
    AnnouncesMap announcesMap = new AnnouncesMap(initAnnounce);
    viewManager.updateView(buildInitView(initAnnounce, slingId)); // must happen before starting the LocalUpdater thread.
    etcdService = new EtcdService(etcdClient, rootKey);
    RunnerFactory factory = new RunnerFactoryImpl(etcdService, announcesMap, clustering, etcdBackOff,
            ioErrorBackOff, slingId, serverInfo, maxAnnounceTtl);
    etcdThreadPool = threadPoolManager.get("CoreOS etcd client threads");
    context = new Context(States.GET_CLUSTER, factory, etcdThreadPool);
    context.init(States.GET_CLUSTER);
    announcer = new Announcer(context, etcdService, announcesMap, propertiesMap, slingId, serverInfo,
            announceRenewalPeriod);
    etcdThreadPool.execute(announcer);
    remoteUpdater = new RemoteUpdater(context, etcdService, topologyUpdatePeriod, announcesMap, propertiesMap,
            slingId);
    etcdThreadPool.execute(remoteUpdater);
    localUpdater = new LocalUpdater(context, propertiesService, viewManager, viewUpdatePeriod, announcesMap,
            propertiesMap, slingId, serverInfo);
    etcdThreadPool.execute(localUpdater);
    LOG.info("Activated etcd discovery service for slingId: {}, serverInfo: {}, rootKey: {}",
            new Object[] { slingId, serverInfo, rootKey });
}