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:com.alexkli.osgi.troubleshoot.impl.TroubleshootServlet.java

private void handleBundles(HttpServletRequest request, HttpServletResponse response, Bundle[] bundles)
        throws IOException {
    PrintWriter out = response.getWriter();

    out.println("<h2>Bundles</h2>");

    out.println("<p class='statline ui-state-highlight'>");
    out.println(getBundleStatusLine(bundles));
    out.println("</p>");

    final List<Bundle> problematicBundles = getProblematicBundles(bundles);

    if (problematicBundles.isEmpty()) {
        out.println("<div class='all-ok'>All bundles ok.</div>");
        return;//from   w ww  .  ja  va  2  s.c  om
    }

    // button + dialog for starting all bundles
    out.println("<form class='startInactiveBundles' method='post' target='actionLog'>");
    out.println("    <input type='hidden' name='action' value='startInactiveBundles' />");
    out.println("    <button type='submit'>Start inactive bundles</button>");
    out.println("</form>");
    out.println("<div id='actionLogDialog' style='display:none'>");
    out.println(
            "   <iframe id='actionLog' name='actionLog' width='100%' height='100%' frameborder='0' marginwidth='0' marginheight='0'></iframe>");
    out.println("</div>");

    out.println("<div>");

    final String bundlesUrl = request.getAttribute(WebConsoleConstants.ATTR_APP_ROOT) + "/bundles";

    for (Bundle bundle : problematicBundles) {
        out.println(getDetailLink(bundle, bundlesUrl));
        out.println(" ");
        out.println(getStatusString(bundle));
        out.println("<br>");

        if (bundle.getState() == Bundle.STOPPING || bundle.getState() == Bundle.STARTING) {
            out.print("<span class='hint'>If the bundle is ");
            out.print(bundle.getState() == Bundle.STOPPING ? "stopping" : "starting");
            out.println(" forever, there might be a deadlock."
                    + " Check the <a href='status-jstack-threaddump'>thread dumps</a>.</span><br/>");
        }

        ExportedPackage[] allExports = packageAdmin.getExportedPackages((Bundle) null);
        // multimap - same package can be exported in multiple versions
        Map<String, List<ExportedPackage>> globalExportMap = new HashMap<String, List<ExportedPackage>>();
        for (int j = 0; j < allExports.length; j++) {
            ExportedPackage exportedPackage = allExports[j];
            List<ExportedPackage> values = globalExportMap.get(exportedPackage.getName());
            if (values == null) {
                values = new ArrayList<ExportedPackage>();
                globalExportMap.put(exportedPackage.getName(), values);
            }
            values.add(exportedPackage);
        }

        Dictionary dict = bundle.getHeaders();

        // go through imports
        // - other bundle might not be resolved
        // - something else exports it, but in another (older) version
        // - nothing exports it

        String importHeader = (String) dict.get(Constants.IMPORT_PACKAGE);
        Clause[] imports = Parser.parseHeader(importHeader);
        if (imports != null) {

            for (Clause importPkg : imports) {
                if (isOptional(importPkg)) {
                    continue;
                }
                if (isOwnPackage(bundle, importPkg.getName())) {
                    continue;
                }

                String name = importPkg.getName();
                List<ExportedPackage> matchingExports = globalExportMap.get(name);
                if (matchingExports != null) {
                    boolean satisfied = false;
                    for (ExportedPackage exported : matchingExports) {
                        if (isSatisfied(importPkg, exported)) {
                            satisfied = true;

                            Bundle exportingBundle = exported.getExportingBundle();
                            if (isInactive(exportingBundle)) {
                                // not an actual issue, just a chain of dependencies not resolving
                                out.print("- dependency not active: ");
                                out.print(getDetailLink(exportingBundle, bundlesUrl));
                                out.print(" ");
                                out.println(getStatusString(exportingBundle));
                                out.print(" (importing ");
                                out.print(name);
                                out.print(")");
                                out.println("<br>");
                            }
                            break;
                        }
                    }
                    if (!satisfied) {
                        // here we have export candidates, but in a different version
                        out.print("<span class='ui-state-error-text'>");

                        String prefix = "";
                        if (matchingExports.size() > 1) {
                            prefix = "candidate ";
                        }
                        // common case
                        if (matchingExports.size() == 1) {
                            for (ExportedPackage export : matchingExports) {
                                Version exportVersion = export.getVersion();
                                String versionAttr = importPkg.getAttribute(Constants.VERSION_ATTRIBUTE);
                                VersionRange importRange = new VersionRange(versionAttr);

                                out.print("- ");
                                out.print(prefix);
                                if ((importRange.getLeftType() == VersionRange.LEFT_CLOSED
                                        && exportVersion.compareTo(importRange.getLeft()) < 0)
                                        || (importRange.getLeftType() == VersionRange.LEFT_OPEN
                                                && exportVersion.compareTo(importRange.getLeft()) <= 0)) {
                                    out.print("dependency too old: ");
                                } else if ((importRange.getRightType() == VersionRange.RIGHT_CLOSED
                                        && exportVersion.compareTo(importRange.getRight()) > 0)
                                        || (importRange.getRightType() == VersionRange.RIGHT_OPEN
                                                && exportVersion.compareTo(importRange.getRight()) >= 0)) {
                                    out.print("dependency too new: ");
                                } else {
                                    out.print("dependency with different version: ");
                                }

                                out.print(getDetailLink(export.getExportingBundle(), bundlesUrl));
                                out.print(" (importing ");
                                out.print(name);
                                out.print(" ");
                                out.print(versionAttr);
                                out.print(" but found ");
                                out.print(exportVersion.toString());
                                out.print(")");
                            }
                        }
                        out.print("</span>");
                        out.println("<br>");
                    }
                } else {
                    // not found at all, bundle missing
                    out.print("<span class='ui-state-error-text'>");
                    out.print("- not exported by any bundle: ");
                    out.println(name);
                    out.print("</span>");
                    out.println("<br>");
                }
            }
        }
        out.println("<br>");
    }
    out.println("</div>");
}

From source file:org.openhab.binding.modbus.internal.ModbusBinding.java

@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    // remove all known items if configuration changed
    modbusSlaves.clear();//from   w w  w .j ava  2 s.co  m
    if (config != null) {
        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;
            }

            Matcher matcher = EXTRACT_MODBUS_CONFIG_PATTERN.matcher(key);
            if (!matcher.matches()) {
                if ("poll".equals(key)) {
                    if (StringUtils.isNotBlank((String) config.get(key))) {
                        pollInterval = Integer.valueOf((String) config.get(key));
                    }
                } else if ("writemultipleregisters".equals(key)) {
                    ModbusSlave.setWriteMultipleRegisters(Boolean.valueOf(config.get(key).toString()));
                } else {
                    logger.debug(
                            "given modbus-slave-config-key '{}' does not follow the expected pattern or 'serial.<slaveId>.<{}>'",
                            key, VALID_COFIG_KEYS);
                }
                continue;
            }

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

            String slave = matcher.group(2);

            ModbusSlave modbusSlave = modbusSlaves.get(slave);
            if (modbusSlave == null) {
                if (matcher.group(1).equals(TCP_PREFIX)) {
                    modbusSlave = new ModbusTcpSlave(slave);
                } else if (matcher.group(1).equals(UDP_PREFIX)) {
                    modbusSlave = new ModbusUdpSlave(slave);
                } else if (matcher.group(1).equals(SERIAL_PREFIX)) {
                    modbusSlave = new ModbusSerialSlave(slave);
                } else {
                    throw new ConfigurationException(slave, "the given slave type '" + slave + "' is unknown");
                }
                logger.debug("modbusSlave '{}' instanciated", slave);
                modbusSlaves.put(slave, modbusSlave);
            }

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

            if ("connection".equals(configKey)) {
                String[] chunks = value.split(":");
                if (modbusSlave instanceof ModbusIPSlave) {
                    // expecting: 
                    //      <devicePort>:<port>
                    ((ModbusIPSlave) modbusSlave).setHost(chunks[0]);
                    if (chunks.length == 2) {
                        ((ModbusIPSlave) modbusSlave).setPort(Integer.valueOf(chunks[1]));
                    }
                } else if (modbusSlave instanceof ModbusSerialSlave) {
                    // expecting: 
                    //      <devicePort>[:<baudRate>:<dataBits>:<parity>:<stopBits>:<encoding>]
                    ((ModbusSerialSlave) modbusSlave).setPort(chunks[0]);
                    if (chunks.length >= 2) {
                        ((ModbusSerialSlave) modbusSlave).setBaud(Integer.valueOf(chunks[1]));
                    }
                    if (chunks.length >= 3) {
                        ((ModbusSerialSlave) modbusSlave).setDatabits(Integer.valueOf(chunks[2]));
                    }
                    if (chunks.length >= 4) {
                        ((ModbusSerialSlave) modbusSlave).setParity(chunks[3]);
                    }
                    if (chunks.length >= 5) {
                        ((ModbusSerialSlave) modbusSlave).setStopbits(Double.valueOf(chunks[4]));
                    }
                    if (chunks.length == 6) {
                        ((ModbusSerialSlave) modbusSlave).setEncoding(chunks[5]);
                    }
                }
            } else if ("start".equals(configKey)) {
                modbusSlave.setStart(Integer.valueOf(value));
            } else if ("length".equals(configKey)) {
                modbusSlave.setLength(Integer.valueOf(value));
            } else if ("id".equals(configKey)) {
                modbusSlave.setId(Integer.valueOf(value));
            } else if ("type".equals(configKey)) {
                if (ArrayUtils.contains(ModbusBindingProvider.SLAVE_DATA_TYPES, value)) {
                    modbusSlave.setType(value);
                } else {
                    throw new ConfigurationException(configKey,
                            "the given slave type '" + value + "' is invalid");
                }
            } else if ("valuetype".equals(configKey)) {
                if (ArrayUtils.contains(ModbusBindingProvider.VALUE_TYPES, value)) {
                    modbusSlave.setValueType(value);
                } else {
                    throw new ConfigurationException(configKey,
                            "the given value type '" + value + "' is invalid");
                }
            } else if ("rawdatamultiplier".equals(configKey)) {
                modbusSlave.setRawDataMultiplier(Double.valueOf(value.toString()));
            } else {
                throw new ConfigurationException(configKey,
                        "the given configKey '" + configKey + "' is unknown");
            }
        }

        logger.debug("config looked good, proceeding with slave-connections");
        // connect instances to modbus slaves
        for (ModbusSlave slave : modbusSlaves.values()) {
            slave.connect();
        }

        setProperlyConfigured(true);
    }
}

From source file:org.openhab.persistence.sql.internal.SqlPersistenceService.java

/**
 * @{inheritDoc//ww  w  .  jav  a 2s  .c om
 */
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    if (config != null) {
        Enumeration<String> keys = config.keys();

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

            Matcher matcher = EXTRACT_CONFIG_PATTERN.matcher(key);

            if (!matcher.matches()) {
                continue;
            }

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

            if (!matcher.group(1).equals("sqltype"))
                continue;

            String itemType = matcher.group(2).toUpperCase() + "ITEM";
            String value = (String) config.get(key);

            sqlTypes.put(itemType, value);
        }

        driverClass = (String) config.get("driverClass");
        if (StringUtils.isBlank(driverClass)) {
            throw new ConfigurationException("sql:driverClass",
                    "The SQL driver class is missing - please configure the sql:driverClass parameter in openhab.cfg");
        }

        url = (String) config.get("url");
        if (StringUtils.isBlank(url)) {
            throw new ConfigurationException("sql:url",
                    "The SQL database URL is missing - please configure the sql:url parameter in openhab.cfg");
        }

        user = (String) config.get("user");
        if (StringUtils.isBlank(user)) {
            throw new ConfigurationException("sql:user",
                    "The SQL user is missing - please configure the sql:user parameter in openhab.cfg");
        }

        password = (String) config.get("password");
        if (StringUtils.isBlank(password)) {
            throw new ConfigurationException("sql:password",
                    "The SQL password is missing. Attempting to connect without password. To specify a password configure the sql:password parameter in openhab.cfg.");
        }

        String errorThresholdString = (String) config.get("reconnectCnt");
        if (StringUtils.isNotBlank(errorThresholdString)) {
            errReconnectThreshold = Integer.parseInt(errorThresholdString);
        }

        disconnectFromDatabase();
        connectToDatabase();

        // connection has been established ... initialization completed!
        initialized = true;
    }

}

From source file:org.apache.sling.models.impl.ModelAdapterFactory.java

@Activate
protected void activate(final ComponentContext ctx) {
    Dictionary<?, ?> props = ctx.getProperties();
    final int maxRecursionDepth = PropertiesUtil.toInteger(props.get(PROP_MAX_RECURSION_DEPTH),
            DEFAULT_MAX_RECURSION_DEPTH);
    this.invocationCountThreadLocal = new ThreadLocal<ThreadInvocationCounter>() {
        @Override/*  w w  w.  ja  va 2s. c om*/
        protected ThreadInvocationCounter initialValue() {
            return new ThreadInvocationCounter(maxRecursionDepth);
        }
    };

    BundleContext bundleContext = ctx.getBundleContext();
    this.queue = new ReferenceQueue<Object>();
    this.disposalCallbacks = new ConcurrentHashMap<java.lang.ref.Reference<Object>, DisposalCallbackRegistryImpl>();
    Hashtable<Object, Object> properties = new Hashtable<Object, Object>();
    properties.put(Constants.SERVICE_VENDOR, "Apache Software Foundation");
    properties.put(Constants.SERVICE_DESCRIPTION, "Sling Models OSGi Service Disposal Job");
    properties.put("scheduler.concurrent", false);
    properties.put("scheduler.period", 30L);

    this.jobRegistration = bundleContext.registerService(Runnable.class.getName(), this, properties);

    this.listener = new ModelPackageBundleListener(ctx.getBundleContext(), this, this.adapterImplementations);

    Hashtable<Object, Object> printerProps = new Hashtable<Object, Object>();
    printerProps.put(Constants.SERVICE_VENDOR, "Apache Software Foundation");
    printerProps.put(Constants.SERVICE_DESCRIPTION, "Sling Models Configuration Printer");
    printerProps.put("felix.webconsole.label", "slingmodels");
    printerProps.put("felix.webconsole.title", "Sling Models");
    printerProps.put("felix.webconsole.configprinter.modes", "always");

    this.configPrinterRegistration = bundleContext.registerService(Object.class.getName(),
            new ModelConfigurationPrinter(this), printerProps);
}

From source file:com.adobe.acs.commons.errorpagehandler.impl.ErrorPageHandlerImpl.java

@SuppressWarnings("squid:S1149")
private void configure(ComponentContext componentContext) {
    Dictionary<?, ?> config = componentContext.getProperties();
    final String legacyPrefix = "prop.";

    this.enabled = PropertiesUtil.toBoolean(config.get(PROP_ENABLED),
            PropertiesUtil.toBoolean(config.get(legacyPrefix + PROP_ENABLED), DEFAULT_ENABLED));

    this.vanityDispatchCheckEnabled = PropertiesUtil.toBoolean(config.get(PROP_VANITY_DISPATCH_ENABLED),
            PropertiesUtil.toBoolean(config.get(legacyPrefix + PROP_VANITY_DISPATCH_ENABLED),
                    DEFAULT_VANITY_DISPATCH_ENABLED));

    /** Error Pages **/

    this.systemErrorPagePath = PropertiesUtil.toString(config.get(PROP_ERROR_PAGE_PATH), PropertiesUtil
            .toString(config.get(legacyPrefix + PROP_ERROR_PAGE_PATH), DEFAULT_SYSTEM_ERROR_PAGE_PATH_DEFAULT));

    this.errorPageExtension = PropertiesUtil.toString(config.get(PROP_ERROR_PAGE_EXTENSION), PropertiesUtil
            .toString(config.get(legacyPrefix + PROP_ERROR_PAGE_EXTENSION), DEFAULT_ERROR_PAGE_EXTENSION));

    this.fallbackErrorName = PropertiesUtil.toString(config.get(PROP_FALLBACK_ERROR_NAME), PropertiesUtil
            .toString(config.get(legacyPrefix + PROP_FALLBACK_ERROR_NAME), DEFAULT_FALLBACK_ERROR_NAME));

    this.pathMap = configurePathMap(PropertiesUtil.toStringArray(config.get(PROP_SEARCH_PATHS),
            PropertiesUtil.toStringArray(config.get(legacyPrefix + PROP_SEARCH_PATHS), DEFAULT_SEARCH_PATHS)));

    /** Not Found Handling **/
    this.notFoundBehavior = PropertiesUtil.toString(config.get(PROP_NOT_FOUND_DEFAULT_BEHAVIOR),
            DEFAULT_NOT_FOUND_DEFAULT_BEHAVIOR);

    String[] tmpNotFoundExclusionPatterns = PropertiesUtil.toStringArray(
            config.get(PROP_NOT_FOUND_EXCLUSION_PATH_PATTERNS), DEFAULT_NOT_FOUND_EXCLUSION_PATH_PATTERNS);

    this.notFoundExclusionPatterns = new ArrayList<Pattern>();
    for (final String tmpPattern : tmpNotFoundExclusionPatterns) {
        this.notFoundExclusionPatterns.add(Pattern.compile(tmpPattern));
    }//w  w  w  .ja  va 2  s. c  om

    /** Error Page Cache **/

    int ttl = PropertiesUtil.toInteger(config.get(PROP_TTL),
            PropertiesUtil.toInteger(LEGACY_PROP_TTL, DEFAULT_TTL));

    boolean serveAuthenticatedFromCache = PropertiesUtil
            .toBoolean(config.get(PROP_SERVE_AUTHENTICATED_FROM_CACHE), PropertiesUtil.toBoolean(
                    LEGACY_PROP_SERVE_AUTHENTICATED_FROM_CACHE, DEFAULT_SERVE_AUTHENTICATED_FROM_CACHE));
    try {
        cache = new ErrorPageCacheImpl(ttl, serveAuthenticatedFromCache);

        Dictionary<String, Object> serviceProps = new Hashtable<String, Object>();
        serviceProps.put("jmx.objectname", "com.adobe.acs.commons:type=ErrorPageHandlerCache");

        cacheRegistration = componentContext.getBundleContext().registerService(DynamicMBean.class.getName(),
                cache, serviceProps);
    } catch (NotCompliantMBeanException e) {
        log.error("Unable to create cache", e);
    }

    /** Error Images **/

    this.errorImagesEnabled = PropertiesUtil.toBoolean(config.get(PROP_ERROR_IMAGES_ENABLED),
            DEFAULT_ERROR_IMAGES_ENABLED);

    this.errorImagePath = PropertiesUtil.toString(config.get(PROP_ERROR_IMAGE_PATH), DEFAULT_ERROR_IMAGE_PATH);

    // Absolute path
    if (StringUtils.startsWith(this.errorImagePath, "/")) {
        ResourceResolver serviceResourceResolver = null;
        try {
            Map<String, Object> authInfo = Collections.singletonMap(ResourceResolverFactory.SUBSERVICE,
                    (Object) SERVICE_NAME);
            serviceResourceResolver = resourceResolverFactory.getServiceResourceResolver(authInfo);
            final Resource resource = serviceResourceResolver.resolve(this.errorImagePath);

            if (resource != null && resource.isResourceType(JcrConstants.NT_FILE)) {
                final PathInfo pathInfo = new PathInfo(this.errorImagePath);

                if (!StringUtils.equals("img", pathInfo.getSelectorString())
                        || StringUtils.isBlank(pathInfo.getExtension())) {

                    log.warn("Absolute Error Image Path paths to nt:files should have '.img.XXX' "
                            + "selector.extension");
                }
            }
        } catch (LoginException e) {
            log.error("Could not get admin resource resolver to inspect validity of absolute errorImagePath");
        } finally {
            if (serviceResourceResolver != null) {
                serviceResourceResolver.close();
            }
        }
    }

    this.errorImageExtensions = PropertiesUtil.toStringArray(config.get(PROP_ERROR_IMAGE_EXTENSIONS),
            DEFAULT_ERROR_IMAGE_EXTENSIONS);

    for (int i = 0; i < errorImageExtensions.length; i++) {
        this.errorImageExtensions[i] = StringUtils.lowerCase(errorImageExtensions[i], Locale.ENGLISH);
    }

    final StringWriter sw = new StringWriter();
    final PrintWriter pw = new PrintWriter(sw);

    pw.println();
    pw.printf("Enabled: %s", this.enabled).println();
    pw.printf("System Error Page Path: %s", this.systemErrorPagePath).println();
    pw.printf("Error Page Extension: %s", this.errorPageExtension).println();
    pw.printf("Fallback Error Page Name: %s", this.fallbackErrorName).println();

    pw.printf("Resource Not Found - Behavior: %s", this.notFoundBehavior).println();
    pw.printf("Resource Not Found - Exclusion Path Patterns %s", Arrays.toString(tmpNotFoundExclusionPatterns))
            .println();

    pw.printf("Cache - TTL: %s", ttl).println();
    pw.printf("Cache - Serve Authenticated: %s", serveAuthenticatedFromCache).println();

    pw.printf("Error Images - Enabled: %s", this.errorImagesEnabled).println();
    pw.printf("Error Images - Path: %s", this.errorImagePath).println();
    pw.printf("Error Images - Extensions: %s", Arrays.toString(this.errorImageExtensions)).println();

    log.debug(sw.toString());
}

From source file:org.energy_home.jemma.osgi.ah.zigbee.appliances.generic.ZclGenericAppliance.java

public ZclGenericAppliance(String pid, Dictionary config) throws ApplianceException {
    super(pid, config);
    //      Integer[] endPointIds = null;
    //      try {
    //         int[] endPointIdsPrimitive = (int[]) config.get(IAppliance.APPLIANCE_EPS_IDS_PROPERTY);
    //         if (endPointIdsPrimitive != null) {
    //            endPointIds = new Integer[endPointIdsPrimitive.length];
    //            for (int i = 0; i < endPointIdsPrimitive.length; i++) {
    //               endPointIds[i] = new Integer(endPointIdsPrimitive[i]);
    //            }            
    //         }/*w w  w. j  a  v a 2  s  .  co m*/
    //      } catch (Exception e) {
    //         // FIXME: Sometimes an array of Integer object is stored in configuration admin
    //         endPointIds = (Integer[]) config.get(IAppliance.APPLIANCE_EPS_IDS_PROPERTY);
    //      }
    //      String[] endPointTypes = (String[]) config.get(IAppliance.APPLIANCE_EPS_TYPES_PROPERTY);
    String[] customConfigurationObject = (String[]) config.get(ZIGBEE_CONFIG_PROPERTY_NAME);
    customConfiguration = new ArrayList();
    ZclEndPointDescriptor epd = null;
    if (customConfigurationObject != null) {
        for (int i = 0; i < customConfigurationObject.length; i++) {
            epd = new ZclEndPointDescriptor(customConfigurationObject[i]);
            customConfiguration.add(epd);
        }
    }
    // Automatic allocation of ep 0
    for (Iterator iterator = customConfiguration.iterator(); iterator.hasNext();) {
        epd = (ZclEndPointDescriptor) iterator.next();
        zclAllocateEndPoint(epd.appEndPointId, epd.profileId, epd.deviceId, epd.endPointId, 0,
                epd.clientClusterIds, epd.serverClusterIds);
    }
    return;
}

From source file:org.jahia.modules.modulemanager.flow.ModuleManagementFlowHandler.java

private void populateActiveVersion(RequestContext context, JahiaTemplatesPackage value) {
    context.getRequestScope().put("activeVersion", value);
    Map<String, String> bundleInfo = new HashMap<String, String>();
    Dictionary<String, String> dictionary = value.getBundle().getHeaders();
    Enumeration<String> keys = dictionary.keys();
    while (keys.hasMoreElements()) {
        String s = keys.nextElement();
        bundleInfo.put(s, dictionary.get(s));
    }//  w  w  w  .  j  a  va 2  s  . c o  m
    context.getRequestScope().put("bundleInfo", bundleInfo);
    context.getRequestScope().put("activeVersionDate", new Date(value.getBundle().getLastModified()));

    context.getRequestScope().put("dependantModules",
            templateManagerService.getTemplatePackageRegistry().getDependantModules(value));
}

From source file:org.openhab.binding.hdanywhere.internal.HDanywhereBinding.java

@SuppressWarnings("rawtypes")
@Override//from  w w w. ja  v  a 2 s . c o m
public void updated(Dictionary config) throws ConfigurationException {

    if (config != null) {

        Enumeration keys = config.keys();
        while (keys.hasMoreElements()) {

            String key = (String) keys.nextElement();

            Matcher matcher = EXTRACT_HDANYWHERE_CONFIG_PATTERN.matcher(key);
            if (!matcher.matches()) {
                logger.debug("given hdanywhere-config-key '" + key
                        + "' does not follow the expected pattern '<host_IP_Address>.ports'");
                continue;
            }

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

            String hostIP = matcher.group(1) + "." + matcher.group(2) + "." + matcher.group(3) + "."
                    + matcher.group(4);
            String configKey = matcher.group(5);
            String value = (String) config.get(key);

            if ("ports".equals(configKey)) {
                matrixCache.put(hostIP, Integer.valueOf(value));
            } else {
                throw new ConfigurationException(configKey,
                        "the given configKey '" + configKey + "' is unknown");
            }
        }
    }

    setProperlyConfigured(true);

}

From source file:org.apache.sling.auth.form.impl.FormAuthenticationHandler.java

/**
 * Called by SCR to activate the authentication handler.
 *
 * @throws InvalidKeyException//from w  w  w .  j  a va2 s  .  com
 * @throws NoSuchAlgorithmException
 * @throws IllegalStateException
 * @throws UnsupportedEncodingException
 */
protected void activate(ComponentContext componentContext) throws InvalidKeyException, NoSuchAlgorithmException,
        IllegalStateException, UnsupportedEncodingException {

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

    this.jaasHelper = new JaasHelper(this, componentContext.getBundleContext(), properties);
    this.loginForm = OsgiUtil.toString(properties.get(PAR_LOGIN_FORM), AuthenticationFormServlet.SERVLET_PATH);
    log.info("Login Form URL {}", loginForm);

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

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

    final String authStorage = OsgiUtil.toString(properties.get(PAR_AUTH_STORAGE), DEFAULT_AUTH_STORAGE);
    if (AUTH_STORAGE_SESSION_ATTRIBUTE.equals(authStorage)) {

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

    } else {

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

    }

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

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

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

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

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

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

From source file:org.openhab.binding.lutron.internal.LutronBinding.java

/**
 * {@inheritDoc}// ww  w  .  jav a2 s .co m
 */
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    Boolean mapping = false;
    stopListening();

    if (config != null) {
        mapping = true;

        LutronBinding.community = (String) config.get("community");
        if (StringUtils.isBlank(LutronBinding.community)) {
            LutronBinding.community = "public";
            logger.info("didn't find SNMP community configuration -> listen to SNMP community {}",
                    LutronBinding.community);
        }

        String portString = (String) config.get("port");
        if (StringUtils.isNotBlank(portString) && portString.matches("\\d*")) {
            LutronBinding.port = integer.valueOf(portString).intValue();
        } else {
            LutronBinding.port = LUTRON_DEFAULT_PORT;
            logger.info(
                    "Didn't find SNMP port configuration or configuration is invalid -> listen to SNMP default port {}",
                    LutronBinding.port);
        }

        String timeoutString = (String) config.get("timeout");
        if (StringUtils.isNotBlank(timeoutString)) {
            LutronBinding.timeout = integer.valueOf(timeoutString).intValue();
            if (LutronBinding.timeout < 0 | LutronBinding.retries > 5) {
                logger.info(
                        "SNMP timeout value is invalid (" + LutronBinding.timeout + "). Using default value.");
                LutronBinding.timeout = 1500;
            }
        } else {
            LutronBinding.timeout = 1500;
            logger.info("Didn't find SNMP timeout or configuration is invalid -> timeout set to {}",
                    LutronBinding.timeout);
        }

        String retriesString = (String) config.get("retries");
        if (StringUtils.isNotBlank(retriesString)) {
            LutronBinding.retries = integer.valueOf(retriesString).intValue();
            if (LutronBinding.retries < 0 | LutronBinding.retries > 5) {
                logger.info(
                        "SNMP retries value is invalid (" + LutronBinding.retries + "). Using default value.");
                LutronBinding.retries = 0;
            }
        } else {
            LutronBinding.retries = 0;
            logger.info("Didn't find SNMP retries or configuration is invalid -> retries set to {}",
                    LutronBinding.retries);
        }

    }

    for (LutronBindingProvider provider : providers) {
        if (provider.getInBindingItemNames() != null) {
            mapping = true;
        }
    }

    // Did we find either a trap request, or any bindings
    if (mapping) {
        listen();
    }
}