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.alarmdecoder.internal.AlarmDecoderBinding.java

@SuppressWarnings("rawtypes")
@Override// w ww.j av  a 2  s  . c  o m
public void updated(Dictionary config) throws ConfigurationException {
    if (config == null) {
        throw new ConfigurationException("alarmdecoder:connect", "no config!");
    }
    logger.debug("config updated!");
    try {
        m_connectString = (String) config.get("connect");
        if (m_connectString == null) {
            throw new ConfigurationException("alarmdecoder:connect", "no connect config in openhab.cfg!");
        }
        String[] parts = m_connectString.split(":");
        if (parts.length < 2) {
            throw new ConfigurationException("alarmdecoder:connect", "missing :, check openhab.cfg!");
        }
        if (parts[0].equals("tcp")) {
            parseTcpConfig(parts);
        } else if (parts[0].startsWith("serial")) {
            parseSerialConfig(parts);
        } else {
            throw new ConfigurationException("alarmdecoder:connect", "invalid parameter " + parts[0]);
        }

        String reconn = (String) config.get("reconnect");
        if (reconn != null && reconn.trim().length() > 0) {
            refreshInterval = Long.parseLong(reconn);
        }
        String acceptCommands = (String) config.get("send_commands_and_compromise_security");
        if (acceptCommands != null && acceptCommands.equalsIgnoreCase("true")) {
            logger.info("accepting commands!");
            m_acceptCommands = true;
        }
        setProperlyConfigured(true);
    } catch (ConfigurationException e) {
        logger.error("configuration error: {} ", e.getMessage(), e);
        throw e;
    }

}

From source file:org.opennaas.core.security.acl.ACLManager.java

/**
 * It is necessary to register the OSGi service here, because OSGi ConfigurationAdmin service has access to "ws.rest.url", required to register
 * our REST API//from  w w w.  ja v  a2 s.c o  m
 * 
 * @throws IOException
 */
private void registerOSGiService() throws IOException {
    Dictionary<String, String> props = new Hashtable<String, String>();
    ConfigurationAdminUtil configurationAdmin = new ConfigurationAdminUtil(Activator.getBundleContext());
    String url = configurationAdmin.getProperty("org.opennaas", "ws.rest.url");

    if (props != null) {
        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 + "/aclmanager");
        props.put("org.apache.cxf.rs.address", "/");
        props.put("org.apache.cxf.httpservice.requirefilter", "true");
    }
    log.info("Registering ws in url: " + props.get("org.apache.cxf.rs.httpservice.context"));
    Activator.getBundleContext().registerService(IACLManager.class.getName(), this, props);
}

From source file:org.codice.ddf.admin.core.impl.AdminConsoleService.java

/** @see AdminConsoleServiceMBean#getPropertiesForLocation(java.lang.String, java.lang.String) */
public Map<String, Object> getPropertiesForLocation(String pid, String location) throws IOException {
    if (pid == null || pid.length() < 1) {
        throw new IOException(ILLEGAL_PID_MESSAGE);
    }/*from   w  w  w.  j  av a2s.  c o m*/
    Map<String, Object> propertiesTable = new HashMap<>();
    Configuration config = configurationAdmin.getConfiguration(pid, location);

    if (isPermittedToViewService(config.getPid())) {
        Dictionary<String, Object> properties = config.getProperties();
        if (properties != null) {
            Enumeration<String> keys = properties.keys();
            while (keys.hasMoreElements()) {
                String key = keys.nextElement();
                propertiesTable.put(key, properties.get(key));
            }
        }
    }
    return propertiesTable;
}

From source file:org.openhab.io.dropbox.internal.DropboxSynchronizer.java

@SuppressWarnings("rawtypes")
@Override/*from w  w w.  j  a v a2 s .  c  o  m*/
public void updated(Dictionary config) throws ConfigurationException {
    if (config != null) {
        isProperlyConfigured = false;

        String appKeyString = (String) config.get("appkey");
        if (isNotBlank(appKeyString)) {
            DropboxSynchronizer.appKey = appKeyString;
        }

        String appSecretString = (String) config.get("appsecret");
        if (isNotBlank(appSecretString)) {
            DropboxSynchronizer.appSecret = appSecretString;
        }

        if (isBlank(DropboxSynchronizer.appKey) || isBlank(DropboxSynchronizer.appSecret)) {
            throw new ConfigurationException("dropbox:appkey",
                    "The parameters 'appkey' or 'appsecret' are missing! Please refer to your 'openhab.cfg'");
        }

        String fakeModeString = (String) config.get("fakemode");
        if (isNotBlank(fakeModeString)) {
            DropboxSynchronizer.fakeMode = BooleanUtils.toBoolean(fakeModeString);
        }

        String contentDirString = (String) config.get("contentdir");
        if (isNotBlank(contentDirString)) {
            DropboxSynchronizer.contentDir = contentDirString;
        }

        String uploadIntervalString = (String) config.get("uploadInterval");
        if (isNotBlank(uploadIntervalString)) {
            DropboxSynchronizer.uploadInterval = uploadIntervalString;
        }

        String downloadIntervalString = (String) config.get("downloadInterval");
        if (isNotBlank(downloadIntervalString)) {
            DropboxSynchronizer.downloadInterval = downloadIntervalString;
        }

        String syncModeString = (String) config.get("syncmode");
        if (isNotBlank(syncModeString)) {
            try {
                DropboxSynchronizer.syncMode = DropboxSyncMode.valueOf(syncModeString.toUpperCase());
            } catch (IllegalArgumentException iae) {
                throw new ConfigurationException("dropbox:syncmode", "Unknown SyncMode '" + syncModeString
                        + "'. Valid SyncModes are 'DROPBOX_TO_LOCAL', 'LOCAL_TO_DROPBOX' and 'BIDIRECTIONAL'.");
            }
        }

        String uploadFilterString = (String) config.get("uploadfilter");
        if (isNotBlank(uploadFilterString)) {
            String[] newFilterElements = uploadFilterString.split(",");
            uploadFilterElements = Arrays.asList(newFilterElements);
        }

        String downloadFilterString = (String) config.get("downloadfilter");
        if (isNotBlank(downloadFilterString)) {
            String[] newFilterElements = downloadFilterString.split(",");
            downloadFilterElements = Arrays.asList(newFilterElements);
        }

        // we got thus far, so we define this synchronizer as properly configured ...
        isProperlyConfigured = true;
        activateSynchronizer();
    }
}

From source file:org.openhab.binding.fht.internal.FHTBinding.java

/**
 * @{inheritDoc/*from ww w.  ja  v  a  2 s. c om*/
 */
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    if (config != null) {

        // to override the default refresh interval one has to add a
        // parameter to openhab.cfg like
        // <bindingName>:refresh=<intervalInMs>
        String refreshIntervalString = (String) config.get("refresh");
        if (StringUtils.isNotBlank(refreshIntervalString)) {
            refreshInterval = Long.parseLong(refreshIntervalString);
        }

        housecode = parseMandatoryValue(KEY_HOUSECODE, config);
        doTimeUpdate = Boolean.parseBoolean((String) config.get(KEY_UPDATE_TIME));
        if (doTimeUpdate) {
            timeUpdatecronExpression = (String) config.get(KEY_UPDATE_CRON);
            if (StringUtils.isEmpty(timeUpdatecronExpression)) {
                setProperlyConfigured(false);
                throw new ConfigurationException(KEY_UPDATE_CRON,
                        "Time update was configured but no cron expression");
            }
            updateTimeJobKey = scheduleJob(UpdateFHTTimeJob.class, timeUpdatecronExpression);
        } else {
            unscheduleJob(updateTimeJobKey);
        }

        requestReports = Boolean.parseBoolean((String) config.get(KEY_REPORTS));
        if (requestReports) {
            reportsCronExpression = (String) config.get(KEY_REPORTS_CRON);
            if (StringUtils.isEmpty(reportsCronExpression)) {
                setProperlyConfigured(false);
                throw new ConfigurationException(KEY_REPORTS_CRON,
                        "Reports are requested, bu no cron expression is supplied");
            }
            requestReportJobKey = scheduleJob(RequestReportsJob.class, reportsCronExpression);
        } else {
            unscheduleJob(requestReportJobKey);
        }

        // At last the device, after we received all other config values
        String deviceName = parseMandatoryValue(KEY_DEVICE, config);
        setNewDeviceName(deviceName);
        setProperlyConfigured(true);
    }
}

From source file:org.openhab.binding.gpsd.internal.GPSdBinding.java

/**
 * @{inheritDoc//from   w  ww  .j av  a 2 s.c o  m
 */
@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");

        }

    }
}

From source file:org.codice.ddf.configuration.admin.ImportMigrationConfigurationAdminEntry.java

private boolean propertiesMatch() {
    final Dictionary<String, Object> props = memoryConfiguration.getProperties();

    if (props == null) {
        return false;
    }//from   ww w .ja va 2 s .c  om
    // remove bundle location, factory pid, and pid from the dictionary as we do not want to match
    // these
    props.remove(ConfigurationAdmin.SERVICE_FACTORYPID);
    props.remove(ConfigurationAdmin.SERVICE_BUNDLELOCATION);
    props.remove(Constants.SERVICE_PID);
    if (properties.size() != props.size()) {
        return false;
    }
    // @formatter:off - to shut up checkstyle!!!!!!!
    for (final Enumeration<String> e = properties.keys(); e.hasMoreElements();) {
        // @formatter:on
        final String key = e.nextElement();

        if (!Objects.deepEquals(properties.get(key), props.get(key))) {
            return false;
        }
    }
    return true;
}

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

@SuppressWarnings("unchecked")
private HttpServiceContext addContext(final ContextModel model) {
    Bundle bundle = model.getBundle();/*from   w  w w  .ja  v a2s .c  om*/
    BundleContext bundleContext = BundleUtils.getBundleContext(bundle);
    // scan for ServletContainerInitializers
    Set<Bundle> bundlesInClassSpace = ClassPathUtil.getBundlesInClassSpace(bundle, new HashSet<Bundle>());

    if (jettyBundle != null) {
        ClassPathUtil.getBundlesInClassSpace(jettyBundle, bundlesInClassSpace);
    }

    for (URL u : ClassPathUtil.findResources(bundlesInClassSpace, "/META-INF/services",
            "javax.servlet.ServletContainerInitializer", true)) {
        try {
            InputStream is = u.openStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            // only the first line is read, it contains the name of the
            // class.
            String className = reader.readLine();
            LOG.info("will add {} to ServletContainerInitializers", className);

            if (className.endsWith("JasperInitializer")) {
                LOG.info("Skipt {}, because specialized handler will be present", className);
                continue;
            }

            Class<?> initializerClass;

            try {
                initializerClass = bundle.loadClass(className);
            } catch (ClassNotFoundException ignore) {
                initializerClass = jettyBundle.loadClass(className);
            }

            // add those to the model contained ones
            Map<ServletContainerInitializer, Set<Class<?>>> containerInitializers = model
                    .getContainerInitializers();

            ServletContainerInitializer initializer = (ServletContainerInitializer) initializerClass
                    .newInstance();

            if (containerInitializers == null) {
                containerInitializers = new HashMap<ServletContainerInitializer, Set<Class<?>>>();
                model.setContainerInitializers(containerInitializers);
            }

            Set<Class<?>> setOfClasses = new HashSet<Class<?>>();
            // scan for @HandlesTypes
            HandlesTypes handlesTypes = initializerClass.getAnnotation(HandlesTypes.class);
            if (handlesTypes != null) {
                Class<?>[] classes = handlesTypes.value();

                for (Class<?> klass : classes) {
                    boolean isAnnotation = klass.isAnnotation();
                    boolean isInteraface = klass.isInterface();

                    if (isAnnotation) {
                        try {
                            BundleAnnotationFinder baf = new BundleAnnotationFinder(
                                    packageAdminTracker.getService(), bundle);
                            List<Class<?>> annotatedClasses = baf
                                    .findAnnotatedClasses((Class<? extends Annotation>) klass);
                            setOfClasses.addAll(annotatedClasses);
                        } catch (Exception e) {
                            LOG.warn("Failed to find annotated classes for ServletContainerInitializer", e);
                        }
                    } else if (isInteraface) {
                        BundleAssignableClassFinder basf = new BundleAssignableClassFinder(
                                packageAdminTracker.getService(), new Class[] { klass }, bundle);
                        Set<String> interfaces = basf.find();
                        for (String interfaceName : interfaces) {
                            setOfClasses.add(bundle.loadClass(interfaceName));
                        }
                    } else {
                        // class
                        BundleAssignableClassFinder basf = new BundleAssignableClassFinder(
                                packageAdminTracker.getService(), new Class[] { klass }, bundle);
                        Set<String> classNames = basf.find();
                        for (String klassName : classNames) {
                            setOfClasses.add(bundle.loadClass(klassName));
                        }
                    }
                }
            }
            containerInitializers.put(initializer, setOfClasses);
            LOG.info("added ServletContainerInitializer: {}", className);
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IOException e) {
            LOG.warn(
                    "failed to parse and instantiate of javax.servlet.ServletContainerInitializer in classpath");
        }
    }

    HttpServiceContext context = new HttpServiceContext((HandlerContainer) getHandler(),
            model.getContextParams(), getContextAttributes(bundleContext), model.getContextName(),
            model.getHttpContext(), model.getAccessControllerContext(), model.getContainerInitializers(),
            model.getJettyWebXmlURL(), model.getVirtualHosts());
    context.setClassLoader(model.getClassLoader());
    Integer modelSessionTimeout = model.getSessionTimeout();
    if (modelSessionTimeout == null) {
        modelSessionTimeout = sessionTimeout;
    }
    String modelSessionCookie = model.getSessionCookie();
    if (modelSessionCookie == null) {
        modelSessionCookie = sessionCookie;
    }
    String modelSessionDomain = model.getSessionDomain();
    if (modelSessionDomain == null) {
        modelSessionDomain = sessionDomain;
    }
    String modelSessionPath = model.getSessionPath();
    if (modelSessionPath == null) {
        modelSessionPath = sessionPath;
    }
    String modelSessionUrl = model.getSessionUrl();
    if (modelSessionUrl == null) {
        modelSessionUrl = sessionUrl;
    }
    Boolean modelSessionCookieHttpOnly = model.getSessionCookieHttpOnly();
    if (modelSessionCookieHttpOnly == null) {
        modelSessionCookieHttpOnly = sessionCookieHttpOnly;
    }
    Boolean modelSessionSecure = model.getSessionCookieSecure();
    if (modelSessionSecure == null) {
        modelSessionSecure = sessionCookieSecure;
    }
    String workerName = model.getSessionWorkerName();
    if (workerName == null) {
        workerName = sessionWorkerName;
    }
    configureSessionManager(context, modelSessionTimeout, modelSessionCookie, modelSessionDomain,
            modelSessionPath, modelSessionUrl, modelSessionCookieHttpOnly, modelSessionSecure, workerName,
            lazyLoad, storeDirectory);

    if (model.getRealmName() != null && model.getAuthMethod() != null) {
        configureSecurity(context, model.getRealmName(), model.getAuthMethod(), model.getFormLoginPage(),
                model.getFormErrorPage());
    }

    configureJspConfigDescriptor(context, model);

    LOG.debug("Added servlet context: " + context);

    if (isStarted()) {
        try {
            LOG.debug("(Re)starting servlet contexts...");
            // start the server handler if not already started
            Handler serverHandler = getHandler();
            if (!serverHandler.isStarted() && !serverHandler.isStarting()) {
                serverHandler.start();
            }
            // if the server handler is a handler collection, seems like
            // jetty will not automatically
            // start inner handlers. So, force the start of the created
            // context
            if (!context.isStarted() && !context.isStarting()) {
                LOG.debug("Registering ServletContext as service. ");
                Dictionary<String, String> properties = new Hashtable<String, String>();
                properties.put("osgi.web.symbolicname", bundle.getSymbolicName());

                Dictionary<?, ?> headers = bundle.getHeaders();
                String version = (String) headers.get(Constants.BUNDLE_VERSION);
                if (version != null && version.length() > 0) {
                    properties.put("osgi.web.version", version);
                }

                // Context servletContext = context.getServletContext();
                String webContextPath = context.getContextPath();

                properties.put("osgi.web.contextpath", webContextPath);

                context.registerService(bundleContext, properties);
                LOG.debug("ServletContext registered as service. ");

            }
            // CHECKSTYLE:OFF
        } catch (Exception ignore) {
            LOG.error("Could not start the servlet context for http context [" + model.getHttpContext() + "]",
                    ignore);
            if (ignore instanceof MultiException) {
                LOG.error("MultiException found: ");
                MultiException mex = (MultiException) ignore;
                List<Throwable> throwables = mex.getThrowables();
                for (Throwable throwable : throwables) {
                    LOG.error(throwable.getMessage());
                }
            }
        }
        // CHECKSTYLE:ON
    }
    return context;
}

From source file:org.jabsorb.serializer.impl.DictionarySerializer.java

public Object marshall(SerializerState state, Object p, Object o) throws MarshallException {
    Dictionary ht = (Dictionary) o;
    JSONObject obj = new JSONObject();
    JSONObject mapdata = new JSONObject();

    try {//  w  w w .  j  a v  a 2  s . co m
        if (ser.getMarshallClassHints()) {
            obj.put("javaClass", o.getClass().getName());
        }
        obj.put("map", mapdata);
        state.push(o, mapdata, "map");
    } catch (JSONException e) {
        throw new MarshallException("Could not put data" + e.getMessage(), e);
    }
    Object key = null;

    try {
        Enumeration en = ht.keys();
        while (en.hasMoreElements()) {
            key = en.nextElement();
            String keyString = key.toString(); // only support String keys

            Object json = ser.marshall(state, mapdata, ht.get(key), keyString);

            // omit the object entirely if it's a circular reference or duplicate
            // it will be regenerated in the fixups phase
            if (JSONSerializer.CIRC_REF_OR_DUPLICATE != json) {
                mapdata.put(keyString, json);
            }

        }
    } catch (MarshallException e) {
        throw new MarshallException("map key " + key + " " + e.getMessage(), e);
    } catch (JSONException e) {
        throw new MarshallException("map key " + key + " " + e.getMessage(), e);
    } finally {
        state.pop();
    }
    return obj;
}

From source file:org.openhab.binding.openenergymonitor.internal.OpenEnergyMonitorBinding.java

/**
 * @{inheritDoc//from  w  ww .  jav a  2 s .  c o  m
 */
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {

    if (config != null) {

        HashMap<String, OpenEnergyMonitorParserRule> parsingRules = new HashMap<String, OpenEnergyMonitorParserRule>();

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

            String value = (String) config.get(key);

            if ("udpPort".equals(key)) {
                if (StringUtils.isNotBlank(value)) {
                    udpPort = Integer.parseInt(value);
                }
            } else if ("serialPort".equals(key)) {
                serialPort = value;
            } else if ("simulate".equals(key)) {
                if (StringUtils.isNotBlank(value)) {
                    simulate = Boolean.parseBoolean(value);
                }
            } else {

                // process all data parsing rules
                try {
                    OpenEnergyMonitorParserRule rule = new OpenEnergyMonitorParserRule(value);
                    parsingRules.put(key, rule);
                } catch (OpenEnergyMonitorException e) {
                    throw new ConfigurationException(key, "invalid parser rule", e);
                }
            }

        }

        if (parsingRules != null) {

            dataParser = new OpenEnergyMonitorDataParser(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();
        messageListener.start();
    }
}