Example usage for java.util Dictionary keys

List of usage examples for java.util Dictionary keys

Introduction

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

Prototype

public abstract Enumeration<K> keys();

Source Link

Document

Returns an enumeration of the keys in this dictionary.

Usage

From source file:org.openhab.binding.paradox.internal.ParadoxBinding.java

/**
 * @{inheritDoc/*from  w  w w .j  a v  a2 s.  co  m*/
 */
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {

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

    if (config != null) {
        /*         if (deviceConfigCache == null) {
                    deviceConfigCache = new HashMap<String, DeviceConfig>();
                 }
        */
        HashMap<String, ParadoxDataParserRule> parsingRules = new HashMap<String, ParadoxDataParserRule>();

        String granularityString = (String) config.get("refresh");
        if (StringUtils.isNotBlank(granularityString)) {
            granularity = Integer.parseInt(granularityString);
        }

        Enumeration<String> keys = config.keys();

        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();

            // the config-key enumeration contains additional keys that we
            // don't want to process here ...
            if ("service.pid".equals(key)) {
                continue;
            }

            // better - more Paradox devices...
            /*            Matcher matcher = EXTRACT_CONFIG_PATTERN.matcher(key);
                    
                        if (!matcher.matches()) {
                           logger.warn("given config key '"
             + key
             + "' does not follow the expected pattern '<deviceId>.<type|serialPort|refresh>'");
                           continue;
                        }
                    
                        matcher.reset();
                        matcher.find();
                    
                        String deviceId = matcher.group(1);
                    
                        DeviceConfig deviceConfig = deviceConfigCache.get(deviceId);
                    
                        if (deviceConfig == null) {
                           logger.debug("Added new device {}", deviceId);
                           deviceConfig = new DeviceConfig(deviceId);
                           deviceConfigCache.put(deviceId, deviceConfig);
                        }
                    
                        String configKey = matcher.group(2);
                        String value = (String) config.get(key);
                    
                        /**
                         * parsing of valid config:
                         * 
            ############################## Paradox Alarm Binding ##################################
            #
            # Serial port of the first Paradox alarm system to control: 
            # paradox:<devId1>.serialPort=
            #
            # Type of the Paradox printer port, to which we are connecting via serial cable
            # valid options are: PTR1, PTR3, simulate (required)
            # paradox:<devId1>.type=
            #
            # Refresh rate in miliseconds of the in-directional items (optional, defaults to 6000)
            # valid for PTR3 only
            # paradox:<devId1>.refresh=
                    
            # example of valid settings:
            paradox:homealarm.serialPort=COM10
            paradox:homealarm.type=simulate
            paradox:homealarm.refresh=6000
                     
                         *
                        if ("serialPort".equals(configKey)) {
                           deviceConfig.serialPort = value;
                                   
                        } else if ("type".equals(configKey)) {
                           if ("PTR1".equals(value))     deviceConfig.type = PTRtype.PTR1;
                           else if("PTR3".equals(value)) deviceConfig.type = PTRtype.PTR3;
                           else deviceConfig.type = PTRtype.SIMULATE;
                                   
                        } else if ("simulate".equals(configKey)) {
                           if (StringUtils.isNotBlank(value)) {
                              deviceConfig.type = PTRtype.SIMULATE;
                           }
                        } else if ("refresh".equals(configKey)) {
                           deviceConfig.granularity = Integer.parseInt(value);
                        }
                          else
                           throw new ConfigurationException(configKey,
                              "the given configKey '" + configKey + "' is unknown");
                        }
                             
                                
                     setProperlyConfigured(true);
                    
            */
            /**
                        ############################## Paradox Alarm Binding ##################################
                        #
                        # Serial port of the Paradox alarm system to control (required): 
                        # paradox.serialPort=
                        #
                        # Type of the Paradox printer port, to which we are connecting via serial cable
                        # valid options are: PTR1, PTR3 (required)  // use 'simulate' for tests only
                        # paradox.type=
                        #
                        # Refresh rate in milliseconds of the in-directional items (optional, defaults to 6000)
                        # valid for PTR3 only
                        # paradox.refresh=
                    
                        # example of valid settings:
                        paradox.serialPort=COM10
                        paradox.type=PTR1
                        paradox.refresh=6000
            */
            String value = (String) config.get(key);

            if ("serialPort".equals(key)) {
                serialPort = value;

            } else if ("type".equals(key)) {
                if ("PTR1".equals(value))
                    deviceType = PTRtype.PTR1;
                else if ("PTR3".equals(value))
                    deviceType = PTRtype.PTR3;
                else
                    deviceType = PTRtype.SIMULATE;

            } else if ("simulate".equals(key)) {
                if (StringUtils.isNotBlank(value)) {
                    deviceType = PTRtype.SIMULATE;
                }
            } else if ("refresh".equals(key)) {
                granularity = Integer.parseInt(value);
            } else
                throw new ConfigurationException(key, "the given configKey '" + key + "' is unknown");
        }

        if (parsingRules != null) {

            dataParser = new ParadoxDataParser(parsingRules);
        }

        messageListener = new MessageListener();
        messageListener.start();
    }
}

From source file:org.liveSense.misc.configloader.ConfigurationLoader.java

/**
 * Set the configuration based on the config file.
 *
 * @param f//from   ww  w . j  av a2  s  .  co m
 *            Configuration file
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
boolean setConfig(URL f) throws Exception {
    Properties p = new Properties();

    @SuppressWarnings("rawtypes")
    Dictionary ht = new Hashtable();

    InputStream in = new BufferedInputStream(f.openStream());
    try {
        // If the file name ends with .config, we using the Felix configuration format
        if (f.getFile().endsWith(".config")) {
            ht = ConfigurationHandler.read(in);
        } else {
            in.mark(1);
            boolean isXml = in.read() == '<';
            in.reset();
            if (isXml) {
                p.loadFromXML(in);
            } else {
                p.load(in);
            }
            ((Hashtable) ht).putAll(p);
        }
    } finally {
        in.close();
    }

    // Searching for templated config entry.
    // If we found one we get Java System properties
    // named as the macros. The config became activated if that
    // system proprty is set.

    Pattern macros = Pattern.compile("\\$\\{(.*?)\\}");
    boolean valid = true;

    Enumeration enumr = ht.keys();
    while (enumr.hasMoreElements()) {
        Object key = enumr.nextElement();
        if (ht.get(key) instanceof String) {
            String str = (String) ht.get(key);
            if (str != null) {
                Matcher matcher = macros.matcher(str);

                HashSet<String> propNames = new HashSet<String>();
                while (matcher.find()) {
                    propNames.add(matcher.group(1));
                }

                for (String prop : propNames) {
                    String sysProp = System.getProperty(prop);
                    if (sysProp == null) {
                        valid = false;
                    }
                    if (valid) {
                        str = StringUtils.replace(str, "${" + prop + "}", sysProp);
                        //str = str.replaceAll("\\$\\{"+prop+"\\}", sysProp);
                    }
                }
                if (valid) {
                    ht.put(key, str);
                }
            }
        }
    }

    if (valid) {
        Util.performSubstitution(p);
        String pid[] = parsePid(getName(f.getFile()));
        ht.put(CONFIGURATION_PROPERTY_NAME, getPidName(pid[0], pid[1]));

        Configuration config = getConfiguration(pid[0], pid[1]);

        /*
        // Backuping parameters for restore
        String persistanceName = pid[0]+(pid[1] == null ? "" : "-" + pid[1]);
        if (config.getProperties() != null && config.getProperties().get(CONFIGURATION_PROPERTY_NAME) == null) {
           if (persistence.load(persistanceName).isEmpty()) {
              persistence.store(persistanceName, config.getProperties());
           }
        }
         */
        if (config.getBundleLocation() != null) {
            config.setBundleLocation(null);
        }

        // If the configuration does not created by configuration loader we update it
        // In other cases (for example the user modified the loaded config) there is no configuration overwrite
        if (config.getProperties() == null || config.getProperties().get(CONFIGURATION_PROPERTY_NAME) == null
                || !config.getProperties().get(CONFIGURATION_PROPERTY_NAME).equals(getName(f.getFile()))) {
            config.update(ht);
        }
    }
    return true;
}

From source file:ch.entwine.weblounge.kernel.site.SiteDispatcherServiceImpl.java

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

    logger.debug("Configuring the site registration service");
    boolean configurationChanged = true;

    // Activate precompilation?
    String precompileSetting = StringUtils.trimToNull((String) config.get(OPT_PRECOMPILE));
    precompile = precompileSetting == null || ConfigurationUtils.isTrue(precompileSetting);
    logger.debug("Jsp precompilation {}", precompile ? "activated" : "deactivated");

    // Log compilation errors?
    String logPrecompileErrors = StringUtils.trimToNull((String) config.get(OPT_PRECOMPILE_LOGGING));
    logCompileErrors = logPrecompileErrors != null && ConfigurationUtils.isTrue(logPrecompileErrors);
    logger.debug("Precompilation errors will {} logged", logCompileErrors ? "be" : "not be");

    // Store the jasper configuration keys
    Enumeration<?> keys = config.keys();
    while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();
        if (key.startsWith(OPT_JASPER_PREFIX) && key.length() > OPT_JASPER_PREFIX.length()) {
            String value = (String) config.get(key);
            if (StringUtils.trimToNull(value) == null)
                continue;
            value = ConfigurationUtils.processTemplate(value);
            key = key.substring(OPT_JASPER_PREFIX.length());

            boolean optionChanged = value.equalsIgnoreCase(jasperConfig.get(key));
            configurationChanged |= !optionChanged;
            if (optionChanged)
                logger.debug("Jetty jsp parameter '{}' configured to '{}'", key, value);

            jasperConfig.put(key, value);
            // This is a work around for jasper's horrible implementation of the
            // compiler context configuration. Some keys are camel case, others are
            // lower case.
            jasperConfig.put(key.toLowerCase(), value);
        }
    }

    return configurationChanged;
}

From source file:org.ops4j.pax.web.extender.war.internal.WebXmlObserver.java

private void fireEvent(String topic, Bundle bundle, Dictionary<String, Object> failure) {
    if (eventAdminService != null) {
        Dictionary<String, Object> properties = new Hashtable<String, Object>();
        properties.put("bundle.symbolicName", bundle.getSymbolicName());
        properties.put("bundle.id", bundle.getBundleId());
        properties.put("bundle", bundle);
        properties.put("bundle.version", bundle.getHeaders().get(Constants.BUNDLE_VERSION));
        String webContextPath = (String) bundle.getHeaders().get("Web-ContextPath");
        if (webContextPath == null || webContextPath.length() == 0)
            webContextPath = (String) bundle.getHeaders().get("Webapp-Context"); //PAX fallback

        properties.put("context.path", webContextPath);
        properties.put("timestamp", System.currentTimeMillis());
        properties.put("extender.bundle", bundleContext.getBundle());
        properties.put("extender.bundle.id", bundleContext.getBundle().getBundleId());
        properties.put("extender.bundle.symbolicName", bundleContext.getBundle().getSymbolicName());
        properties.put("extender.bundle.version",
                bundleContext.getBundle().getHeaders().get(Constants.BUNDLE_VERSION));

        if (failure != null) {
            Enumeration<String> keys = failure.keys();
            while (keys.hasMoreElements()) {
                String key = keys.nextElement();
                properties.put(key, failure.get(key));
            }//from  www  .j  ava2  s  . c o m
        }

        Event event = new Event(topic, properties);
        this.eventAdminService.postEvent(event);
    }

    if (logService != null) {
        this.logService.log(LogService.LOG_DEBUG, topic);
    }
}

From source file:org.apache.geronimo.console.bundlemanager.BundleManagerPortlet.java

protected void doView(RenderRequest renderRequest, RenderResponse renderResponse)
        throws IOException, PortletException {

    if (WindowState.MINIMIZED.equals(renderRequest.getWindowState())) { // minimal view
        return;/*from w w w  .  j  a  v  a 2  s  .  c  om*/

    } else { // normal and maximal view

        String page = renderRequest.getParameter("page");

        if (FIND_PACKAGES_PAGE.equals(page)) {
            BundleContext bundleContext = getBundleContext(renderRequest);

            ServiceReference reference = bundleContext.getServiceReference(PackageAdmin.class.getName());
            PackageAdmin packageAdmin = (PackageAdmin) bundleContext.getService(reference);

            String packageString = renderRequest.getParameter("packageStringValue");

            Map<PackageInfo, List<BundleInfo>> packageExportBundles = new HashMap<PackageInfo, List<BundleInfo>>();
            Map<PackageInfo, List<BundleInfo>> packageImportBundles = new HashMap<PackageInfo, List<BundleInfo>>();

            for (Bundle bundle : bundleContext.getBundles()) {
                ExportedPackage[] exportedPackages = packageAdmin.getExportedPackages(bundle);
                if (exportedPackages != null) {

                    // construct the export bundle info
                    BundleInfo exportBundleInfo = new SimpleBundleInfo(bundle);

                    for (ExportedPackage exportedPackage : exportedPackages) {
                        // filter by keyword and ignore case. if the keyword is null, then return all the packages
                        if (packageString == null || exportedPackage.getName().toLowerCase()
                                .indexOf(packageString.trim().toLowerCase()) != -1) {
                            // construct the package info
                            // fill in its export bundle
                            PackageInfo packageInfo = new PackageInfo(exportedPackage.getName(),
                                    exportedPackage.getVersion().toString());
                            fillPackageBundlesMap(packageExportBundles, packageInfo, exportBundleInfo);

                            Bundle[] importingBundles = exportedPackage.getImportingBundles();
                            if (importingBundles != null) {
                                for (Bundle importingBundle : importingBundles) {

                                    // construct the import bundle info
                                    // fill in its import bundle
                                    BundleInfo importBundleInfo = new SimpleBundleInfo(importingBundle);
                                    fillPackageBundlesMap(packageImportBundles, packageInfo, importBundleInfo);

                                }

                            }
                        }
                    }
                }
            }

            List<PackageWiredBundles> packageWiredBundlesList = new ArrayList<PackageWiredBundles>();
            BundleSymbolicComparator bsc = new BundleSymbolicComparator();
            for (Entry<PackageInfo, List<BundleInfo>> entry : packageExportBundles.entrySet()) {
                PackageInfo pkg = entry.getKey();
                List<BundleInfo> exportBundles = entry.getValue();
                List<BundleInfo> importBundles = packageImportBundles.get(pkg) == null
                        ? new ArrayList<BundleInfo>()
                        : packageImportBundles.get(pkg);

                PackageWiredBundles pwb = new PackageWiredBundles(pkg, exportBundles, importBundles);
                pwb.sortBundleInfos(bsc);
                packageWiredBundlesList.add(pwb);
            }

            Collections.sort(packageWiredBundlesList);

            renderRequest.setAttribute("packageWiredBundlesList", packageWiredBundlesList);
            renderRequest.setAttribute("packageStringValue", packageString);
            findPackagesView.include(renderRequest, renderResponse);

        } else if (VIEW_MANIFEST_PAGE.equals(page)) {
            BundleContext bundleContext = getBundleContext(renderRequest);

            long id = Long.valueOf(renderRequest.getParameter("bundleId"));
            Bundle bundle = bundleContext.getBundle(id);

            List<ManifestHeader> manifestHeaders = new ArrayList<ManifestHeader>();
            Dictionary<String, String> headers = bundle.getHeaders();
            Enumeration<String> keys = headers.keys();
            while (keys.hasMoreElements()) {
                String key = (String) keys.nextElement();
                if (key.equals("Import-Package") || key.equals("Export-Package") || key.equals("Ignore-Package")
                        || key.equals("Private-Package") || key.equals("Export-Service")) {
                    manifestHeaders.add(new ManifestHeader(key,
                            ManifestHeader.formatPackageHeader((String) headers.get(key))));
                } else {
                    manifestHeaders.add(new ManifestHeader(key, (String) headers.get(key)));
                }
            }

            SimpleBundleInfo bundleInfo = new SimpleBundleInfo(bundle);

            Collections.sort(manifestHeaders);
            renderRequest.setAttribute("manifestHeaders", manifestHeaders);
            renderRequest.setAttribute("bundleInfo", bundleInfo);
            showManifestView.include(renderRequest, renderResponse);

        } else if (VIEW_SERVICES_PAGE.equals(page)) {

            BundleContext bundleContext = getBundleContext(renderRequest);

            long id = Long.valueOf(renderRequest.getParameter("bundleId"));
            Bundle bundle = bundleContext.getBundle(id);

            // because this page should not be very complex ,so we only have a Service Perspective
            // if user wants 2 perspective like wired bundle page, we can extend this page to add a new Bundle Perspective.
            List<ServicePerspective> usingServicePerspectives = getUsingServicePerspectives(bundle);
            List<ServicePerspective> registeredServicePerspectives = getRegisteredServicePerspectives(bundle);

            Collections.sort(usingServicePerspectives);
            Collections.sort(registeredServicePerspectives);

            renderRequest.setAttribute("usingServicePerspectives", usingServicePerspectives);
            renderRequest.setAttribute("registeredServicePerspectives", registeredServicePerspectives);

            SimpleBundleInfo bundleInfo = new SimpleBundleInfo(bundle);

            renderRequest.setAttribute("bundleInfo", bundleInfo);

            showServicesView.include(renderRequest, renderResponse);

        } else if (VIEW_WIRED_BUNDLES_PAGE.equals(page)) {

            BundleContext bundleContext = getBundleContext(renderRequest);

            long id = Long.valueOf(renderRequest.getParameter("bundleId"));
            Bundle bundle = bundleContext.getBundle(id);

            String perspectiveType = renderRequest.getParameter("perspectiveTypeValue");
            if (perspectiveType == null || perspectiveType == "")
                perspectiveType = "bundle"; //when we access this page with a renderURL, we need the default value

            ServiceReference reference = bundleContext.getServiceReference(PackageAdmin.class.getName());
            PackageAdmin packageAdmin = (PackageAdmin) bundle.getBundleContext().getService(reference);

            Set<String> wiredPackages = new HashSet<String>();
            Set<PackageBundlePair> importingPairs = getImportingPairs(packageAdmin, bundle, wiredPackages);
            Set<PackageBundlePair> dynamicImportingPairs = getDynamicImportingPairs(packageAdmin, bundle,
                    wiredPackages);
            Set<PackageBundlePair> requireBundlesImportingPairs = getRequireBundlesImportingPairs(packageAdmin,
                    bundle);
            Set<PackageBundlePair> exportingPairs = getExportingPairs(packageAdmin, bundle);

            if ("package".equals(perspectiveType)) {
                List<PackagePerspective> importingPackagePerspectives = getPackagePerspectives(importingPairs);
                List<PackagePerspective> dynamicImportingPackagePerspectives = getPackagePerspectives(
                        dynamicImportingPairs);
                List<PackagePerspective> requireBundlesImportingPackagePerspectives = getPackagePerspectives(
                        requireBundlesImportingPairs);
                List<PackagePerspective> exportingPackagePerspectives = getPackagePerspectives(exportingPairs);

                Collections.sort(importingPackagePerspectives);
                Collections.sort(dynamicImportingPackagePerspectives);
                Collections.sort(requireBundlesImportingPackagePerspectives);
                Collections.sort(exportingPackagePerspectives);

                renderRequest.setAttribute("importingPackagePerspectives", importingPackagePerspectives);
                renderRequest.setAttribute("dynamicImportingPackagePerspectives",
                        dynamicImportingPackagePerspectives);
                renderRequest.setAttribute("requireBundlesImportingPackagePerspectives",
                        requireBundlesImportingPackagePerspectives);
                renderRequest.setAttribute("exportingPackagePerspectives", exportingPackagePerspectives);

            } else { //"bundle".equals(perspectiveType)){
                List<BundlePerspective> importingBundlePerspectives = getBundlePerspectives(importingPairs);
                List<BundlePerspective> dynamicImportingBundlePerspectives = getBundlePerspectives(
                        dynamicImportingPairs);
                List<BundlePerspective> requireBundlesImportingBundlePerspectives = getBundlePerspectives(
                        requireBundlesImportingPairs);
                List<BundlePerspective> exportingBundlePerspectives = getBundlePerspectives(exportingPairs);

                Collections.sort(importingBundlePerspectives);
                Collections.sort(dynamicImportingBundlePerspectives);
                Collections.sort(requireBundlesImportingBundlePerspectives);
                Collections.sort(exportingBundlePerspectives);

                renderRequest.setAttribute("importingBundlePerspectives", importingBundlePerspectives);
                renderRequest.setAttribute("dynamicImportingBundlePerspectives",
                        dynamicImportingBundlePerspectives);
                renderRequest.setAttribute("requireBundlesImportingBundlePerspectives",
                        requireBundlesImportingBundlePerspectives);
                renderRequest.setAttribute("exportingBundlePerspectives", exportingBundlePerspectives);
            }

            SimpleBundleInfo bundleInfo = new SimpleBundleInfo(bundle);

            renderRequest.setAttribute("bundleInfo", bundleInfo);
            renderRequest.setAttribute("perspectiveTypeValue", perspectiveType);

            showWiredBundlesView.include(renderRequest, renderResponse);

        } else { // main page

            String listType = renderRequest.getParameter("listTypeValue");
            if (listType == null || listType == "")
                listType = "all"; //when we access this page with a renderURL, we need the default value
            String searchString = renderRequest.getParameter("searchStringValue");
            if (searchString == null)
                searchString = ""; //when we access this page with a renderURL, we need the default value

            BundleContext bundleContext = getBundleContext(renderRequest);

            // retrieve bundle infos
            List<ExtendedBundleInfo> bundleInfos = new ArrayList<ExtendedBundleInfo>();

            // get the StartLeval object
            ServiceReference startLevelRef = bundleContext
                    .getServiceReference(StartLevel.class.getCanonicalName());
            StartLevel startLevelService = (StartLevel) bundleContext.getService(startLevelRef);

            // get configured bundle Ids
            Set<Long> configurationBundleIds = getConfigurationBundleIds();

            Bundle[] bundles = bundleContext.getBundles();
            for (Bundle bundle : bundles) {

                if (searchString != "" && !matchBundle(bundle, searchString)) {
                    continue;
                }

                // construct the result bundleInfos by listType
                if ("wab".equals(listType)) {
                    if (checkWABBundle(bundle)) {
                        ExtendedBundleInfo info = createExtendedBundleInfo(bundle, startLevelService,
                                configurationBundleIds);
                        info.addContextPath(getContextPath(bundle));
                        bundleInfos.add(info);
                    }
                } else if ("blueprint".equals(listType)) {
                    if (checkBlueprintBundle(bundle)) {
                        ExtendedBundleInfo info = createExtendedBundleInfo(bundle, startLevelService,
                                configurationBundleIds);

                        // currently, we try get the the blueprintContainer service to determine if a blueprint bundle is created
                        // TODO A better way is using a BlueprintListener to track all blueprint bundle events
                        String filter = "(&(osgi.blueprint.container.symbolicname=" + bundle.getSymbolicName()
                                + ")(osgi.blueprint.container.version=" + bundle.getVersion() + "))";
                        ServiceReference[] serviceReferences = null;
                        try {
                            serviceReferences = bundleContext
                                    .getServiceReferences(BlueprintContainer.class.getName(), filter);
                        } catch (InvalidSyntaxException e) {
                            throw new RuntimeException(e);
                        }
                        if (serviceReferences != null && serviceReferences.length > 0) {
                            info.setBlueprintState(BlueprintState.CREATED);
                        }

                        bundleInfos.add(info);
                    }
                } else if ("system".equals(listType)) {
                    if (checkSysBundle(bundle, startLevelService)) {
                        ExtendedBundleInfo info = createExtendedBundleInfo(bundle, startLevelService,
                                configurationBundleIds);
                        bundleInfos.add(info);
                    }
                } else if ("configuration".equals(listType)) {
                    if (checkConfigurationBundle(bundle, configurationBundleIds)) {
                        ExtendedBundleInfo info = createExtendedBundleInfo(bundle, startLevelService,
                                configurationBundleIds);
                        bundleInfos.add(info);
                    }
                } else {
                    ExtendedBundleInfo info = createExtendedBundleInfo(bundle, startLevelService,
                            configurationBundleIds);
                    bundleInfos.add(info);
                }
            }

            Collections.sort(bundleInfos, new BundleIdDescComparator());
            renderRequest.setAttribute("extendedBundleInfos", bundleInfos);

            // set the values to render attribute
            renderRequest.setAttribute("listTypeValue", listType);
            renderRequest.setAttribute("searchStringValue", searchString);

            renderRequest.setAttribute("initStartLevel", startLevelService.getInitialBundleStartLevel());

            if (bundleInfos.size() == 0) {
                addWarningMessage(renderRequest,
                        getLocalizedString(renderRequest, "consolebase.bundlemanager.warn.nobundlesfound"));
            }

            bundleManagerView.include(renderRequest, renderResponse);

        }
    }
}

From source file:org.opencastproject.kernel.security.OrganizationDirectoryServiceImpl.java

@Override
@SuppressWarnings("rawtypes")
public void updated(String pid, Dictionary properties) throws ConfigurationException {
    if (persistence == null) {
        logger.debug("No persistence available: Ignoring organization update for pid='{}'", pid);
        unhandledOrganizations.put(pid, properties);
        return;/*  w w w .j a  v a 2  s  .  c  o  m*/
    }
    logger.debug("Updating organization pid='{}'", pid);

    // Gather the properties
    final String id = (String) properties.get(ORG_ID_KEY);
    final String name = (String) properties.get(ORG_NAME_KEY);
    final String server = (String) properties.get(ORG_SERVER_KEY);

    // Make sure the configuration meets the minimum requirements
    if (StringUtils.isBlank(id))
        throw new ConfigurationException(ORG_ID_KEY, ORG_ID_KEY + " must be set");
    if (StringUtils.isBlank(server))
        throw new ConfigurationException(ORG_SERVER_KEY, ORG_SERVER_KEY + " must be set");

    final String portAsString = StringUtils.trimToNull((String) properties.get(ORG_PORT_KEY));
    final int port = portAsString != null ? Integer.parseInt(portAsString) : 80;
    final String adminRole = (String) properties.get(ORG_ADMIN_ROLE_KEY);
    final String anonRole = (String) properties.get(ORG_ANONYMOUS_ROLE_KEY);

    // Build the properties map
    final Map<String, String> orgProperties = new HashMap<String, String>();
    for (Enumeration<?> e = properties.keys(); e.hasMoreElements();) {
        final String key = (String) e.nextElement();
        if (!key.startsWith(ORG_PROPERTY_PREFIX)) {
            continue;
        }
        orgProperties.put(key.substring(ORG_PROPERTY_PREFIX.length()), (String) properties.get(key));
    }

    // Load the existing organization or create a new one
    try {
        JpaOrganization org;
        try {
            org = (JpaOrganization) persistence.getOrganization(id);
            org.setName(name);
            org.addServer(server, port);
            org.setAdminRole(adminRole);
            org.setAnonymousRole(anonRole);
            org.setProperties(orgProperties);
            logger.info("Registering organization '{}'", id);
        } catch (NotFoundException e) {
            org = new JpaOrganization(id, name, server, port, adminRole, anonRole, orgProperties);
            logger.info("Updating organization '{}'", id);
        }
        persistence.storeOrganization(org);
        cache.invalidate();
    } catch (OrganizationDatabaseException e) {
        logger.error("Unable to register organization '{}': {}", id, e);
    }
}

From source file:org.openhab.binding.obd.internal.OBDBinding.java

/**
 * @{inheritDoc//from w  w w  . j ava2 s  .  c om
 */
@Override
public synchronized void updated(Dictionary config) throws ConfigurationException {

    logger.trace("OBD Updated");
    if (config != null) {
        logger.trace("OBD Configuration not null");
        if (config != null) {
            String deviceString = (String) config.get("device");
            if (StringUtils.isNotBlank(deviceString)) {
                device = deviceString;
                logger.trace("device setting is {} ", device);
            }

            String speedString = (String) config.get("speed");
            if (StringUtils.isNotBlank(speedString)) {
                speed = Integer.parseInt(speedString);
                logger.trace("speed setting is{} ", speed);
            }

            String readDelay = (String) config.get("delay");
            if (StringUtils.isNotBlank(readDelay)) {
                delay = Integer.parseInt(readDelay);
                logger.trace("comm delay setting is {} ", delay);
            }

            //setProperlyConfigured(true);

        }

        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.trace("Using serial device {}", device.toString());
                }
            } else if ("speed".equals(key)) {
                speed = Integer.parseInt(value);
                logger.trace("Speed  set to {}", speed);
            } else if ("refresh".equals(key)) {
                refresh = Integer.parseInt(value);
                logger.trace("Refresh  set to {}", refresh);
            } else if ("retry".equals(key)) {
                retry = Integer.parseInt(value);
                logger.trace("Retry set to {}", retry);
            } else if ("delay".equals(key)) {
                delay = Integer.parseInt(value);
                logger.trace("Delay set to {}", retry);
            } else {

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

        }

        if (parsingRules != null) {
            logger.trace("OBD Data Parser called");
            dataParser = new OBDDataParser(parsingRules);
        }

        if (messageListener != null) {

            logger.trace("Close previous message listener");

            messageListener.setInterrupted(true);
            try {
                messageListener.join();
            } catch (InterruptedException e) {
                logger.info("Previous message listener closing interrupted", e);
            }
        }

        if (!running) {
            messageListener = new MessageListener(this);
            messageListener.start();
        }
    }
}

From source file:org.apache.felix.webconsole.internal.compendium.ConfigManager.java

private void configForm(JSONWriter jsonWriter, String inputPid, Configuration config, String pidFilter,
        String locale) throws JSONException {

    jsonWriter.key(ConfigManager.SERVICE_PID);
    jsonWriter.value(inputPid);/*from   w  ww  . j  a  v  a 2  s.c o  m*/

    if (pidFilter != null) {
        jsonWriter.key(PID_FILTER);
        jsonWriter.value(pidFilter);
    }

    Dictionary propsDictionary = null;
    ObjectClassDefinition classDef;
    if (config != null) {
        propsDictionary = config.getProperties();
        classDef = this.getObjectClassDefinition(config, locale);
    } else {
        classDef = this.getObjectClassDefinition(inputPid, locale);
    }

    propsDictionary = this.mergeWithMetaType(propsDictionary, classDef, jsonWriter);

    if (propsDictionary != null) {

        jsonWriter.key("title");
        jsonWriter.value(inputPid);
        jsonWriter.key("description");
        jsonWriter.value(
                "Please enter configuration properties for this configuration in the field below. This configuration has no associated description");

        jsonWriter.key("propertylist");
        jsonWriter.value("properties");

        jsonWriter.key("properties");
        jsonWriter.object();
        for (Enumeration propEnum = propsDictionary.keys(); propEnum.hasMoreElements();) {
            Object nextElement = propEnum.nextElement();

            // ignore well known special properties
            if (!nextElement.equals(Constants.SERVICE_PID) && !nextElement.equals(Constants.SERVICE_DESCRIPTION)
                    && !nextElement.equals(Constants.SERVICE_ID)
                    && !nextElement.equals(Constants.SERVICE_RANKING)
                    && !nextElement.equals(ConfigurationAdmin.SERVICE_FACTORYPID)
                    && !nextElement.equals(Constants.SERVICE_VENDOR)
                    && !nextElement.equals(ConfigurationAdmin.SERVICE_BUNDLELOCATION)) {
                jsonWriter.key(String.valueOf(nextElement));
                jsonWriter.value(propsDictionary.get(nextElement));
            }
        }
        jsonWriter.endObject();

    }

    if (config != null) {
        this.addConfigurationInfo(config, jsonWriter, locale);
    }
}

From source file:org.openhab.binding.smarthomatic.internal.SmarthomaticBinding.java

/**
 * @{inheritDoc//from   ww w. ja  v  a2s  .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);
        }

        boolean changed = false;

        if (serialPortname != (String) config.get("serialPort")) {
            serialPortname = (String) config.get("serialPort");
            changed = true;
        }
        String dummy = (String) config.get("baud");
        try {
            if (serialBaudrate != Integer.parseInt(dummy)) {
                serialBaudrate = Integer.parseInt(dummy);
                changed = true;
            }
        } catch (NumberFormatException e) {
            logger.info("reading exception");
        }

        if (changed | (baseStation == null)) {
            if (baseStation != null) {
                baseStation.closeSerialPort();
            }

            baseStation = new BaseStation(serialPortname, serialBaudrate, this);
            logger.debug("Smarthomatic Binding:update creates new basestation");
        }

        Enumeration<String> keys = config.keys();
        for (int i = 0; i < config.size(); i++) {
            String key = keys.nextElement();
            StringTokenizer tokens = new StringTokenizer(key, ":");

            if (tokens.nextToken().equals("device")) {
                if (tokens.hasMoreElements()) {
                    dummy = tokens.nextToken();
                    int deviceID = Integer.parseInt(dummy);
                    String name = (String) config.get(key);
                    SmarthomaticGenericBindingProvider.addDevice(name, deviceID);
                    logger.debug("Smarthomatic device {} can be indexed by name {}",
                            new String[] { dummy, name });
                }
            }
            logger.debug("KEY: {}", key);
        }

        setProperlyConfigured(true);
    }
}

From source file:org.energy_home.jemma.ah.internal.hac.lib.HacService.java

/**
 * Checks and adds or updates some properties contained in
 * the configuration. The props dictionary is changed.
 * /*from w ww .  j ava2 s.  c om*/
 * @param c
 *            The Configuration Admin configuration.
 * @param props
 *            The new property set
 * @param name
 *            The name of the property of c that must not be overridden.
 * @throws HacException
 */

private void checkAndUpdateProperties(IManagedAppliance managedAppliance, Configuration c, Dictionary props)
        throws HacException {
    // don't override the appliance type property. Fatal error if
    // this property is not set for the appliance
    Dictionary oldProps = c.getProperties();
    String applianceType = (String) oldProps.get(IAppliance.APPLIANCE_TYPE_PROPERTY);
    if (applianceType == null) {
        // FIXME: nella configurazione NON compare mai la ah.app.type
        // property!!!!! Perche?
        LOG.warn(IAppliance.APPLIANCE_TYPE_PROPERTY + " property not found in record");
    }

    // Restore some key properties: it seems it does not associate to new service registration properties 
    // that are not included in last change to configuration (it also avoid to have some properties
    // can contains invalid values)
    props.put(IAppliance.APPLIANCE_TYPE_PROPERTY, managedAppliance.getDescriptor().getType());
    props.put(IAppliance.APPLIANCE_PID, managedAppliance.getPid());
    props.put(IAppliance.APPLIANCE_EPS_IDS_PROPERTY, managedAppliance.getEndPointIds());
    props.put(IAppliance.APPLIANCE_EPS_TYPES_PROPERTY, managedAppliance.getEndPointTypes());
    props.put(IAppliance.APPLIANCE_EPS_IDS_PROPERTY, managedAppliance.getEndPointIds());
    props.put(IAppliance.APPLIANCE_EPS_TYPES_PROPERTY, managedAppliance.getEndPointTypes());
    Dictionary customConfig = managedAppliance.getCustomConfiguration();
    if (customConfig != null) {
        for (Enumeration e = customConfig.keys(); e.hasMoreElements();) {
            String key = (String) e.nextElement();
            // Custom properties that are invalid are filtered
            if (key.startsWith(IAppliance.APPLIANCE_CUSTOM_PROPERTIES_PREXIF))
                ;
            props.put(key, customConfig.get(key));
        }
    }
    //TODO: check merge, 5 lines below were missing in 3.3.0
    // For compatibility with old applications (i.e. green@home), appliance common property is always managed
    manageMultiEndPointConfiguration(props, oldProps, IAppliance.APPLIANCE_NAME_PROPERTY,
            IAppliance.END_POINT_NAMES_PROPERTY);
    manageMultiEndPointConfiguration(props, oldProps, IAppliance.APPLIANCE_CATEGORY_PID_PROPERTY,
            IAppliance.END_POINT_CATEGORY_PIDS_PROPERTY);
    manageMultiEndPointConfiguration(props, oldProps, IAppliance.APPLIANCE_LOCATION_PID_PROPERTY,
            IAppliance.END_POINT_LOCATION_PIDS_PROPERTY);
    manageMultiEndPointConfiguration(props, oldProps, IAppliance.APPLIANCE_ICON_PROPERTY,
            IAppliance.END_POINT_LOCATION_PIDS_PROPERTY);

}