Example usage for org.apache.commons.configuration HierarchicalConfiguration getInt

List of usage examples for org.apache.commons.configuration HierarchicalConfiguration getInt

Introduction

In this page you can find the example usage for org.apache.commons.configuration HierarchicalConfiguration getInt.

Prototype

public int getInt(String key, int defaultValue) 

Source Link

Usage

From source file:com.bytelightning.opensource.pokerface.PokerFace.java

/**
 * Configures all the needed components, but does not actually start the server.
 * @param config   Contains all information needed to fully wire up the http, https, and httpclient components of this reverse proxy.
 * @throws Exception   Yeah, a lot can go wrong here, but at least it will be caught immediately :-)
 *///from  w  ww .j av a 2s . c o  m
public void config(HierarchicalConfiguration config) throws Exception {
    List<HierarchicalConfiguration> lconf;
    HttpAsyncRequester executor = null;
    BasicNIOConnPool connPool = null;
    ObjectPool<ByteBuffer> byteBufferPool = null;
    LinkedHashMap<String, TargetDescriptor> mappings = null;
    ConcurrentMap<String, HttpHost> hosts = null;

    handlerRegistry = new UriHttpAsyncRequestHandlerMapper();

    // Initialize the keystore (if one was specified)
    KeyStore keystore = null;
    char[] keypass = null;
    String keystoreUri = config.getString("keystore");
    if ((keystoreUri != null) && (keystoreUri.trim().length() > 0)) {
        Path keystorePath = Utils.MakePath(keystoreUri);
        if (!Files.exists(keystorePath))
            throw new ConfigurationException("Keystore does not exist.");
        if (Files.isDirectory(keystorePath))
            throw new ConfigurationException("Keystore is not a file");
        String storepass = config.getString("storepass");
        if ((storepass != null) && "null".equals(storepass))
            storepass = null;
        keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream keyStoreStream = Files.newInputStream(keystorePath)) {
            keystore.load(keyStoreStream, storepass == null ? null : storepass.trim().toCharArray());
        } catch (IOException ex) {
            Logger.error("Unable to load https server keystore from " + keystoreUri);
            return;
        }
        keypass = config.getString("keypass").trim().toCharArray();
    }

    // Wire up the listening reactor
    lconf = config.configurationsAt("server");
    if ((lconf == null) || (lconf.size() != 1))
        throw new ConfigurationException("One (and only one) server configuration element is allowed.");
    else {
        Builder builder = IOReactorConfig.custom();
        builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("server[@cpu]", 0.667)));
        builder.setSoTimeout(config.getInt("server[@soTimeout]", 0));
        builder.setSoLinger(config.getInt("server[@soLinger]", -1));
        builder.setSoReuseAddress(true);
        builder.setTcpNoDelay(false);
        builder.setSelectInterval(100);

        IOReactorConfig rconfig = builder.build();
        Logger.info("Configuring server with options: " + rconfig.toString());
        listeningReactor = new DefaultListeningIOReactor(rconfig);

        lconf = config.configurationsAt("server.listen");
        InetSocketAddress addr;
        boolean hasNonWildcardSecure = false;
        LinkedHashMap<SocketAddress, SSLContext> addrSSLContext = new LinkedHashMap<SocketAddress, SSLContext>();
        if ((lconf == null) || (lconf.size() == 0)) {
            addr = new InetSocketAddress("127.0.0.1", 8080);
            ListenerEndpoint ep = listeningReactor.listen(addr);
            Logger.warn("Configured " + ep.getAddress());
        } else {
            TrustManager[] trustManagers = null;
            KeyManagerFactory kmf = null;
            // Create all the specified listeners.
            for (HierarchicalConfiguration hc : lconf) {
                String addrStr = hc.getString("[@address]");
                if ((addrStr == null) || (addrStr.length() == 0))
                    addrStr = "0.0.0.0";
                String alias = hc.getString("[@alias]");
                int port = hc.getInt("[@port]", alias != null ? 443 : 80);
                addr = new InetSocketAddress(addrStr, port);
                ListenerEndpoint ep = listeningReactor.listen(addr);
                String protocol = hc.containsKey("[@protocol]") ? hc.getString("[@protocol]") : null;
                Boolean secure = hc.containsKey("[@secure]") ? hc.getBoolean("[@secure]") : null;
                if ((alias != null) && (secure == null))
                    secure = true;
                if ((protocol != null) && (secure == null))
                    secure = true;
                if ((secure != null) && secure) {
                    if (protocol == null)
                        protocol = "TLS";
                    if (keystore == null)
                        throw new ConfigurationException(
                                "An https listening socket was requested, but no keystore was specified.");
                    if (kmf == null) {
                        kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                        kmf.init(keystore, keypass);
                    }
                    // Are we going to trust all clients or just specific ones?
                    if (hc.getBoolean("[@trustAny]", true))
                        trustManagers = new TrustManager[] { new X509TrustAllManager() };
                    else {
                        TrustManagerFactory instance = TrustManagerFactory
                                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                        instance.init(keystore);
                        trustManagers = instance.getTrustManagers();
                    }
                    KeyManager[] keyManagers = kmf.getKeyManagers();
                    if (alias != null)
                        for (int i = 0; i < keyManagers.length; i++) {
                            if (keyManagers[i] instanceof X509ExtendedKeyManager)
                                keyManagers[i] = new PokerFaceKeyManager(alias,
                                        (X509ExtendedKeyManager) keyManagers[i]);
                        }
                    SSLContext sslCtx = SSLContext.getInstance(protocol);
                    sslCtx.init(keyManagers, trustManagers, new SecureRandom());
                    if (addr.getAddress().isAnyLocalAddress()) {
                        // This little optimization helps us respond faster for every connection as we don't have to extrapolate a local connection address to wild card.
                        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                                .hasMoreElements();) {
                            NetworkInterface intf = en.nextElement();
                            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                                    .hasMoreElements();) {
                                addr = new InetSocketAddress(enumIpAddr.nextElement(), port);
                                addrSSLContext.put(addr, sslCtx);
                            }
                        }
                    } else {
                        addrSSLContext.put(addr, sslCtx);
                        hasNonWildcardSecure = true;
                    }
                }
                Logger.warn("Configured " + (alias == null ? "" : (protocol + " on")) + ep.getAddress());
            }
        }
        // We will need an HTTP protocol processor for the incoming connections
        String serverAgent = config.getString("server.serverAgent", "PokerFace/" + Utils.Version);
        HttpProcessor inhttpproc = new ImmutableHttpProcessor(
                new HttpResponseInterceptor[] { new ResponseDateInterceptor(), new ResponseServer(serverAgent),
                        new ResponseContent(), new ResponseConnControl() });
        HttpAsyncService serviceHandler = new HttpAsyncService(inhttpproc, new DefaultConnectionReuseStrategy(),
                null, handlerRegistry, null) {
            public void exception(final NHttpServerConnection conn, final Exception cause) {
                Logger.warn(cause.getMessage());
                super.exception(conn, cause);
            }
        };
        if (addrSSLContext.size() > 0) {
            final SSLContext defaultCtx = addrSSLContext.values().iterator().next();
            final Map<SocketAddress, SSLContext> sslMap;
            if ((!hasNonWildcardSecure) || (addrSSLContext.size() == 1))
                sslMap = null;
            else
                sslMap = addrSSLContext;
            listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler,
                    new SSLNHttpServerConnectionFactory(defaultCtx, null, ConnectionConfig.DEFAULT) {
                        protected SSLIOSession createSSLIOSession(IOSession iosession, SSLContext sslcontext,
                                SSLSetupHandler sslHandler) {
                            SSLIOSession retVal;
                            SSLContext sktCtx = sslcontext;
                            if (sslMap != null) {
                                SocketAddress la = iosession.getLocalAddress();
                                if (la != null) {
                                    sktCtx = sslMap.get(la);
                                    if (sktCtx == null)
                                        sktCtx = sslcontext;
                                }
                                retVal = new SSLIOSession(iosession, SSLMode.SERVER, sktCtx, sslHandler);
                            } else
                                retVal = super.createSSLIOSession(iosession, sktCtx, sslHandler);
                            if (sktCtx != null)
                                retVal.setAttribute("com.bytelightning.opensource.pokerface.secure", true);
                            return retVal;
                        }
                    });
        } else
            listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler, ConnectionConfig.DEFAULT);
    }

    // Configure the httpclient reactor that will be used to do reverse proxing to the specified targets.
    lconf = config.configurationsAt("targets");
    if ((lconf != null) && (lconf.size() > 0)) {
        HierarchicalConfiguration conf = lconf.get(0);
        Builder builder = IOReactorConfig.custom();
        builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("targets[@cpu]", 0.667)));
        builder.setSoTimeout(conf.getInt("targets[@soTimeout]", 0));
        builder.setSoLinger(config.getInt("targets[@soLinger]", -1));
        builder.setConnectTimeout(conf.getInt("targets[@connectTimeout]", 0));
        builder.setSoReuseAddress(true);
        builder.setTcpNoDelay(false);
        connectingReactor = new DefaultConnectingIOReactor(builder.build());

        final int bufferSize = conf.getInt("targets[@bufferSize]", 1024) * 1024;
        byteBufferPool = new SoftReferenceObjectPool<ByteBuffer>(new BasePooledObjectFactory<ByteBuffer>() {
            @Override
            public ByteBuffer create() throws Exception {
                return ByteBuffer.allocateDirect(bufferSize);
            }

            @Override
            public PooledObject<ByteBuffer> wrap(ByteBuffer buffer) {
                return new DefaultPooledObject<ByteBuffer>(buffer);
            }
        });

        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;

        if (keystore != null) {
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(keystore, keypass);
            keyManagers = kmf.getKeyManagers();
        }
        // Will the httpclient's trust any remote target, or only specific ones.
        if (conf.getBoolean("targets[@trustAny]", false))
            trustManagers = new TrustManager[] { new X509TrustAllManager() };
        else if (keystore != null) {
            TrustManagerFactory instance = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            instance.init(keystore);
            trustManagers = instance.getTrustManagers();
        }
        SSLContext clientSSLContext = SSLContext.getInstance(conf.getString("targets[@protocol]", "TLS"));
        clientSSLContext.init(keyManagers, trustManagers, new SecureRandom());

        // Setup an SSL capable connection pool for the httpclients.
        connPool = new BasicNIOConnPool(connectingReactor,
                new BasicNIOConnFactory(clientSSLContext, null, ConnectionConfig.DEFAULT),
                conf.getInt("targets[@connectTimeout]", 0));
        connPool.setMaxTotal(conf.getInt("targets[@connMaxTotal]", 1023));
        connPool.setDefaultMaxPerRoute(conf.getInt("targets[@connMaxPerRoute]", 1023));

        // Set up HTTP protocol processor for outgoing connections
        String userAgent = conf.getString("targets.userAgent", "PokerFace/" + Utils.Version);
        HttpProcessor outhttpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                new RequestContent(), new RequestTargetHost(), new RequestConnControl(),
                new RequestUserAgent(userAgent), new RequestExpectContinue(true) });
        executor = new HttpAsyncRequester(outhttpproc, new DefaultConnectionReuseStrategy());

        // Now set up all the configured targets.
        mappings = new LinkedHashMap<String, TargetDescriptor>();
        hosts = new ConcurrentHashMap<String, HttpHost>();
        String[] scheme = { null };
        String[] host = { null };
        int[] port = { 0 };
        String[] path = { null };
        int[] stripPrefixCount = { 0 };
        for (HierarchicalConfiguration targetConfig : conf.configurationsAt("target")) {
            String match = targetConfig.getString("[@pattern]");
            if ((match == null) || (match.trim().length() < 1)) {
                Logger.error("Unable to configure target;  Invalid url match pattern");
                continue;
            }
            String key = RequestForTargetConsumer.UriToTargetKey(targetConfig.getString("[@url]"), scheme, host,
                    port, path, stripPrefixCount);
            if (key == null) {
                Logger.error("Unable to configure target");
                continue;
            }
            HttpHost targetHost = hosts.get(key);
            if (targetHost == null) {
                targetHost = new HttpHost(host[0], port[0], scheme[0]);
                hosts.put(key, targetHost);
            }
            TargetDescriptor desc = new TargetDescriptor(targetHost, path[0], stripPrefixCount[0]);
            mappings.put(match, desc);
        }
        connectionDispatcher = new DefaultHttpClientIODispatch(new HttpAsyncRequestExecutor(),
                ConnectionConfig.DEFAULT);
    }
    // Allocate the script map which will be populated by it's own executor thread.
    if (config.containsKey("scripts.rootDirectory")) {
        Path tmp = Utils.MakePath(config.getProperty("scripts.rootDirectory"));
        if (!Files.exists(tmp))
            throw new FileNotFoundException("Scripts directory does not exist.");
        if (!Files.isDirectory(tmp))
            throw new FileNotFoundException("'scripts' path is not a directory.");
        scripts = new ConcurrentSkipListMap<String, ScriptObjectMirror>();
        boolean watch = config.getBoolean("scripts.dynamicWatch", false);
        List<Path> jsLibs;
        Object prop = config.getProperty("scripts.library");
        if (prop != null) {
            jsLibs = new ArrayList<Path>();
            if (prop instanceof Collection<?>) {
                @SuppressWarnings("unchecked")
                Collection<Object> oprop = (Collection<Object>) prop;
                for (Object obj : oprop)
                    jsLibs.add(Utils.MakePath(obj));
            } else {
                jsLibs.add(Utils.MakePath(prop));
            }
        } else
            jsLibs = null;

        lconf = config.configurationsAt("scripts.scriptConfig");
        if (lconf != null) {
            if (lconf.size() > 1)
                throw new ConfigurationException("Only one scriptConfig element is allowed.");
            if (lconf.size() == 0)
                lconf = null;
        }

        HierarchicalConfiguration scriptConfig;
        if (lconf == null)
            scriptConfig = new HierarchicalConfiguration();
        else
            scriptConfig = lconf.get(0);
        scriptConfig.setProperty("pokerface.scripts.rootDirectory", tmp.toString());

        configureScripts(jsLibs, scriptConfig, tmp, watch);
        if (watch)
            ScriptDirectoryWatcher = new DirectoryWatchService();
    }

    // Configure the static file directory (if any)
    Path staticFilesPath = null;
    if (config.containsKey("files.rootDirectory")) {
        Path tmp = Utils.MakePath(config.getProperty("files.rootDirectory"));
        if (!Files.exists(tmp))
            throw new FileNotFoundException("Files directory does not exist.");
        if (!Files.isDirectory(tmp))
            throw new FileNotFoundException("'files' path is not a directory.");
        staticFilesPath = tmp;
        List<HierarchicalConfiguration> mimeEntries = config.configurationsAt("files.mime-entry");
        if (mimeEntries != null) {
            for (HierarchicalConfiguration entry : mimeEntries) {
                entry.setDelimiterParsingDisabled(true);
                String type = entry.getString("[@type]", "").trim();
                if (type.length() == 0)
                    throw new ConfigurationException("Invalid mime type entry");
                String extensions = entry.getString("[@extensions]", "").trim();
                if (extensions.length() == 0)
                    throw new ConfigurationException("Invalid mime extensions for: " + type);
                ScriptHelperImpl.AddMimeEntry(type, extensions);
            }
        }
    }

    handlerRegistry.register("/*",
            new RequestHandler(executor, connPool, byteBufferPool, staticFilesPath, mappings,
                    scripts != null ? Collections.unmodifiableNavigableMap(scripts) : null,
                    config.getBoolean("scripts.allowScriptsToSpecifyDynamicHosts", false) ? hosts : null));
}

From source file:at.ac.tuwien.auto.iotsys.gateway.connectors.knx.KNXDeviceLoaderImpl.java

public ArrayList<Connector> initDevices(ObjectBroker objectBroker) {
    setConfiguration(devicesConfig);/*from ww  w .  jav a2 s  . co m*/
    objectBroker.getConfigDb().prepareDeviceLoader(getClass().getName());

    ArrayList<Connector> connectors = new ArrayList<Connector>();

    List<JsonNode> connectorsFromDb = objectBroker.getConfigDb().getConnectors("knx");
    int connectorsSize = 0;

    if (connectorsFromDb.size() <= 0) {
        Object knxConnectors = devicesConfig.getProperty("knx.connector.name");

        if (knxConnectors != null) {
            connectorsSize = 1;
        }

        if (knxConnectors instanceof Collection<?>) {
            connectorsSize = ((Collection<?>) knxConnectors).size();
        }
    } else
        connectorsSize = connectorsFromDb.size();

    for (int connector = 0; connector < connectorsSize; connector++) {

        HierarchicalConfiguration subConfig = devicesConfig.configurationAt("knx.connector(" + connector + ")");

        Object knxConfiguredDevices = subConfig.getProperty("device.type");// just to get the number of devices
        String connectorId = "";
        String connectorName = subConfig.getString("name");
        String routerIP = subConfig.getString("router.ip");
        int routerPort = subConfig.getInteger("router.port", 3671);
        String localIP = subConfig.getString("localIP");
        Boolean enabled = subConfig.getBoolean("enabled", false);

        try {
            connectorId = connectorsFromDb.get(connector).get("_id").asText();
            connectorName = connectorsFromDb.get(connector).get("name").asText();
            enabled = connectorsFromDb.get(connector).get("enabled").asBoolean();
            routerIP = connectorsFromDb.get(connector).get("routerHostname").asText();
            routerPort = connectorsFromDb.get(connector).get("routerPort").asInt();
            localIP = connectorsFromDb.get(connector).get("localIP").asText();
        } catch (Exception e) {
            log.info("Cannot fetch configuration from Database, using devices.xml");
        }

        if (enabled) {
            try {
                KNXConnector knxConnector = new KNXConnector(routerIP, routerPort, localIP);
                knxConnector.setName(connectorName);
                knxConnector.setTechnology("knx");
                knxConnector.setEnabled(enabled);
                //knxConnector.connect();
                connectors.add(knxConnector);

                int numberOfDevices = 0;
                List<Device> devicesFromDb = objectBroker.getConfigDb().getDevices(connectorId);

                if (connectorsFromDb.size() <= 0) {
                    if (knxConfiguredDevices != null) {
                        numberOfDevices = 1; // there is at least one
                                             // device.
                    }
                    if (knxConfiguredDevices instanceof Collection<?>) {
                        Collection<?> knxDevices = (Collection<?>) knxConfiguredDevices;
                        numberOfDevices = knxDevices.size();
                    }
                } else
                    numberOfDevices = devicesFromDb.size();

                log.info(
                        numberOfDevices + " KNX devices found in configuration for connector " + connectorName);
                for (int i = 0; i < numberOfDevices; i++) {

                    String type = subConfig.getString("device(" + i + ").type");
                    List<Object> address = subConfig.getList("device(" + i + ").address");
                    String addressString = address.toString();

                    String ipv6 = subConfig.getString("device(" + i + ").ipv6");
                    String href = subConfig.getString("device(" + i + ").href");

                    String name = subConfig.getString("device(" + i + ").name");

                    String displayName = subConfig.getString("device(" + i + ").displayName");

                    Boolean historyEnabled = subConfig.getBoolean("device(" + i + ").historyEnabled", false);

                    Boolean groupCommEnabled = subConfig.getBoolean("device(" + i + ").groupCommEnabled",
                            false);

                    Integer historyCount = subConfig.getInt("device(" + i + ").historyCount", 0);

                    Boolean refreshEnabled = subConfig.getBoolean("device(" + i + ").refreshEnabled", false);

                    Device deviceFromDb;
                    try {
                        deviceFromDb = devicesFromDb.get(i);
                        type = deviceFromDb.getType();
                        addressString = deviceFromDb.getAddress();
                        String subAddr[] = addressString.substring(1, addressString.length() - 1).split(", ");
                        address = Arrays.asList((Object[]) subAddr);
                        ipv6 = deviceFromDb.getIpv6();
                        href = deviceFromDb.getHref();
                        name = deviceFromDb.getName();
                        displayName = deviceFromDb.getDisplayName();
                        historyEnabled = deviceFromDb.isHistoryEnabled();
                        groupCommEnabled = deviceFromDb.isGroupcommEnabled();
                        refreshEnabled = deviceFromDb.isRefreshEnabled();
                        historyCount = deviceFromDb.getHistoryCount();
                    } catch (Exception e) {
                    }

                    // Transition step: comment when done
                    Device d = new Device(type, ipv6, addressString, href, name, displayName, historyCount,
                            historyEnabled, groupCommEnabled, refreshEnabled);
                    objectBroker.getConfigDb().prepareDevice(connectorName, d);

                    if (type != null && address != null) {
                        int addressCount = address.size();
                        try {
                            Constructor<?>[] declaredConstructors = Class.forName(type)
                                    .getDeclaredConstructors();
                            for (int k = 0; k < declaredConstructors.length; k++) {
                                if (declaredConstructors[k].getParameterTypes().length == addressCount + 1) { // constructor
                                    // that
                                    // takes
                                    // the
                                    // KNX
                                    // connector
                                    // and
                                    // group
                                    // address
                                    // as
                                    // argument
                                    Object[] args = new Object[address.size() + 1];
                                    // first arg is KNX connector

                                    args[0] = knxConnector;
                                    for (int l = 1; l <= address.size(); l++) {
                                        try {
                                            String adr = (String) address.get(l - 1);
                                            if (adr == null || adr.equals("null")) {
                                                args[l] = null;
                                            } else {
                                                args[l] = new GroupAddress(adr);
                                            }
                                        } catch (KNXFormatException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                    try {
                                        // create a instance of the
                                        // specified KNX device
                                        Obj knxDevice = (Obj) declaredConstructors[k].newInstance(args);

                                        knxDevice.setHref(new Uri(
                                                URLEncoder.encode(connectorName, "UTF-8") + "/" + href));

                                        if (name != null && name.length() > 0) {
                                            knxDevice.setName(name);
                                        }

                                        if (displayName != null && displayName.length() > 0) {
                                            knxDevice.setDisplayName(displayName);
                                        }

                                        if (ipv6 != null) {
                                            objectBroker.addObj(knxDevice, ipv6);
                                        } else {
                                            objectBroker.addObj(knxDevice);
                                        }

                                        myObjects.add(knxDevice);

                                        knxDevice.initialize();

                                        if (historyEnabled != null && historyEnabled) {
                                            if (historyCount != null && historyCount != 0) {
                                                objectBroker.addHistoryToDatapoints(knxDevice, historyCount);
                                            } else {
                                                objectBroker.addHistoryToDatapoints(knxDevice);
                                            }
                                        }

                                        if (groupCommEnabled) {
                                            objectBroker.enableGroupComm(knxDevice);
                                        }

                                        if (refreshEnabled != null && refreshEnabled) {
                                            objectBroker.enableObjectRefresh(knxDevice);
                                        }

                                    } catch (IllegalArgumentException e) {
                                        e.printStackTrace();
                                    } catch (InstantiationException e) {
                                        e.printStackTrace();
                                    } catch (IllegalAccessException e) {
                                        e.printStackTrace();
                                    } catch (InvocationTargetException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        } catch (SecurityException e) {
                            e.printStackTrace();
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    return connectors;
}

From source file:at.ac.tuwien.auto.iotsys.gateway.connectors.bacnet.BacnetDeviceLoaderImpl.java

public ArrayList<Connector> initDevices(ObjectBroker objectBroker) {
    setConfiguration(devicesConfig);//w w w .j a  v a  2  s. c o m
    objectBroker.getConfigDb().prepareDeviceLoader(getClass().getName());

    ArrayList<Connector> connectors = new ArrayList<Connector>();

    List<JsonNode> connectorsFromDb = objectBroker.getConfigDb().getConnectors("bacnet");
    int connectorsSize = 0;
    // bacnet
    if (connectorsFromDb.size() <= 0) {
        Object bacnetConnectors = devicesConfig.getProperty("bacnet.connector.name");

        if (bacnetConnectors != null) {
            connectorsSize = 1;
        } else {
            connectorsSize = 0;
        }

        if (bacnetConnectors instanceof Collection<?>) {
            connectorsSize = ((Collection<?>) bacnetConnectors).size();
        }
    } else
        connectorsSize = connectorsFromDb.size();

    for (int connector = 0; connector < connectorsSize; connector++) {
        HierarchicalConfiguration subConfig = devicesConfig
                .configurationAt("bacnet.connector(" + connector + ")");

        Object bacnetConfiguredDevices = subConfig.getProperty("device.type");
        String connectorId = "";
        String connectorName = subConfig.getString("name");
        String broadcastAddress = subConfig.getString("broadcastAddress");
        int localPort = subConfig.getInteger("localPort", 3671);
        int localDeviceID = subConfig.getInteger("localDeviceID", 12345);
        boolean enabled = subConfig.getBoolean("enabled", false);
        Boolean groupCommEnabled = subConfig.getBoolean("groupCommEnabled", null);
        Boolean historyEnabled = subConfig.getBoolean("historyEnabled", null);

        try {
            connectorId = connectorsFromDb.get(connector).get("_id").asText();
            connectorName = connectorsFromDb.get(connector).get("name").asText();
            enabled = connectorsFromDb.get(connector).get("enabled").asBoolean();
            groupCommEnabled = connectorsFromDb.get(connector).get("groupCommEnabled").asBoolean();
            historyEnabled = connectorsFromDb.get(connector).get("historyEnabled").asBoolean();
            broadcastAddress = connectorsFromDb.get(connector).get("broadcastAddress").asText();
            localPort = connectorsFromDb.get(connector).get("localPort").asInt();
            localDeviceID = connectorsFromDb.get(connector).get("localDeviceID").asInt();
        } catch (Exception e) {
            log.info("Cannot fetch configuration from Database, using devices.xml");
        }

        if (enabled) {
            try {
                BACnetConnector bacnetConnector = new BACnetConnector(localDeviceID, broadcastAddress,
                        localPort);
                bacnetConnector.setName(connectorName);
                bacnetConnector.setTechnology("bacnet");
                bacnetConnector.setEnabled(enabled);

                Obj bacRoot = bacnetConnector.getRootObj();
                bacRoot.setName(connectorName);
                bacRoot.setHref(new Uri(connectorName.replaceAll("[^a-zA-Z0-9-~\\(\\)]", "")));
                objectBroker.addObj(bacRoot, true);

                // Transition step: Moving configs to DB: all connector enabled, uncomment when done
                //bacnetConnector.connect();

                Boolean discoveryEnabled = subConfig.getBoolean("discovery-enabled", false);
                if (discoveryEnabled)
                    bacnetConnector.discover(
                            new DeviceDiscoveryListener(objectBroker, groupCommEnabled, historyEnabled));

                connectors.add(bacnetConnector);

                int numberOfDevices = 0;
                List<Device> devicesFromDb = objectBroker.getConfigDb().getDevices(connectorId);

                if (connectorsFromDb.size() <= 0) {
                    // TODO: bacnetConfiguredDevices is from devices.xml --> mismatch when a connector does not have any device associated,
                    // e.g., bacnet a-lab (auto) connector
                    // do like this for other device loaders!
                    if (bacnetConfiguredDevices != null) {
                        numberOfDevices = 1; // there is at least one device.
                    }
                    if (bacnetConfiguredDevices instanceof Collection<?>) {
                        Collection<?> bacnetDevices = (Collection<?>) bacnetConfiguredDevices;
                        numberOfDevices = bacnetDevices.size();
                    }
                } else
                    numberOfDevices = devicesFromDb.size();

                log.info(numberOfDevices + " BACnet devices found in configuration for connector "
                        + connectorName);

                // Transition step: comment when done
                for (int i = 0; i < numberOfDevices; i++) {
                    String type = subConfig.getString("device(" + i + ").type");
                    List<Object> address = subConfig.getList("device(" + i + ").address");
                    String addressString = address.toString();
                    String ipv6 = subConfig.getString("device(" + i + ").ipv6");
                    String href = subConfig.getString("device(" + i + ").href");

                    // device specific setting
                    Boolean historyEnabledDevice = subConfig.getBoolean("device(" + i + ").historyEnabled",
                            null);

                    if (historyEnabledDevice != null) {
                        historyEnabled = historyEnabledDevice;
                    }

                    // device specific setting
                    Boolean groupCommEnabledDevice = subConfig.getBoolean("device(" + i + ").groupCommEnabled",
                            null);

                    if (groupCommEnabledDevice != null) {
                        // overwrite general settings
                        groupCommEnabled = groupCommEnabledDevice;
                    }

                    String name = subConfig.getString("device(" + i + ").name");

                    String displayName = subConfig.getString("device(" + i + ").displayName");

                    Boolean refreshEnabled = subConfig.getBoolean("device(" + i + ").refreshEnabled", false);

                    Integer historyCount = subConfig.getInt("device(" + i + ").historyCount", 0);

                    Device deviceFromDb;
                    try {
                        deviceFromDb = devicesFromDb.get(i);
                        type = deviceFromDb.getType();
                        addressString = deviceFromDb.getAddress();
                        String subAddr[] = addressString.substring(1, addressString.length() - 1).split(", ");
                        address = Arrays.asList((Object[]) subAddr);
                        ipv6 = deviceFromDb.getIpv6();
                        href = deviceFromDb.getHref();
                        name = deviceFromDb.getName();
                        displayName = deviceFromDb.getDisplayName();
                        historyEnabled = deviceFromDb.isHistoryEnabled();
                        groupCommEnabled = deviceFromDb.isGroupcommEnabled();
                        refreshEnabled = deviceFromDb.isRefreshEnabled();
                        historyCount = deviceFromDb.getHistoryCount();
                    } catch (Exception e) {
                    }
                    // Transition step: comment when done
                    Device d = new Device(type, ipv6, addressString, href, name, displayName, historyCount,
                            historyEnabled, groupCommEnabled, refreshEnabled);
                    objectBroker.getConfigDb().prepareDevice(connectorName, d);

                    if (type != null && address != null) {

                        // now follow possible multiple data points
                        // identified through
                        // the device Id, object type, the instance number and the
                        // property identifier, which shall be packaged into an BacnetDatapointInfo object

                        ObjectIdentifier[] objectIdentifier = new ObjectIdentifier[(address.size()) / 4];
                        PropertyIdentifier[] propertyIdentifier = new PropertyIdentifier[(address.size()) / 4];

                        BacnetDataPointInfo[] bacnetDataPointInfo = new BacnetDataPointInfo[(address.size())
                                / 4];

                        int q = 0;
                        for (int p = 0; p <= address.size() - 4; p += 4) {
                            int remoteDeviceID = Integer.parseInt((String) address.get(p));
                            ObjectIdentifier objIdentifier = new ObjectIdentifier(
                                    new ObjectType(Integer.parseInt((String) address.get(p + 1))),
                                    Integer.parseInt((String) address.get(p + 2)));
                            PropertyIdentifier propIdentifier = new PropertyIdentifier(
                                    Integer.parseInt((String) address.get(p + 3)));
                            objectIdentifier[q] = objIdentifier;
                            propertyIdentifier[q] = propIdentifier;
                            bacnetDataPointInfo[q] = new BacnetDataPointInfo(remoteDeviceID, objIdentifier,
                                    propIdentifier);
                            q = q + 1;
                        }
                        Object[] args = new Object[q + 1];
                        args[0] = bacnetConnector;
                        //                        args[1] = Integer.parseInt(remoteDeviceID);
                        for (int p = 0; p < bacnetDataPointInfo.length; p++) {
                            args[1 + p] = bacnetDataPointInfo[p];
                        }

                        try {

                            Constructor<?>[] declaredConstructors = Class.forName(type)
                                    .getDeclaredConstructors();
                            for (int k = 0; k < declaredConstructors.length; k++) {
                                if (declaredConstructors[k].getParameterTypes().length == args.length) { // constructor
                                    // that
                                    // takes
                                    // the
                                    // KNX
                                    // connector
                                    // and
                                    // group
                                    // address
                                    // as
                                    // argument
                                    Obj bacnetDevice = (Obj) declaredConstructors[k].newInstance(args); // create
                                    // a
                                    // instance
                                    // of
                                    // the
                                    // specified
                                    // KNX
                                    // device
                                    bacnetDevice.setHref(
                                            new Uri(URLEncoder.encode(connectorName, "UTF-8") + "/" + href));

                                    if (name != null && name.length() > 0) {
                                        bacnetDevice.setName(name);
                                    }

                                    if (displayName != null && displayName.length() > 0) {
                                        bacnetDevice.setDisplayName(displayName);
                                    }

                                    if (ipv6 != null) {
                                        objectBroker.addObj(bacnetDevice, ipv6);
                                    } else {
                                        objectBroker.addObj(bacnetDevice);
                                    }

                                    myObjects.add(bacnetDevice);

                                    bacnetDevice.initialize();

                                    if (historyEnabled != null && historyEnabled) {
                                        if (historyCount != null && historyCount != 0) {
                                            objectBroker.addHistoryToDatapoints(bacnetDevice, historyCount);
                                        } else {
                                            objectBroker.addHistoryToDatapoints(bacnetDevice);
                                        }
                                    }

                                    if (refreshEnabled != null && refreshEnabled) {
                                        objectBroker.enableObjectRefresh(bacnetDevice);
                                    }

                                    if (groupCommEnabled != null && groupCommEnabled) {
                                        objectBroker.enableGroupComm(bacnetDevice);
                                    }
                                }
                            }
                        } catch (SecurityException e) {
                            e.printStackTrace();
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    return connectors;
}

From source file:org.ambraproject.service.user.UserServiceImpl.java

@Override
@SuppressWarnings("unchecked")
public List<UserAlert> getAvailableAlerts() {
    List<UserAlert> alerts = new ArrayList<UserAlert>();

    final SortedMap<Integer, Pair> categoryNames = new ConcurrentSkipListMap<Integer, Pair>();

    HierarchicalConfiguration hc = (HierarchicalConfiguration) configuration;
    List<HierarchicalConfiguration> categories = hc.configurationsAt(ALERTS_CATEGORIES_CATEGORY);

    for (HierarchicalConfiguration c : categories) {
        String key = c.getString("[@key]");
        int order = c.getInt("[@displayOrder]", categoryNames.size());
        String value = c.getString("");

        categoryNames.put(order, new Pair<String, String>(key, value));
    }//from  w  w w .ja  va 2  s .c om

    final String[] weeklyCategories = hc.getStringArray(ALERTS_WEEKLY);
    final String[] monthlyCategories = hc.getStringArray(ALERTS_MONTHLY);
    final String[] subjectFilters = hc.getStringArray(SUBJECT_FILTER);

    final Set<Map.Entry<Integer, Pair>> categoryNamesSet = categoryNames.entrySet();

    for (final Map.Entry<Integer, Pair> category : categoryNamesSet) {
        final String key = (String) category.getValue().getFirst();
        boolean weeklyCategoryKey = false;
        boolean monthlyCategoryKey = false;
        boolean subjectFilter = false;

        if (ArrayUtils.contains(weeklyCategories, key)) {
            weeklyCategoryKey = true;
        }
        if (ArrayUtils.contains(monthlyCategories, key)) {
            monthlyCategoryKey = true;
        }
        if (ArrayUtils.contains(subjectFilters, key)) {
            subjectFilter = true;
        }

        alerts.add(
                new UserAlert((String) category.getValue().getFirst(), (String) category.getValue().getSecond(),
                        weeklyCategoryKey, monthlyCategoryKey, subjectFilter));
    }
    return alerts;
}

From source file:org.apache.james.dnsservice.dnsjava.DNSJavaService.java

@Override
public void configure(HierarchicalConfiguration configuration) throws ConfigurationException {

    boolean autodiscover = configuration.getBoolean("autodiscover", true);

    List<Name> sPaths = new ArrayList<Name>();
    if (autodiscover) {
        logger.info("Autodiscovery is enabled - trying to discover your system's DNS Servers");
        String[] serversArray = ResolverConfig.getCurrentConfig().servers();
        if (serversArray != null) {
            for (String aServersArray : serversArray) {
                dnsServers.add(aServersArray);
                logger.info("Adding autodiscovered server " + aServersArray);
            }/*from  w  ww.  j  av  a2  s  . c  o  m*/
        }
        Name[] systemSearchPath = ResolverConfig.getCurrentConfig().searchPath();
        if (systemSearchPath != null && systemSearchPath.length > 0) {
            sPaths.addAll(Arrays.asList(systemSearchPath));
        }
        if (logger.isInfoEnabled()) {
            for (Name searchPath : sPaths) {
                logger.info("Adding autodiscovered search path " + searchPath.toString());
            }
        }
    }

    // singleIPPerMX = configuration.getBoolean( "singleIPperMX", false );

    setAsDNSJavaDefault = configuration.getBoolean("setAsDNSJavaDefault", true);

    // Get the DNS servers that this service will use for lookups
    Collections.addAll(dnsServers, configuration.getStringArray("servers.server"));

    // Get the DNS servers that this service will use for lookups
    for (String aSearchPathsConfiguration : configuration.getStringArray("searchpaths.searchpath")) {
        try {
            sPaths.add(Name.fromString(aSearchPathsConfiguration));
        } catch (TextParseException e) {
            throw new ConfigurationException("Unable to parse searchpath host: " + aSearchPathsConfiguration,
                    e);
        }
    }

    searchPaths = sPaths.toArray(new Name[sPaths.size()]);

    if (dnsServers.isEmpty()) {
        logger.info("No DNS servers have been specified or found by autodiscovery - adding 127.0.0.1");
        dnsServers.add("127.0.0.1");
    }

    boolean authoritative = configuration.getBoolean("authoritative", false);
    // TODO: Check to see if the credibility field is being used correctly.
    // From the
    // docs I don't think so
    dnsCredibility = authoritative ? Credibility.AUTH_ANSWER : Credibility.NONAUTH_ANSWER;

    maxCacheSize = configuration.getInt("maxcachesize", maxCacheSize);
}

From source file:org.apache.james.imapserver.netty.IMAPServer.java

@Override
public void doConfigure(HierarchicalConfiguration configuration) throws ConfigurationException {

    super.doConfigure(configuration);

    hello = softwaretype + " Server " + getHelloName() + " is ready.";
    compress = configuration.getBoolean("compress", false);
    maxLineLength = configuration.getInt("maxLineLength", DEFAULT_MAX_LINE_LENGTH);
    inMemorySizeLimit = configuration.getInt("inMemorySizeLimit", DEFAULT_IN_MEMORY_SIZE_LIMIT);
    literalSizeLimit = configuration.getInt("literalSizeLimit", DEFAULT_LITERAL_SIZE_LIMIT);

    plainAuthDisallowed = configuration.getBoolean("plainAuthDisallowed", false);
    timeout = configuration.getInt("timeout", DEFAULT_TIMEOUT);
    if (timeout < DEFAULT_TIMEOUT) {
        throw new ConfigurationException("Minimum timeout of 30 minutes required. See rfc2060 5.4 for details");
    }//ww w  . j  a  v a 2s.com

    if (timeout < 0) {
        timeout = 0;
    }

}

From source file:org.apache.james.mailetcontainer.impl.JamesMailSpooler.java

/**
 * @see org.apache.james.lifecycle.api.Configurable#configure(org.apache.commons.configuration.HierarchicalConfiguration)
 *//* w w w. j a v  a  2  s  . c o  m*/
public void configure(HierarchicalConfiguration config) throws ConfigurationException {
    numDequeueThreads = config.getInt("dequeueThreads", 2);

    numThreads = config.getInt("threads", 100);
}

From source file:org.apache.james.mailrepository.jdbc.JDBCMailRepository.java

protected void doConfigure(HierarchicalConfiguration configuration) throws ConfigurationException {
    super.doConfigure(configuration);
    if (getLogger().isDebugEnabled()) {
        getLogger().debug(this.getClass().getName() + ".configure()");
    }//w w  w  .j  a  v a  2  s .  co  m
    destination = configuration.getString("[@destinationURL]");

    // normalize the destination, to simplify processing.
    if (!destination.endsWith("/")) {
        destination += "/";
    }
    // Parse the DestinationURL for the name of the datasource,
    // the table to use, and the (optional) repository Key.
    // Split on "/", starting after "db://"
    List<String> urlParams = new ArrayList<String>();
    int start = 5;
    if (destination.startsWith("dbfile")) {
        // this is dbfile:// instead of db://
        start += 4;
    }
    int end = destination.indexOf('/', start);
    while (end > -1) {
        urlParams.add(destination.substring(start, end));
        start = end + 1;
        end = destination.indexOf('/', start);
    }

    // Build SqlParameters and get datasource name from URL parameters
    if (urlParams.size() == 0) {
        String exceptionBuffer = "Malformed destinationURL - Must be of the format '"
                + "db://<data-source>[/<table>[/<repositoryName>]]'.  Was passed "
                + configuration.getString("[@destinationURL]");
        throw new ConfigurationException(exceptionBuffer);
    }
    if (urlParams.size() >= 1) {
        datasourceName = urlParams.get(0);
    }
    if (urlParams.size() >= 2) {
        tableName = urlParams.get(1);
    }
    if (urlParams.size() >= 3) {
        repositoryName = "";
        for (int i = 2; i < urlParams.size(); i++) {
            if (i >= 3) {
                repositoryName += '/';
            }
            repositoryName += urlParams.get(i);
        }
    }

    if (getLogger().isDebugEnabled()) {
        String logBuffer = "Parsed URL: table = '" + tableName + "', repositoryName = '" + repositoryName + "'";
        getLogger().debug(logBuffer);
    }

    inMemorySizeLimit = configuration.getInt("inMemorySizeLimit", 409600000);

    filestore = configuration.getString("filestore", null);
    sqlFileName = configuration.getString("sqlFile");

}

From source file:org.apache.james.protocols.lib.netty.AbstractConfigurableAsyncServer.java

/**
 * @see//from w w  w . j ava 2  s.c  om
 * org.apache.james.lifecycle.api.Configurable
 * #configure(org.apache.commons.configuration.HierarchicalConfiguration)
 */
public final void configure(HierarchicalConfiguration config) throws ConfigurationException {

    enabled = config.getBoolean("[@enabled]", true);

    final Logger logger = getLogger();
    if (!enabled) {
        logger.info(getServiceType() + " disabled by configuration");
        return;
    }

    String listen[] = config.getString("bind", "0.0.0.0:" + getDefaultPort()).split(",");
    List<InetSocketAddress> bindAddresses = new ArrayList<InetSocketAddress>();
    for (String aListen : listen) {
        String bind[] = aListen.split(":");

        InetSocketAddress address;
        String ip = bind[0].trim();
        int port = Integer.parseInt(bind[1].trim());
        if (!ip.equals("0.0.0.0")) {
            try {
                ip = InetAddress.getByName(ip).getHostName();
            } catch (UnknownHostException unhe) {
                throw new ConfigurationException(
                        "Malformed bind parameter in configuration of service " + getServiceType(), unhe);
            }
        }
        address = new InetSocketAddress(ip, port);

        String infoBuffer = getServiceType() + " bound to: " + ip + ":" + port;
        logger.info(infoBuffer);

        bindAddresses.add(address);
    }
    setListenAddresses(bindAddresses.toArray(new InetSocketAddress[bindAddresses.size()]));

    jmxName = config.getString("jmxName", getDefaultJMXName());
    int ioWorker = config.getInt("ioWorkerCount", DEFAULT_IO_WORKER_COUNT);
    setIoWorkerCount(ioWorker);

    maxExecutorThreads = config.getInt("maxExecutorCount", DEFAULT_MAX_EXECUTOR_COUNT);

    configureHelloName(config);

    setTimeout(config.getInt(TIMEOUT_NAME, DEFAULT_TIMEOUT));

    StringBuilder infoBuffer = new StringBuilder(64).append(getServiceType())
            .append(" handler connection timeout is: ").append(getTimeout());
    logger.info(infoBuffer.toString());

    setBacklog(config.getInt(BACKLOG_NAME, DEFAULT_BACKLOG));

    infoBuffer = new StringBuilder(64).append(getServiceType()).append(" connection backlog is: ")
            .append(getBacklog());
    logger.info(infoBuffer.toString());

    String connectionLimitString = config.getString("connectionLimit", null);
    if (connectionLimitString != null) {
        try {
            connectionLimit = new Integer(connectionLimitString);
        } catch (NumberFormatException nfe) {
            logger.error("Connection limit value is not properly formatted.", nfe);
        }
        if (connectionLimit < 0) {
            logger.error("Connection limit value cannot be less than zero.");
            throw new ConfigurationException("Connection limit value cannot be less than zero.");
        } else if (connectionLimit > 0) {
            infoBuffer = new StringBuilder(128).append(getServiceType()).append(" will allow a maximum of ")
                    .append(connectionLimitString).append(" connections.");
            logger.info(infoBuffer.toString());
        }
    }

    String connectionLimitPerIP = config.getString("connectionLimitPerIP", null);
    if (connectionLimitPerIP != null) {
        try {
            connPerIP = Integer.parseInt(connectionLimitPerIP);
        } catch (NumberFormatException nfe) {
            logger.error("Connection limit per IP value is not properly formatted.", nfe);
        }
        if (connPerIP < 0) {
            logger.error("Connection limit per IP value cannot be less than zero.");
            throw new ConfigurationException("Connection limit value cannot be less than zero.");
        } else if (connPerIP > 0) {
            infoBuffer = new StringBuilder(128).append(getServiceType()).append(" will allow a maximum of ")
                    .append(connPerIP).append(" per IP connections for ").append(getServiceType());
            logger.info(infoBuffer.toString());
        }
    }

    useStartTLS = config.getBoolean("tls.[@startTLS]", false);
    useSSL = config.getBoolean("tls.[@socketTLS]", false);

    if (useSSL && useStartTLS)
        throw new ConfigurationException("startTLS is only supported when using plain sockets");

    if (useStartTLS || useSSL) {
        enabledCipherSuites = config.getStringArray("tls.supportedCipherSuites.cipherSuite");
        keystore = config.getString("tls.keystore", null);
        if (keystore == null) {
            throw new ConfigurationException("keystore needs to get configured");
        }
        secret = config.getString("tls.secret", "");
        x509Algorithm = config.getString("tls.algorithm", defaultX509algorithm);
    }

    doConfigure(config);

}

From source file:org.apache.james.rrt.lib.AbstractRecipientRewriteTable.java

/**
 * @see org.apache.james.lifecycle.api.Configurable#configure(HierarchicalConfiguration)
 *//*from w ww  .java2 s .c om*/
public void configure(HierarchicalConfiguration config) throws ConfigurationException {
    setRecursiveMapping(config.getBoolean("recursiveMapping", true));
    try {
        setMappingLimit(config.getInt("mappingLimit", 10));
    } catch (IllegalArgumentException e) {
        throw new ConfigurationException(e.getMessage());
    }
    doConfigure(config);
}