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.ops4j.pax.web.itest.jetty.WhiteboardR6IntegrationTest.java

private ServiceRegistration<Servlet> registerServlet(Dictionary<String, String> extendedProps) {
    Dictionary<String, String> properties = new Hashtable<>();
    properties.put("osgi.http.whiteboard.servlet.pattern", "/myservlet");
    properties.put("servlet.init.myname", "value");

    if (extendedProps != null) {
        Enumeration<String> keys = extendedProps.keys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            properties.put(key, extendedProps.get(key));
        }/* w  ww.  j a va 2 s. c  o m*/
    }

    ServiceRegistration<Servlet> registerService = bundleContext.registerService(Servlet.class, new MyServlet(),
            properties);
    return registerService;
}

From source file:org.openengsb.core.test.AbstractOsgiMockServiceTest.java

private <T> ServiceReference<T> putService(T service, Dictionary<String, Object> props) {
    @SuppressWarnings("unchecked")
    ServiceReference<T> serviceReference = mock(ServiceReference.class);
    long serviceId = --this.serviceId;
    LOGGER.info("registering service with ID: " + serviceId);
    props.put(Constants.SERVICE_ID, serviceId);
    services.put(serviceReference, service);
    synchronized (serviceReferences) {
        serviceReferences.put(serviceReference, props);
    }//from  w ww.  ja v  a  2 s  .  c  o m
    when(serviceReference.getProperty(anyString())).thenAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return serviceReferences.get(invocation.getMock()).get(invocation.getArguments()[0]);
        }
    });
    when(serviceReference.getBundle()).thenReturn(bundle);
    when(serviceReference.getPropertyKeys()).thenAnswer(new Answer<String[]>() {
        @Override
        public String[] answer(InvocationOnMock invocation) throws Throwable {
            Dictionary<String, Object> dictionary = serviceReferences.get(invocation.getMock());
            List<?> list = EnumerationUtils.toList(dictionary.keys());
            @SuppressWarnings("unchecked")
            Collection<String> typedCollection = CollectionUtils.typedCollection(list, String.class);
            return typedCollection.toArray(new String[0]);
        }
    });
    return serviceReference;
}

From source file:org.openhab.binding.pilight.internal.PilightBinding.java

private Map<String, PilightConnection> parseConfig(Dictionary<String, ?> config) {
    Map<String, PilightConnection> connections = new HashMap<String, PilightConnection>();
    Enumeration<String> keys = config.keys();

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

        if ("service.pid".equals(key))
            continue;

        String[] parts = key.split("\\.");
        String instance = parts[0];

        PilightConnection connection = connections.get(instance);
        if (connection == null) {
            connection = new PilightConnection();
            connection.setInstance(instance);
        }//from w  w w .  j  a va2s .  com

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

        if ("host".equals(parts[1])) {
            connection.setHostname(value);
        }
        if ("port".equals(parts[1])) {
            connection.setPort(Integer.valueOf(value));
        }
        if ("delay".equals(parts[1])) {
            connection.setDelay(Long.valueOf(value));
        }

        connections.put(instance, connection);
    }
    return connections;
}

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   www  . j  a  v  a2  s. c o 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.mitre.dsmiley.httpproxy.ProxyServletTest.java

protected WebResponse execAndAssert(WebRequest request, String expectedUri) throws Exception {
    WebResponse rsp = sc.getResponse(request);

    assertEquals(HttpStatus.SC_OK, rsp.getResponseCode());
    //HttpUnit doesn't pass the message; not a big deal
    //assertEquals("TESTREASON",rsp.getResponseMessage());
    final String text = rsp.getText();
    assertTrue(text.startsWith("REQUESTLINE:"));

    String expectedTargetUri = getExpectedTargetUri(request, expectedUri);
    String expectedFirstLine = "REQUESTLINE: " + (request instanceof GetMethodWebRequest ? "GET" : "POST");
    expectedFirstLine += " " + expectedTargetUri + " HTTP/1.1";

    String firstTextLine = text.substring(0, text.indexOf(System.getProperty("line.separator")));

    assertEquals(expectedFirstLine, firstTextLine);

    // Assert all headers are present, and therefore checks the case has been preserved (see GH #65)
    Dictionary headers = request.getHeaders();
    Enumeration headerNameEnum = headers.keys();
    while (headerNameEnum.hasMoreElements()) {
        String headerName = (String) headerNameEnum.nextElement();
        assertTrue(text.contains(headerName));
    }/*from w ww  .j  a v  a 2 s. c  om*/

    return rsp;
}

From source file:org.openhab.binding.sallegra.internal.SallegraBinding.java

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

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

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

        Enumeration<String> keys = config.keys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();

            // Escape of dot absolutely necessary
            String[] keyElements = key.split("\\.");

            String deviceId = keyElements[0];

            if (keyElements.length >= 2) {

                SallegraNode node = sallegraNodes.get(deviceId);
                if (node == null) {
                    node = new SallegraNode();
                    sallegraNodes.put(deviceId, node);
                }

                String option = keyElements[1];
                if (option.equals("password")) {
                    node.setPassword((String) config.get(key));
                } else if (option.equals("hostname")) {
                    node.setHostName((String) config.get(key));
                }
            }
        }

        setProperlyConfigured(checkProperlyConfigured());
    }
}

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

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

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

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

    m_httpServiceFactoryProps = toPropagate;
}

From source file:org.openhab.binding.networkupstools.internal.NetworkUpsToolsBinding.java

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

        Map<String, NutConfig> newUpses = new HashMap<String, NutConfig>();

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

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

            if ("refresh".equals(key) || "service.pid".equals(key)) {
                continue;
            }

            String[] parts = key.split("\\.");
            String name = parts[0];
            String prop = parts[1];
            String value = (String) config.get(key);

            NutConfig nutConfig = newUpses.get(name);
            if (nutConfig == null) {
                nutConfig = new NutConfig();
                newUpses.put(name, nutConfig);
            }

            if ("device".equalsIgnoreCase(prop)) {
                nutConfig.device = value;
            } else if ("host".equalsIgnoreCase(prop)) {
                nutConfig.host = value;
            } else if ("login".equalsIgnoreCase(prop)) {
                nutConfig.login = value;
            } else if ("pass".equalsIgnoreCase(prop)) {
                nutConfig.pass = value;
            } else if ("port".equalsIgnoreCase(prop)) {
                nutConfig.port = Integer.parseInt(value);
            }
        }

        upses = newUpses;

        setProperlyConfigured(true);
    }
}

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

/**
 * @{inheritDoc/* ww w . j av a2s .c o  m*/
 */
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.felix.webconsole.internal.compendium.ComponentsServlet.java

private void listComponentProperties(JSONWriter jsonWriter, Component inputComponent) {
    Dictionary propsBook = inputComponent.getProperties();
    if (propsBook != null) {
        JSONArray myBuf = new JSONArray();
        TreeSet bookKeys = new TreeSet(Collections.list(propsBook.keys()));
        for (Iterator keyIter = bookKeys.iterator(); keyIter.hasNext();) {
            final String key = (String) keyIter.next();
            final StringBuffer strBuffer = new StringBuffer();
            strBuffer.append(key).append(" = ");

            Object prop = propsBook.get(key);
            if (prop.getClass().isArray()) {
                prop = Arrays.asList((Object[]) prop);
            }//from w ww . j  av a2  s  .  co  m
            strBuffer.append(prop);
            myBuf.put(strBuffer.toString());
        }

        printKeyVal(jsonWriter, "Properties", myBuf);
    }

}