List of usage examples for org.apache.commons.configuration HierarchicalConfiguration setProperty
public void setProperty(String key, Object value)
From source file:com.houghtonassociates.bamboo.plugins.view.GitWebRepositoryViewer.java
@NotNull @Override/*from w w w. j av a 2s .c o m*/ public HierarchicalConfiguration toConfiguration() { HierarchicalConfiguration configuration = super.toConfiguration(); configuration.setProperty(GITWEB_REPOSITORY_NAME, getWebRepositoryRepoName()); configuration.setProperty(GITWEB_REPOSITORY_PATH, getWebRepositoryPath()); configuration.setProperty(GITWEB_REPOSITORY_URL, com.atlassian.bamboo.util.UrlUtils.correctlyFormatUrl(getWebRepositoryUrl())); return configuration; }
From source file:i2p.bote.imap.ImapService.java
public ImapService(Configuration configuration, final PasswordVerifier passwordVerifier, EmailFolderManager folderManager) throws ConfigurationException { this.folderManager = folderManager; setLog(LoggerFactory.getLogger(ImapService.class)); // Set up the keystore for the SSL certificate sslKeyStore = configuration.getSSLKeyStoreFile(); setFileSystem(new FileSystem() { @Override//from w ww . j ava 2 s .c om public InputStream getResource(String resource) throws IOException { return null; } @Override public File getFile(String fileURL) throws FileNotFoundException { if (fileURL.equals(SSL_KEYSTORE_FILE)) return sslKeyStore; return null; } @Override public File getBasedir() throws FileNotFoundException { return null; } }); HierarchicalConfiguration cfg = new HierarchicalConfiguration(); SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket s = null; try { // Create an unconnected socket for getting supported cipher suites s = (SSLSocket) sf.createSocket(); // enable STARTTLS using the above keystore cfg.setProperty("tls.[@startTLS]", true); cfg.setProperty("tls.keystore", SSL_KEYSTORE_FILE); cfg.setProperty("tls.secret", configuration.getSSLKeyStorePassword()); // select strong cipher suites cfg.setProperty("tls.supportedCipherSuites.cipherSuite", StrongTls.getRecommendedCipherSuites(s.getSupportedCipherSuites())); } catch (IOException e) { log.error("Couldn't determine supported cipher suites", e); } finally { if (s != null) try { s.close(); } catch (IOException e) { } } configure(cfg); // use the defaults for the rest setListenAddresses(new InetSocketAddress(configuration.getImapAddress(), configuration.getImapPort())); mailboxSessionMapperFactory = new MapperFactory(folderManager); MailboxACLResolver aclResolver = createMailboxACLResolver(); GroupMembershipResolver groupMembershipResolver = new GroupMembershipResolver() { public boolean isMember(String user, String group) { return true; } }; Authenticator authenticator = createAuthenticator(passwordVerifier); StoreMailboxManager<String> mailboxManager = new StoreMailboxManager<String>(mailboxSessionMapperFactory, authenticator, aclResolver, groupMembershipResolver); mailboxManager.setDelegatingMailboxListener(new HashMapDelegatingMailboxListener()); mailboxManager.setMailboxSessionIdGenerator(new RandomMailboxSessionIdGenerator()); SubscriptionManager subscriptionManager = createSubscriptionManager(); ImapProcessor processor = DefaultImapProcessorFactory.createDefaultProcessor(mailboxManager, subscriptionManager); setImapProcessor(processor); setImapEncoder(DefaultImapEncoderFactory.createDefaultEncoder(new Localizer() { public String localize(HumanReadableText text, Locales locales) { return text.getDefaultValue(); } }, true)); setImapDecoder(DefaultImapDecoderFactory.createDecoder()); }
From source file:com.eyeq.pivot4j.ui.condition.CellValueCondition.java
/** * @see com.eyeq.pivot4j.ui.condition.AbstractCondition#saveSettings(org.apache.commons.configuration.HierarchicalConfiguration) *//*from w w w . j a va2s . c om*/ @Override public void saveSettings(HierarchicalConfiguration configuration) { super.saveSettings(configuration); if (criteria != null) { configuration.addProperty("criteria", criteria.name()); } if (value != null) { configuration.addProperty("value", value); } if (positionUniqueNames != null) { int index = 0; for (String member : positionUniqueNames) { String name = String.format("position.member(%s)", index++); configuration.setProperty(name, member); } } }
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 w w . j a v 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:com.houghtonassociates.bamboo.plugins.GerritRepositoryAdapter.java
@Override public HierarchicalConfiguration toConfiguration() { HierarchicalConfiguration configuration = super.toConfiguration(); configuration.setProperty(REPOSITORY_GERRIT_REPOSITORY_HOSTNAME, hostname); configuration.setProperty(REPOSITORY_GERRIT_USERNAME, username); configuration.setProperty(REPOSITORY_GERRIT_EMAIL, userEmail); configuration.setProperty(REPOSITORY_GERRIT_PROJECT, project); if (!vcsBranch.equals(MASTER_BRANCH) && !vcsBranch.equals(ALL_BRANCH)) { configuration.setProperty(REPOSITORY_GERRIT_DEFAULT_BRANCH, CUSTOM_BRANCH_SET); configuration.setProperty(REPOSITORY_GERRIT_CUSTOM_BRANCH, vcsBranch.getName()); } else {//w w w.j a v a 2 s.c o m String br = vcsBranch.getName(); configuration.setProperty(REPOSITORY_GERRIT_DEFAULT_BRANCH, br); configuration.setProperty(REPOSITORY_GERRIT_CUSTOM_BRANCH, br); } configuration.setProperty(REPOSITORY_GERRIT_BRANCH, vcsBranch.getName()); configuration.setProperty(REPOSITORY_GERRIT_SSH_KEY, sshKey); configuration.setProperty(REPOSITORY_GERRIT_SSH_PASSPHRASE, encryptionService.encrypt(sshPassphrase)); configuration.setProperty(REPOSITORY_GERRIT_CONFIG_DIR, relativeConfigPath); configuration.setProperty(REPOSITORY_GERRIT_SSH_KEY_FILE, relativeSSHKeyFilePath); configuration.setProperty(REPOSITORY_GERRIT_REPOSITORY_PORT, port); configuration.setProperty(REPOSITORY_GERRIT_USE_SHALLOW_CLONES, useShallowClones); configuration.setProperty(REPOSITORY_GERRIT_USE_SUBMODULES, useSubmodules); configuration.setProperty(REPOSITORY_GERRIT_COMMAND_TIMEOUT, commandTimeout); configuration.setProperty(REPOSITORY_GERRIT_VERBOSE_LOGS, verboseLogs); return configuration; }
From source file:org.lab41.dendrite.rexster.DendriteRexsterApplication.java
private void configureScriptEngine() { // the EngineController needs to be configured statically before requests start serving so that it can // properly construct ScriptEngine objects with the correct reset policy. allow script engines to be // configured so that folks can drop in different gremlin flavors. HierarchicalConfiguration config = new HierarchicalConfiguration(); config.setProperty("name", "gremlin-groovy"); config.setProperty("reset-threshold", "-1"); List<String> imports = new ArrayList<>(); imports.add("com.tinkerpop.gremlin.*"); imports.add("com.tinkerpop.gremlin.java.*"); imports.add("com.tinkerpop.gremlin.pipes.filter.*"); imports.add("com.tinkerpop.gremlin.pipes.sideeffect.*"); imports.add("com.tinkerpop.gremlin.pipes.transform.*"); imports.add("com.tinkerpop.blueprints.*"); imports.add("com.tinkerpop.blueprints.impls.*"); imports.add("com.tinkerpop.blueprints.impls.tg.*"); imports.add("com.tinkerpop.blueprints.impls.neo4j.*"); imports.add("com.tinkerpop.blueprints.impls.neo4j.batch.*"); imports.add("com.tinkerpop.blueprints.impls.orient.*"); imports.add("com.tinkerpop.blueprints.impls.orient.batch.*"); imports.add("com.tinkerpop.blueprints.impls.dex.*"); imports.add("com.tinkerpop.blueprints.impls.rexster.*"); imports.add("com.tinkerpop.blueprints.impls.sail.*"); imports.add("com.tinkerpop.blueprints.impls.sail.impls.*"); imports.add("com.tinkerpop.blueprints.util.*"); imports.add("com.tinkerpop.blueprints.util.io.*"); imports.add("com.tinkerpop.blueprints.util.io.gml.*"); imports.add("com.tinkerpop.blueprints.util.io.graphml.*"); imports.add("com.tinkerpop.blueprints.util.io.graphson.*"); imports.add("com.tinkerpop.blueprints.util.wrappers.*"); imports.add("com.tinkerpop.blueprints.util.wrappers.batch.*"); imports.add("com.tinkerpop.blueprints.util.wrappers.batch.cache.*"); imports.add("com.tinkerpop.blueprints.util.wrappers.event.*"); imports.add("com.tinkerpop.blueprints.util.wrappers.event.listener.*"); imports.add("com.tinkerpop.blueprints.util.wrappers.id.*"); imports.add("com.tinkerpop.blueprints.util.wrappers.partition.*"); imports.add("com.tinkerpop.blueprints.util.wrappers.readonly.*"); imports.add("com.tinkerpop.blueprints.oupls.sail.*"); imports.add("com.tinkerpop.blueprints.oupls.sail.pg.*"); imports.add("com.tinkerpop.blueprints.oupls.jung.*"); imports.add("com.tinkerpop.pipes.*"); imports.add("com.tinkerpop.pipes.branch.*"); imports.add("com.tinkerpop.pipes.filter.*"); imports.add("com.tinkerpop.pipes.sideeffect.*"); imports.add("com.tinkerpop.pipes.transform.*"); imports.add("com.tinkerpop.pipes.util.*"); imports.add("com.tinkerpop.pipes.util.iterators.*"); imports.add("com.tinkerpop.pipes.util.structures.*"); imports.add("org.apache.commons.configuration.*"); imports.add("com.thinkaurelius.titan.core.*"); imports.add("com.thinkaurelius.titan.core.attribute.*"); imports.add("com.thinkaurelius.titan.core.util.*"); imports.add("com.thinkaurelius.titan.example.*"); imports.add("org.apache.commons.configuration.*"); imports.add("com.tinkerpop.gremlin.Tokens.T"); imports.add("com.tinkerpop.gremlin.groovy.*"); config.setProperty("imports", imports); List<String> staticImports = new ArrayList<>(); staticImports.add("com.tinkerpop.blueprints.Direction.*"); staticImports.add("com.tinkerpop.blueprints.TransactionalGraph$Conclusion.*"); staticImports.add("com.tinkerpop.blueprints.Compare.*"); staticImports.add("com.thinkaurelius.titan.core.attribute.Geo.*"); staticImports.add("com.thinkaurelius.titan.core.attribute.Text.*"); staticImports.add("com.thinkaurelius.titan.core.TypeMaker$UniquenessConsistency.*"); staticImports.add("com.tinkerpop.blueprints.Query$Compare.*"); config.setProperty("static-imports", staticImports); EngineConfiguration engineConfiguration = new EngineConfiguration(config); List<EngineConfiguration> engineConfigurations = new ArrayList<>(); engineConfigurations.add(engineConfiguration); EngineController.configure(engineConfigurations); }
From source file:org.lable.oss.dynamicconfig.core.BasicUseIT.java
@Test public void withDefaultsClasspathTest() throws ConfigurationException { System.setProperty(ConfigurationInitializer.LIBRARY_PREFIX + ".type", "classpath"); System.setProperty(ConfigurationInitializer.LIBRARY_PREFIX + ".classpath.path", "test.yml"); HierarchicalConfiguration defaults = new HierarchicalConfiguration(); defaults.setProperty("type.string", "Not okay"); defaults.setProperty("only.in.defaults", "XXX"); Configuration configuration = ConfigurationInitializer.configureFromProperties(defaults, new YamlDeserializer()); assertThat(configuration.getString("type.string"), is("Okay")); assertThat(configuration.getString("only.in.defaults"), is("XXX")); }
From source file:org.lable.oss.dynamicconfig.core.commonsconfiguration.ObjectifierTest.java
@Test @SuppressWarnings("unchecked") public void testTree() throws Exception { // Prepare a configuration object to test with. HierarchicalConfiguration configuration = new HierarchicalConfiguration(); configuration.setProperty("type.unicodeString", ""); configuration.setProperty("type.booleanFalse", false); configuration.setProperty("type.booleanTrue", true); configuration.setProperty("type.list", Arrays.asList("1", "2", "3")); configuration.setProperty("type.listInt", Arrays.asList(1, 2, 3)); // Perform the test. Object tree = Objectifier.traverseTreeAndEmit(configuration.getRootNode()); assertThat(tree, instanceOf(Map.class)); Map<String, Object> treeMap = (Map<String, Object>) tree; assertThat(treeMap.get("type"), instanceOf(Map.class)); Map<String, Object> typeMap = (Map<String, Object>) treeMap.get("type"); assertThat(typeMap.size(), is(5));//w w w . j a v a 2 s. c om String unicodeString = (String) typeMap.get("unicodeString"); assertThat(unicodeString, is("")); boolean booleanFalse = (boolean) typeMap.get("booleanFalse"); boolean booleanTrue = (boolean) typeMap.get("booleanTrue"); assertThat(booleanFalse, is(false)); assertThat(booleanTrue, is(true)); List<String> stringList = (List<String>) typeMap.get("list"); assertThat(stringList, is(Arrays.asList("1", "2", "3"))); List<Integer> intList = (List<Integer>) typeMap.get("listInt"); assertThat(intList, is(Arrays.asList(1, 2, 3))); }
From source file:org.lable.oss.dynamicconfig.core.ConcurrencyIT.java
@Test public void concurrencyTest() throws IOException, InterruptedException, ConfigurationException { final int threadCount = 20; final Path configFile = Files.createTempFile("config", ".yaml"); Files.write(configFile, "test: 0\n".getBytes()); System.setProperty(ConfigurationInitializer.LIBRARY_PREFIX + ".type", "file"); System.setProperty(ConfigurationInitializer.LIBRARY_PREFIX + ".file.path", configFile.toAbsolutePath().toString()); HierarchicalConfiguration defaults = new HierarchicalConfiguration(); defaults.setProperty("test", -1); final Configuration configuration = ConfigurationInitializer.configureFromProperties(defaults, new YamlDeserializer()); final CountDownLatch ready = new CountDownLatch(threadCount + 1); final CountDownLatch start = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(threadCount + 1); final Map<Integer, Long> result = new ConcurrentHashMap<>(threadCount); final long stopTime = System.currentTimeMillis() + 1_000; for (int i = 0; i < threadCount; i++) { final Integer number = 10 + i; new Thread(() -> { ready.countDown();/*from ww w . j a va 2s . co m*/ try { result.put(number, 0L); start.await(); while (System.currentTimeMillis() < stopTime) { System.out.println(configuration.getLong("test")); result.put(number, result.get(number) + 1); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } done.countDown(); }, String.valueOf(number)).start(); } new Thread(() -> { long count = 1; ready.countDown(); try { start.await(); while (System.currentTimeMillis() < stopTime) { String contents = "test: " + count + "\n"; Files.write(configFile, contents.getBytes()); count++; Thread.sleep(10); } } catch (Exception e) { fail(e.getMessage()); } done.countDown(); }, "setter").start(); ready.await(); start.countDown(); done.await(); for (Map.Entry<Integer, Long> entry : result.entrySet()) { System.out.println("Thread " + entry.getKey() + ": " + entry.getValue()); } }
From source file:org.lable.oss.dynamicconfig.core.DependencyInjectionIT.java
@Test public void diProviderTestWithDefaults() { System.setProperty(ConfigurationInitializer.LIBRARY_PREFIX + ".type", "classpath"); System.setProperty(ConfigurationInitializer.LIBRARY_PREFIX + ".classpath.path", "test.yml"); final HierarchicalConfiguration defaults = new HierarchicalConfiguration(); defaults.setProperty("type.string", "Not okay"); defaults.setProperty("only.in.defaults", "XXX"); Injector injector = Guice.createInjector(new AbstractModule() { @Override/*from w w w .j a v a2 s . com*/ protected void configure() { bind(HierarchicalConfiguration.class).annotatedWith(ConfigurationDefaults.class) .toInstance(defaults); bind(HierarchicalConfigurationDeserializer.class).to(YamlDeserializer.class); bind(Configuration.class).toProvider(ConfigurationProvider.class); } }); Configuration configuration = injector.getInstance(Configuration.class); // As set in test.yml: assertThat(configuration.getString("type.string"), is("Okay")); // Overridden in this test: assertThat(configuration.getString("only.in.defaults"), is("XXX")); }