List of usage examples for org.apache.commons.configuration HierarchicalConfiguration getProperty
public Object getProperty(String key)
From source file:at.ac.tuwien.auto.iotsys.gateway.connectors.knx.KNXDeviceLoaderETSImpl.java
private void parseEntites(KNXConnector knxConnector, ObjectBroker objectBroker, Hashtable<String, EntityImpl> entityById, Hashtable<String, DatapointImpl> datapointById, NetworkImpl n, Hashtable<String, String> resourceById, Hashtable<String, String> groupAddressByDatapointID, boolean enableGroupComm, boolean enableHistories) { for (int entityIdx = 0; entityIdx < sizeOfConfiguration( devicesConfig.getProperty("entities.entity[@id]")); entityIdx++) { // Entity HierarchicalConfiguration entityConfig = devicesConfig .configurationAt("entities.entity(" + entityIdx + ")"); String entityId = entityConfig.getString("[@id]"); String entityName = arrayToString(entityConfig.getStringArray("[@name]")); String entityDescription = arrayToString(entityConfig.getStringArray("[@description]")); String entityOrderNumber = entityConfig.getString("[@orderNumber]"); String entityManufacturerId = entityConfig.getString("[@manufacturerId]"); EntityImpl entity = new EntityImpl(entityId, entityName, entityDescription, resourceById.get(entityManufacturerId), entityOrderNumber); entityById.put(entityId, entity); n.getEntities().addEntity(entity); objectBroker.addObj(entity, true); // Translations for (int transIdx = 0; transIdx < sizeOfConfiguration( entityConfig.getProperty("translations.translation[@language]")); transIdx++) { HierarchicalConfiguration transConfig = entityConfig .configurationAt("translations.translation(" + transIdx + ")"); String language = transConfig.getString("[@language]"); String attribute = transConfig.getString("[@attribute]"); String value = arrayToString(transConfig.getStringArray("[@value]")); try { entity.addTranslation(language, attribute, value); } catch (Exception e) { log.warning(e.getMessage()); }/*from w w w . j a v a2 s . co m*/ } // DPs for (int datapointIdx = 0; datapointIdx < sizeOfConfiguration( entityConfig.getProperty("datapoints.datapoint[@id]")); datapointIdx++) { HierarchicalConfiguration datapointConfig = entityConfig .configurationAt("datapoints.datapoint(" + datapointIdx + ")"); String dataPointName = arrayToString(datapointConfig.getStringArray("[@name]")); String dataPointTypeIds = datapointConfig.getString("[@datapointTypeIds]"); String dataPointId = datapointConfig.getString("[@id]"); String dataPointDescription = arrayToString(datapointConfig.getStringArray("[@description]")); String dataPointWriteFlag = datapointConfig.getString("[@writeFlag]"); String dataPointReadFlag = datapointConfig.getString("[@readFlag]"); // String dataPointPriority = datapointConfig.getString("[@priority]"); // String dataPointCommunicationFlag = datapointConfig.getString("[@communicationFlag]"); // String dataPointReadOnInitFlag = datapointConfig.getString("[@readOnInitFlag]"); // String dataPointTransmitFlag = datapointConfig.getString("[@transmitFlag]"); // String updateFlag = datapointConfig.getString("[@updateFlag]"); // use only the first DPTS if (dataPointTypeIds.indexOf(" ") >= 0) { dataPointTypeIds = dataPointTypeIds.substring(0, dataPointTypeIds.indexOf(" ")); } log.info("Found data point type id: " + dataPointTypeIds); String clazzName = "at.ac.tuwien.auto.iotsys.gateway.obix.objects.knx.datapoint.impl." + dataPointTypeIds.replace('-', '_') + "_ImplKnx"; Class<?> clazz = null; try { log.info("Loading: " + clazzName); clazz = Class.forName(clazzName); } catch (ClassNotFoundException e) { log.warning(clazzName + " not found. Cannot instantiate according sub data point type. Trying fallback to generic main type."); int firstIndexOf = dataPointTypeIds.indexOf('-'); int secondIndexOf = dataPointTypeIds.indexOf('-', firstIndexOf + 1); clazzName = "at.ac.tuwien.auto.iotsys.gateway.obix.objects.knx.datapoint.impl." + "DPT_" + dataPointTypeIds.substring(firstIndexOf + 1, secondIndexOf) + "_ImplKnx"; // try { log.info("Loading: " + clazzName); clazz = Class.forName(clazzName); } catch (ClassNotFoundException e1) { e1.printStackTrace(); log.warning(clazzName + " not found. Cannot instantiate according main data point type."); } } try { if (clazz != null) { Constructor<?> constructor = clazz.getConstructor(KNXConnector.class, DataPointInit.class); Object[] object = new Object[2]; object[0] = knxConnector; DataPointInit dptInit = new DataPointInit(); dptInit.setDisplay(dataPointDescription); dptInit.setDisplayName(dataPointName); dptInit.setReadable( EnumsImpl.getInstance().getEnum(EnumEnabled.HREF).getBool(dataPointReadFlag)); dptInit.setName(dataPointId); dptInit.setGroupAddress( new GroupAddress(Integer.parseInt(groupAddressByDatapointID.get(dataPointId)))); dptInit.setWritable( EnumsImpl.getInstance().getEnum(EnumEnabled.HREF).getBool(dataPointWriteFlag)); object[1] = dptInit; DatapointImpl dataPoint = (DatapointImpl) constructor.newInstance(object); datapointById.put(dataPointId, dataPoint); entity.addDatapoint(dataPoint); if (enableGroupComm) objectBroker.enableGroupComm(dataPoint); if (enableHistories) objectBroker.addHistoryToDatapoints(dataPoint); objectBroker.addObj(dataPoint, true); // Search for child "value" Obj dpValue = dataPoint.get("value"); if (dpValue != null) { dpValue.setDisplayName(dataPointDescription); } // Translations (DP) for (int transIdx = 0; transIdx < sizeOfConfiguration( datapointConfig.getProperty("translations.translation[@language]")); transIdx++) { HierarchicalConfiguration transConfig = datapointConfig .configurationAt("translations.translation(" + transIdx + ")"); String language = transConfig.getString("[@language]"); String attribute = transConfig.getString("[@attribute]"); String value = arrayToString(transConfig.getStringArray("[@value]")); try { dataPoint.addTranslation(language, attribute, value); // translation for DisplayName of value if (attribute.toLowerCase().trim().equals("description") && dpValue != null) { dpValue.addTranslation(language, TranslationAttribute.displayName, value); } } catch (Exception e) { log.warning(e.getMessage()); } } } } catch (NoSuchMethodException e) { log.warning(clazzName + " no such method. Cannot instantiate according datapoint."); } catch (SecurityException e) { log.warning(clazzName + " security exception. Cannot instantiate according datapoint."); } catch (InstantiationException e) { log.warning(clazzName + " instantiation exception. Cannot instantiate according datapoint."); } catch (IllegalAccessException e) { log.warning(clazzName + " illegal access exception. Cannot instantiate according datapoint."); } catch (IllegalArgumentException e) { log.warning(clazzName + " illegal argument exception. Cannot instantiate according datapoint."); e.printStackTrace(); } catch (InvocationTargetException e) { log.warning( clazzName + " invocation target exception. Cannot instantiate according datapoint."); e.printStackTrace(); } } } }
From source file:net.fenyo.gnetwatch.GUI.GUI.java
/** * Parses a configuration file to create initial targets. * @param filename configuration file. * @return void./*w ww. j a va 2 s . c o m*/ */ public void createFromXML(final String filename) { final GUI gui = this; asyncExec(new Runnable() { public void run() { synchronized (synchro) { final Session session = synchro.getSessionFactory().getCurrentSession(); session.beginTransaction(); try { final XMLConfiguration initial = new XMLConfiguration(filename); initial.setExpressionEngine(new XPathExpressionEngine()); // limitation de l'implmentation : on n'autorise que les parents de type groupe for (final HierarchicalConfiguration subconf : (java.util.List<HierarchicalConfiguration>) initial .configurationsAt("/objects/target")) { if (subconf.getProperty("@targetType").equals("group")) { final String name = subconf.getString("name"); final java.util.List<String> parents = (java.util.List<String>) subconf .getList("parent[@parentType='group']"); if (parents.size() == 0) { final TargetGroup target_group = new TargetGroup( "added by initial configuration", name); target_group.addTarget(gui, user_defined); } else for (final String parent : parents) { final TargetGroup foo = new TargetGroup("temporary", parent); final TargetGroup target_parent = (TargetGroup) getCanonicalInstance(foo); if (target_parent == foo) log.error("Initial configuration: parent does not exist"); else { final TargetGroup target_group = new TargetGroup( "added by initial configuration", name); target_group.addTarget(gui, target_parent); } } } if (subconf.getProperty("@targetType").equals("ipv4")) { final String address = subconf.getString("address"); java.util.List<String> parents = (java.util.List<String>) subconf .getList("parent[@parentType='group']"); if (parents.size() != 0) for (final String parent : parents) { final TargetGroup foo = new TargetGroup("temporary", parent); final TargetGroup target_parent = (TargetGroup) getCanonicalInstance(foo); if (target_parent == foo) log.error("Initial configuration: parent does not exist"); else { final TargetIPv4 target = new TargetIPv4( "added by initial configuration", GenericTools.stringToInet4Address(address), snmp_manager); target.addTarget(gui, target_parent); if (subconf.getString("snmp/version") != null) { if (subconf.getString("snmp/version").equals("v1")) target.getSNMPQuerier().setVersion(0); if (subconf.getString("snmp/version").equals("v2c")) target.getSNMPQuerier().setVersion(1); if (subconf.getString("snmp/version").equals("v3")) target.getSNMPQuerier().setVersion(2); } if (subconf.getString("snmp/community") != null) target.getSNMPQuerier() .setCommunity(subconf.getString("snmp/community")); // Setting the agent is not possible when creating a target through the GUI if (subconf.getString("snmp/agent") != null) target.getSNMPQuerier().setAddress(GenericTools .stringToInet4Address(subconf.getString("snmp/agent"))); if (subconf.getString("snmp/password-auth") != null) target.getSNMPQuerier() .setPasswordAuth(subconf.getString("snmp/password-auth")); if (subconf.getString("snmp/password-priv") != null) target.getSNMPQuerier() .setPasswordPriv(subconf.getString("snmp/password-priv")); if (subconf.getString("snmp/pdu-max-size") != null) target.getSNMPQuerier() .setPDUMaxSize(subconf.getInt("snmp/pdu-max-size")); if (subconf.getString("snmp/port") != null) target.getSNMPQuerier().setPort(subconf.getInt("snmp/port")); if (subconf.getString("snmp/retries") != null) target.getSNMPQuerier().setRetries(subconf.getInt("snmp/retries")); if (subconf.getString("snmp/security") != null && subconf.getString("snmp/security").equals("NOAUTH_NOPRIV")) target.getSNMPQuerier().setSec(SecurityLevel.NOAUTH_NOPRIV); if (subconf.getString("snmp/security") != null && subconf.getString("snmp/security").equals("AUTH_NOPRIV")) target.getSNMPQuerier().setSec(SecurityLevel.AUTH_NOPRIV); if (subconf.getString("snmp/security") != null && subconf.getString("snmp/security").equals("AUTH_PRIV")) target.getSNMPQuerier().setSec(SecurityLevel.AUTH_PRIV); if (subconf.getString("snmp/timeout") != null) target.getSNMPQuerier().setTimeout(subconf.getInt("snmp/timeout")); target.getSNMPQuerier().update(); } } } if (subconf.getProperty("@targetType").equals("ipv6")) { final String address = subconf.getString("address"); java.util.List<String> parents = (java.util.List<String>) subconf .getList("parent[@parentType='group']"); if (parents.size() != 0) for (final String parent : parents) { final TargetGroup foo = new TargetGroup("temporary", parent); final TargetGroup target_parent = (TargetGroup) getCanonicalInstance(foo); if (target_parent == foo) log.error("Initial configuration: parent does not exist"); else { final TargetIPv6 target = new TargetIPv6( "added by initial configuration", GenericTools.stringToInet6Address(address), snmp_manager); target.addTarget(gui, target_parent); } } } if (subconf.getProperty("@targetType").equals("ipv4range")) { final String begin = subconf.getString("begin"); final String end = subconf.getString("end"); java.util.List<String> parents = (java.util.List<String>) subconf .getList("parent[@parentType='group']"); if (parents.size() != 0) for (final String parent : parents) { final TargetGroup foo = new TargetGroup("temporary", parent); final TargetGroup target_parent = (TargetGroup) getCanonicalInstance(foo); if (target_parent == foo) log.error("Initial configuration: parent does not exist"); else { final TargetIPv4Range target = new TargetIPv4Range( "added by initial configuration", GenericTools.stringToInet4Address(begin), GenericTools.stringToInet4Address(end)); target.addTarget(gui, target_parent); } } } if (subconf.getProperty("@targetType").equals("ipv4subnet")) { final String network = subconf.getString("network"); final String netmask = subconf.getString("netmask"); java.util.List<String> parents = (java.util.List<String>) subconf .getList("parent[@parentType='group']"); if (parents.size() != 0) for (final String parent : parents) { final TargetGroup foo = new TargetGroup("temporary", parent); final TargetGroup target_parent = (TargetGroup) getCanonicalInstance(foo); if (target_parent == foo) log.error("Initial configuration: parent does not exist"); else { final TargetIPv4Subnet target = new TargetIPv4Subnet( "added by initial configuration", GenericTools.stringToInet4Address(network), GenericTools.stringToInet4Address(netmask)); target.addTarget(gui, target_parent); } } } } session.getTransaction().commit(); } catch (final ConfigurationException ex) { log.warn("Exception", ex); session.getTransaction().rollback(); } catch (final AlgorithmException ex) { log.error("Exception", ex); session.getTransaction().rollback(); } catch (final UnknownHostException ex) { log.error("Exception", ex); session.getTransaction().rollback(); } } } }); }
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 a v a 2 s . 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:org.apache.james.utils.FileConfigurationProviderTest.java
@Test public void getConfigurationShouldLoadCorrespondingXMLFile() throws Exception { HierarchicalConfiguration hierarchicalConfiguration = configurationProvider .getConfiguration(ROOT_CONFIG_KEY); assertThat(hierarchicalConfiguration.getKeys()).containsOnly(CONFIG_KEY_1, String.join(CONFIG_SEPARATOR, CONFIG_KEY_4, CONFIG_KEY_2), String.join(CONFIG_SEPARATOR, CONFIG_KEY_4, CONFIG_KEY_5, CONFIG_KEY_2)); assertThat(hierarchicalConfiguration.getProperty(CONFIG_KEY_1)).isEqualTo(VALUE_1); }
From source file:org.apache.james.utils.FileConfigurationProviderTest.java
@Test public void getConfigurationShouldLoadCorrespondingXMLFilePart() throws Exception { HierarchicalConfiguration hierarchicalConfiguration = configurationProvider .getConfiguration(String.join(CONFIG_SEPARATOR, ROOT_CONFIG_KEY, CONFIG_KEY_4)); assertThat(hierarchicalConfiguration.getKeys()).containsOnly(CONFIG_KEY_2, String.join(CONFIG_SEPARATOR, CONFIG_KEY_5, CONFIG_KEY_2)); assertThat(hierarchicalConfiguration.getProperty(CONFIG_KEY_2)).isEqualTo(VALUE_2); }
From source file:org.apache.james.utils.FileConfigurationProviderTest.java
@Test public void getConfigurationShouldLoadCorrespondingXMLFileWhenAPathIsProvidedPart() throws Exception { HierarchicalConfiguration hierarchicalConfiguration = configurationProvider .getConfiguration(String.join(CONFIG_SEPARATOR, ROOT_CONFIG_KEY, CONFIG_KEY_4, CONFIG_KEY_5)); assertThat(hierarchicalConfiguration.getKeys()).containsOnly(CONFIG_KEY_2); assertThat(hierarchicalConfiguration.getProperty(CONFIG_KEY_2)).isEqualTo(VALUE_3); }
From source file:org.apache.james.utils.FileConfigurationProviderTest.java
@Test public void multiplesSeparatorsShouldBeTolerated() throws Exception { HierarchicalConfiguration hierarchicalConfiguration = configurationProvider .getConfiguration(ROOT_CONFIG_KEY + CONFIG_SEPARATOR + CONFIG_SEPARATOR + CONFIG_KEY_4); assertThat(hierarchicalConfiguration.getKeys()).containsOnly(CONFIG_KEY_2, String.join(CONFIG_SEPARATOR, CONFIG_KEY_5, CONFIG_KEY_2)); assertThat(hierarchicalConfiguration.getProperty(CONFIG_KEY_2)).isEqualTo(VALUE_2); }
From source file:org.kepler.configuration.SerializationComparisonTest.java
/** * test the commons interface for reading properties *///from ww w .j ava 2s . co m public void testCommonsRead() { try { File f = new File("configuration-manager/resources/configurations/configuration.xml"); assertTrue(f.exists()); XMLConfiguration config = new XMLConfiguration(f); //get the conditionals of query and read some properties ArrayList al = (ArrayList) config .getProperty("ecogridService.queryList.query.AND.OR.condition.concept"); assertTrue(config.getString("ecogridService.queryList.query.AND.OR.condition(1).concept") .equals("keyword")); assertTrue( config.getString("ecogridService.queryList.query.AND.OR.condition(3).operator").equals("LIKE")); //break the config down into a smaller subset of just the queryList HierarchicalConfiguration sub = config.configurationAt("ecogridService.queryList"); al = (ArrayList) sub.getProperty("query.returnField"); al = (ArrayList) sub.getProperty("query(0).returnField"); //get the 2nd returnfield of the first query assertTrue(((String) al.get(1)).equals("entityName")); } catch (Exception e) { e.printStackTrace(); fail("Commons error: " + e.getMessage()); } System.out.println(); System.out.println(); }
From source file:org.onosproject.driver.netconf.XmlConfigParser.java
protected static String parseSwitchId(HierarchicalConfiguration cfg) { HierarchicalConfiguration field = cfg .configurationAt("data.capable-switch." + "logical-switches." + "switch"); return field.getProperty("id").toString(); }
From source file:org.onosproject.driver.netconf.XmlConfigParser.java
protected static String parseCapableSwitchId(HierarchicalConfiguration cfg) { HierarchicalConfiguration field = cfg.configurationAt("data.capable-switch"); return field.getProperty("id").toString(); }