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.hpt.internal.HptBinding.java

/**
 * @{inheritDoc//  w w w. j a  va2 s. co m
 */
@Override
public void updated(Dictionary config) throws ConfigurationException {

    logger.debug("High Precision Timer Updated");
    if (config != null) {
        logger.debug("High Precision Timer Configuration not null");

        String refreshIntervalString = (String) config.get("refresh");

        if (StringUtils.isNotBlank(refreshIntervalString)) {
            refreshInterval = Long.parseLong(refreshIntervalString);
        }

        this.item = (Item) config.get("item");
        if (this.item != null) {
            logger.error("No Item name configured");
            //   setProperlyConfigured(false);
            throw new ConfigurationException("Item", "The device name can't be empty");
        } else {
            //setNewDeviceName(deviceName);
        }
        // setProperlyConfigured(true);
        timer.scheduleAtFixedRate(task, refreshInterval, refreshInterval);

        /*   HashMap<String, OBDParserRule> parsingRules = new HashMap<String, OBDParserRule>();
                
           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 ("device".equals(key)) {
                 if (StringUtils.isNotBlank(value)) {
          device = value;
          logger.debug("Using serial device {}", device.toString());
                 }
              } else if ("speed".equals(key)) {
                 speed = Integer.parseInt(value);
                 logger.debug("Speed  set to {}", speed);
              } else if ("refresh".equals(key)) {
                 refresh = Integer.parseInt(value);
                 logger.debug("Refresh  set to {}", refresh);
              } else if ("retry".equals(key)) {
          retry = Integer.parseInt(value);
          logger.debug("Retry set to {}", retry );
              }
              else {
                
                 // process all data parsing rules
              try {
         OBDParserRule rule = new OBDParserRule(value);
         parsingRules.put(key, rule);
               } catch (HptException e) {
          throw new ConfigurationException(key, "invalid parser rule", e);
               }
              }
                
           }
                      
           if (parsingRules != null) {
              logger.debug("OBD Data Parser called");
              dataParser = new OBDDataParser(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);
              }
           }
                   
           messageListener = new MessageListener( this );
           messageListener.start(); */

    } else {
        timer.scheduleAtFixedRate(task, 1000, 1000);

    }
}

From source file:org.openhab.binding.weather.internal.common.WeatherConfig.java

/**
 * Parses and validates the properties in openhab.cfg.
 */// w  w  w.ja  v  a2 s .co  m
public void parse(Dictionary<String, ?> properties) throws ConfigurationException {
    valid = false;
    if (properties != null) {
        Enumeration<String> keys = properties.keys();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();

            String value = StringUtils.trimToNull((String) properties.get(key));
            if (StringUtils.startsWithIgnoreCase(key, "apikey")) {
                parseApiKey(key, value);
            } else if (StringUtils.startsWithIgnoreCase(key, "location")) {
                parseLocation(key, value);
            }
        }

        // check all LocationConfigs
        for (LocationConfig lc : locationConfigs.values()) {
            if (!lc.isValid()) {
                throw new ConfigurationException("weather", "Incomplete location config for locationId '"
                        + lc.getLocationId() + "', please check your openhab.cfg!");
            }
            if (lc.getProviderName() != ProviderName.YAHOO
                    && !providerConfigs.containsKey(lc.getProviderName())) {
                throw new ConfigurationException("weather", "No apikey found for provider '"
                        + lc.getProviderName() + "', please check your openhab.cfg!");
            }
        }

        // check all ProviderConfigs
        for (ProviderConfig pc : providerConfigs.values()) {
            if (!pc.isValid()) {
                throw new ConfigurationException("weather", "Invalid apikey config for provider '"
                        + pc.getProviderName() + "', please check your openhab.cfg!");
            }
        }

        valid = locationConfigs.size() > 0;
    }
}

From source file:Main.java

private static Manifest getSurrogateManifest(Dictionary compositeManifest, BundleDescription compositeDesc,
        ExportPackageDescription[] matchingExports) {
    Manifest manifest = new Manifest();
    Attributes attributes = manifest.getMainAttributes();
    attributes.putValue("Manifest-Version", "1.0"); //$NON-NLS-1$//$NON-NLS-2$
    // Ignore the manifest version from the map
    // always use bundle manifest version 2
    attributes.putValue(Constants.BUNDLE_MANIFESTVERSION, "2"); //$NON-NLS-1$
    // Ignore the Equinox composite bundle header
    attributes.putValue(BaseStorageHook.COMPOSITE_HEADER, BaseStorageHook.SURROGATE_BUNDLE);

    if (compositeDesc != null && matchingExports != null) {
        // convert the exports from the composite into imports
        addImports(attributes, compositeDesc, matchingExports);

        // convert the matchingExports from the composite into exports
        addExports(attributes, compositeDesc, matchingExports);
    }/*from  www . j a  v  a 2 s.c om*/

    // add the rest
    for (Enumeration keys = compositeManifest.keys(); keys.hasMoreElements();) {
        Object header = keys.nextElement();
        if (Constants.BUNDLE_MANIFESTVERSION.equals(header) || BaseStorageHook.COMPOSITE_HEADER.equals(header)
                || Constants.IMPORT_PACKAGE.equals(header) || Constants.EXPORT_PACKAGE.equals(header))
            continue;
        if (header instanceof String && compositeManifest.get(header) instanceof String)
            attributes.putValue((String) header, (String) compositeManifest.get(header));
    }
    return manifest;
}

From source file:com.whizzosoftware.hobson.bootstrap.api.hub.OSGIHubManager.java

@Override
public void setHubPassword(String userId, String hubId, PasswordChange change) {
    try {//from   w  ww . j a v  a 2s. com
        Configuration config = getConfiguration();
        Dictionary props = getConfigurationProperties(config);

        // verify the old password
        String shaOld = DigestUtils.sha256Hex(change.getCurrentPassword());
        String hubPassword = (String) props.get(ADMIN_PASSWORD);
        if (hubPassword != null && !hubPassword.equals(shaOld)) {
            throw new HobsonRuntimeException("The current hub password is invalid");
        }

        // verify the password meets complexity requirements
        if (!change.isValid()) {
            throw new HobsonInvalidRequestException("New password does not meet complexity requirements");
        }

        // set the new password
        props.put(ADMIN_PASSWORD, DigestUtils.sha256Hex(change.getNewPassword()));

        updateConfiguration(config, props);
    } catch (IOException e) {
        throw new HobsonRuntimeException("Error setting hub password", e);
    }
}

From source file:net.cellar.hazelcast.HazelcastGroupManager.java

@Override
public void registerGroup(Group group) {
    String groupName = group.getName();
    createGroup(groupName);/*from   w ww  .  ja v  a 2  s  .c o  m*/
    ITopic topic = instance.getTopic(Constants.TOPIC + "." + groupName);

    Properties serviceProperties = new Properties();
    serviceProperties.put("type", "group");
    serviceProperties.put("name", groupName);

    if (!producerRegistrations.containsKey(groupName)) {
        TopicProducer producer = new TopicProducer();
        producer.setTopic(topic);
        producer.setNode(getNode());

        ServiceRegistration producerRegistration = bundleContext
                .registerService(EventProducer.class.getCanonicalName(), producer, serviceProperties);
        producerRegistrations.put(groupName, producerRegistration);
    }

    if (!consumerRegistrations.containsKey(groupName)) {
        TopicConsumer consumer = new TopicConsumer();
        consumer.setDispatcher(dispatcher);
        consumer.setTopic(topic);
        consumer.setNode(getNode());
        consumer.init();

        ServiceRegistration consumerRegistration = bundleContext
                .registerService(EventConsumer.class.getCanonicalName(), consumer, serviceProperties);
        consumerRegistrations.put(groupName, consumerRegistration);
    }

    group.getMembers().add(getNode());
    listGroups().put(groupName, group);

    //Add group to configuration
    try {
        Configuration configuration = configurationAdmin.getConfiguration(Configurations.NODE);
        Dictionary<String, String> properties = configuration.getProperties();
        String groups = properties.get(Configurations.GROUPS_KEY);
        if (groups == null || groups.isEmpty()) {
            groups = groupName;
        } else {

            Set<String> groupNamesSet = convertStringToSet(groups);
            groupNamesSet.add(groupName);
            groups = convertSetToString(groupNamesSet);
        }

        if (groups == null || groups.isEmpty()) {
            groups = groupName;
        }
        properties.put(Configurations.GROUPS_KEY, groups);
        configuration.update(properties);
    } catch (IOException e) {
        logger.error("Error reading group configuration {}", group);
    }

    //Sync
    try {
        ServiceReference[] serviceReferences = bundleContext
                .getAllServiceReferences("net.cellar.core.Synchronizer", null);
        if (serviceReferences != null && serviceReferences.length > 0) {
            for (ServiceReference ref : serviceReferences) {
                Synchronizer synchronizer = (Synchronizer) bundleContext.getService(ref);
                if (synchronizer.isSyncEnabled(group)) {
                    synchronizer.pull(group);
                    synchronizer.push(group);
                }
                bundleContext.ungetService(ref);
            }
        }
    } catch (InvalidSyntaxException e) {
        logger.error("Error looking up for Synchronizers", e);
    }
}

From source file:org.apache.sling.superimposing.impl.SuperimposingManagerImpl.java

@Activate
protected synchronized void activate(final ComponentContext ctx) throws LoginException, RepositoryException {

    // check enabled state
    @SuppressWarnings("unchecked")
    final Dictionary<String, Object> props = ctx.getProperties();
    this.enabled = PropertiesUtil.toBoolean(props.get(ENABLED_PROPERTY), ENABLED_DEFAULT);
    log.debug("Config: " + "Enabled={} ", enabled);
    if (!isEnabled()) {
        return;//from  ww w. j  a v a2 s .c om
    }

    // get "find all" queries
    this.findAllQueries = PropertiesUtil.toStringArray(props.get(FINDALLQUERIES_PROPERTY),
            new String[] { FINDALLQUERIES_DEFAULT });
    this.obervationPaths = PropertiesUtil.toStringArray(props.get(OBSERVATION_PATHS_PROPERTY),
            new String[] { OBSERVATION_PATHS_DEFAULT });

    if (null == resolver) {
        bundleContext = ctx.getBundleContext();
        resolver = resolverFactory.getAdministrativeResourceResolver(null);

        // Watch for events on the root to register/deregister superimposings at runtime
        // For each observed path create an event listener object which redirects the event to the main class
        final Session session = resolver.adaptTo(Session.class);
        if (session != null) {
            this.observationEventListeners = new EventListener[this.obervationPaths.length];
            for (int i = 0; i < this.obervationPaths.length; i++) {
                this.observationEventListeners[i] = new EventListener() {
                    public void onEvent(EventIterator events) {
                        SuperimposingManagerImpl.this.onEvent(events);
                    }
                };
                session.getWorkspace().getObservationManager().addEventListener(
                        this.observationEventListeners[i],
                        Event.NODE_ADDED | Event.NODE_REMOVED | Event.PROPERTY_ADDED | Event.PROPERTY_CHANGED
                                | Event.PROPERTY_REMOVED,
                        this.obervationPaths[i], // absolute path
                        true, // isDeep
                        null, // uuids
                        null, // node types
                        true); // noLocal
            }
        }

        // register all superimposing definitions that already exist
        initialization = Executors.newSingleThreadExecutor().submit(new Runnable() {
            public void run() {
                try {
                    registerAllSuperimposings();
                } catch (Throwable ex) {
                    log.warn("Error registering existing superimposing resources on service startup.", ex);
                }
            }
        });
    }
}

From source file:ch.entwine.weblounge.kernel.publisher.EndpointPublishingService.java

/**
 * Configures this service using the given configuration properties.
 * //w w w .j a v a2 s.  c o  m
 * @param config
 *          the service configuration
 * @throws ConfigurationException
 *           if configuration fails
 */
private synchronized boolean configure(Dictionary<?, ?> config) throws ConfigurationException {

    boolean changed = false;

    // context path
    String updatedRestMountpoint = StringUtils.trim((String) config.get(OPT_PATH));
    if (updatedRestMountpoint != null) {
        if (!updatedRestMountpoint.startsWith("/"))
            throw new IllegalArgumentException("Context path (" + OPT_PATH + ") must start with a '/'");
        changed |= !updatedRestMountpoint.equals(defaultContextPathPrefix);
        defaultContextPathPrefix = updatedRestMountpoint;
    }

    return changed;
}

From source file:org.openhab.binding.wemo.internal.WemoBinding.java

/**
 * @{inheritDoc}//from w  w  w.j  a v  a2 s  .c o  m
 */
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    setProperlyConfigured(true);
    if (config != null) {
        String refreshIntervalString = (String) config.get("refresh");
        if (StringUtils.isNotBlank(refreshIntervalString)) {
            refreshInterval = Long.parseLong(refreshIntervalString);
        }

    }
}

From source file:org.openhab.binding.s300th.internal.S300THBinding.java

/**
 * @{inheritDoc//from  w ww .ja v a 2  s . c  o m
 */
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    logger.debug("Received new config");
    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);
        }
        String deviceName = (String) config.get(KEY_DEVICE_NAME);
        if (StringUtils.isEmpty(deviceName)) {
            logger.error("No device name configured");
            setProperlyConfigured(false);
            throw new ConfigurationException(KEY_DEVICE_NAME, "The device name can't be empty");
        } else {
            setNewDeviceName(deviceName);
        }

        setProperlyConfigured(true);
        // read further config parameters here ...

    }
}

From source file:org.opencastproject.loadtest.impl.LoadTest.java

/**
 * Sets a new URI to hit the core with.//from w  w  w  .j a va 2 s  .co  m
 * 
 * @param properties
 *          The new properties to extract the property from.
 * @throws InvalidConfigurationException
 *           Thrown if property doesn't exist
 */
@SuppressWarnings("unchecked")
private void updateCoreAddress(Dictionary properties) throws InvalidConfigurationException {
    String newCoreAddress = StringUtils.trimToNull((String) properties.get(CORE_ADDRESS_KEY));
    if (newCoreAddress != null) {
        coreAddress = newCoreAddress;
    } else if (componentContext != null && componentContext.getBundleContext() != null) {
        // Use the core address as a default.
        coreAddress = componentContext.getBundleContext().getProperty(BUNDLE_CONTEXT_SERVER_URL);
        if (coreAddress == null) {
            throw new InvalidConfigurationException(
                    "The core address must be set in the configuration file so that loadtesting will occur. It isn't set in {FELIX_HOME}/conf/config.properties or {FELIX_HOME}/conf/services/org.opencastproject.loadtest.impl.LoadTestFactory.properties");
        }
    }
}