Java Code Examples for org.rapidoid.config.Conf

The following examples show how to use org.rapidoid.config.Conf. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: rapidoid   Source File: Auth.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean login(String username, String password) {
	if (U.isEmpty(username) || password == null) {
		return false;
	}

	if (!Conf.USERS.has(username)) {
		return false;
	}

	Config user = Conf.USERS.sub(username);

	if (user.isEmpty()) {
		return false;
	}

	String pass = user.entry("password").str().getOrNull();
	String hash = user.entry("hash").str().getOrNull();

	return (pass != null && U.eq(password, pass)) || (hash != null && Crypto.passwordMatches(password, hash));
}
 
Example 2
Source Project: rapidoid   Source File: Msc.java    License: Apache License 2.0 6 votes vote down vote up
public static void reset() {
	Env.reset();
	Events.reset();
	Log.reset();
	Crypto.reset();
	Res.reset();
	Conf.reset();
	Groups.reset();
	Jobs.reset();
	Env.reset();
	Caching.reset();

	Ctxs.reset();
	U.must(Ctxs.get() == null);

	resetState();
}
 
Example 3
Source Project: rapidoid   Source File: RolesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRolesConfig() {
	isFalse(Conf.USERS.toMap().isEmpty());
	isTrue(Conf.USERS.toMap().containsKey("niko"));
	isTrue(Conf.USERS.has("niko"));

	isFalse(Conf.USERS.sub("niko").isEmpty());
	isTrue(Conf.USERS.sub("niko").has("email"));
	eq(Conf.USERS.sub("niko").get("email"), "[email protected]");
	eq(Conf.USERS.sub("niko").entry("password").str().or("none"), "easy");

	eq(Auth.getRolesFor("niko"), U.set("owner", "moderator", "administrator"));
	eq(Auth.getRolesFor("chuck"), U.set("moderator", "restarter"));
	eq(Auth.getRolesFor("abc"), U.set("guest", "foo", "bar"));

	eq(Auth.getRolesFor("zzz"), U.set());

	eq(Auth.getRolesFor(""), U.set());
	eq(Auth.getRolesFor(null), U.set());
}
 
Example 4
Source Project: rapidoid   Source File: IoCContextImpl.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> T getInjectableByName(Object target, Class<T> type, String name,
                                  Map<String, Object> properties, boolean useConfig) {

	Object instance = properties != null ? properties.get(name) : null;

	if (instance == null && target != null && useConfig) {
		Config config = Conf.section(target.getClass());

		if (type.equals(Boolean.class) || type.equals(boolean.class)) {
			instance = config.is(name);
		} else {
			String opt = config.entry(name).str().getOrNull();
			if (opt != null) {
				instance = Cls.convert(opt, type);
			}
		}
	}

	return (T) instance;
}
 
Example 5
Source Project: rapidoid   Source File: App.java    License: Apache License 2.0 6 votes vote down vote up
private static void resetAppStateBeforeRestart() {
	App.boot.reset();
	App.status = AppStatus.NOT_STARTED;
	App.dirty = false;
	App.packages = null;

	Groups.reset();
	Conf.reset();
	Env.reset();
	Res.reset();
	JSON.reset();
	Beany.reset();

	for (RapidoidModule mod : RapidoidModules.getAllAvailable()) {
		mod.restartApp();
	}

	AppStarter.reset();
	ClasspathScanner.reset();
	invoked.clear();

	Setups.reloadAll();

	Setups.initDefaults();
	Conf.reset(); // reset the config again
}
 
Example 6
Source Project: rapidoid   Source File: Main.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

		// first thing to do - initializing Rapidoid, without bootstrapping anything at the moment
		App.run(args); // instead of App.bootstrap(args), which might start the server

		// customizing the server address and port - before the server is bootstrapped
		On.address("0.0.0.0").port(9998);
		Admin.address("127.0.0.1").port(9999);

		// fine-tuning the HTTP server
		Conf.HTTP.set("maxPipeline", 32);
		Conf.NET.set("bufSizeKB", 16);

		// now bootstrap some components, e.g. classpath scanning (beans)
		App.scan();

		Boot.jmx()
			.adminCenter();

		// continue with normal setup
		On.get("/x").json("x");
	}
 
Example 7
Source Project: rapidoid   Source File: JDBCPoolC3P0Test.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJDBCWithTextConfig() {
	Conf.JDBC.set("poolProvider", "c3p0");
	Conf.JDBC.set("driver", "org.h2.Driver");
	Conf.JDBC.set("url", "jdbc:h2:mem:mydb");
	Conf.JDBC.set("username", "sa");

	Conf.ROOT.set("c3p0.minPoolSize", 5);
	Conf.ROOT.set("c3p0.maxPoolSize", "123");

	JdbcClient jdbc = JDBC.api();
	eq(jdbc.driver(), "org.h2.Driver");

	ComboPooledDataSource c3p0 = (ComboPooledDataSource) jdbc.init().dataSource();

	eq(c3p0.getMinPoolSize(), 5);
	eq(c3p0.getMaxPoolSize(), 123);

	JDBC.execute("create table abc (id int, name varchar)");
	JDBC.execute("insert into abc values (?, ?)", 123, "xyz");

	final Map<String, ?> expected = U.map("id", 123, "name", "xyz");

	runBenchmark(expected);
}
 
Example 8
Source Project: rapidoid   Source File: JDBCPoolHikariTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testHikariPool() {

	Conf.HIKARI.set("maximumPoolSize", 234);

	JdbcClient jdbc = JDBC.api();
	jdbc.h2("hikari-test");
	jdbc.dataSource(HikariFactory.createDataSourceFor(jdbc));

	jdbc.execute("create table abc (id int, name varchar)");
	jdbc.execute("insert into abc values (?, ?)", 123, "xyz");

	final Map<String, ?> expected = U.map("id", 123, "name", "xyz");

	assertTimeout(Duration.ofSeconds(30), () -> {
		Msc.benchmarkMT(100, "select", 100000, () -> {
			Map<String, Object> record = U.single(JDBC.query("select id, name from abc").all());
			record = Msc.lowercase(record);
			eq(record, expected);
		});
	});

	HikariDataSource hikari = (HikariDataSource) jdbc.dataSource();

	eq(hikari.getMaximumPoolSize(), 234);
}
 
Example 9
Source Project: rapidoid   Source File: HttpTestCommons.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void openContext() {
	Msc.reset();

	ClasspathUtil.setRootPackage("some.nonexisting.app");

	JPAUtil.reset();
	Conf.ROOT.setPath(getTestNamespace());
	IoC.reset();

	App.resetGlobalState();
	On.changes().ignore();

	On.setup().activate();
	On.setup().reload();

	verifyNoRoutes();
}
 
Example 10
Source Project: rapidoid   Source File: C3P0Factory.java    License: Apache License 2.0 6 votes vote down vote up
public static DataSource createDataSourceFor(JdbcClient jdbc) {
	ComboPooledDataSource pool = new ComboPooledDataSource();

	pool.setJdbcUrl(jdbc.url());
	pool.setUser(jdbc.username());
	pool.setPassword(jdbc.password());

	try {
		pool.setDriverClass(jdbc.driver());
	} catch (PropertyVetoException e) {
		throw U.rte("Cannot load JDBC driver!", e);
	}

	Conf.section("c3p0").applyTo(pool);

	return pool;
}
 
Example 11
Source Project: rapidoid   Source File: OpenAPIDescriptor.java    License: Apache License 2.0 6 votes vote down vote up
private Map<String, Object> createRoot() {
	Map<String, Object> spec = Coll.deepCopyOf(cfg.toMap());

	if (spec.isEmpty()) {
		Map<String, Object> info = U.map(
			"version", cfg.entry("version").or("0"),
			"title", cfg.entry("title").or("Untitled")
		);

		spec.put("info", info);

		Map<String, Object> servers = U.map(
			"url", Msc.http() + "://localhost:" + Conf.ON.entry("port").or(8080) + "/"
		);

		spec.put("servers", servers);
	}

	return spec;
}
 
Example 12
Source Project: rapidoid   Source File: Env.java    License: Apache License 2.0 5 votes vote down vote up
private static void processInitialConfig() {
	// initialize root
	String root = U.or(initial("root"), initial("default_root"));
	setRoot(root);

	// initialize config
	String config = initial("config");
	if (config != null) {
		Conf.setFilenameBase(config);
	}
}
 
Example 13
Source Project: rapidoid   Source File: Crypto.java    License: Apache License 2.0 5 votes vote down vote up
private static synchronized void initSecret() {
	String secret = Conf.ROOT.entry("secret").str().getOrNull();

	char[] src;
	if (secret == null) {
		Log.warn("!Application secret was not specified, generating random secret!");

		src = Str.toHex(randomBytes(128)).toCharArray();

	} else {
		src = secret.toCharArray();
	}

	secretKey = CryptoKey.from(src);
}
 
Example 14
Source Project: rapidoid   Source File: Msc.java    License: Apache License 2.0 5 votes vote down vote up
public static synchronized String id() {
	if (state.uid == null) {
		state.uid = Conf.ROOT.entry("id").or(processName());
	}

	return state.uid;
}
 
Example 15
Source Project: rapidoid   Source File: AbstractHttpProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Server listen(String address, int port) {
	FastHttpProtocol protocol = new FastHttpProtocol(this);

	return TCP.server(Conf.HTTP)
		.protocol(protocol)
		.address(address)
		.port(port)
		.syncBufs(syncBufs)
		.build()
		.start();
}
 
Example 16
Source Project: rapidoid   Source File: RespImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void authorize(UserInfo user) {
	Ctxs.required().setUser(user);

	req.token().put(Tokens._USER, user.username);

	long ttl = Conf.TOKEN.entry("ttl").or(0);
	long expiresOn = ttl > 0 ? U.time() + ttl : Long.MAX_VALUE;
	req.token().put(Tokens._EXPIRES, expiresOn);

	req.tokenChanged.set(true);
}
 
Example 17
Source Project: rapidoid   Source File: AbstractHttpServer.java    License: Apache License 2.0 5 votes vote down vote up
public Server listen(String address, int port) {
	return TCP.server(Conf.HTTP)
		.protocol(this)
		.address(address)
		.port(port)
		.syncBufs(syncBufs)
		.build()
		.start();
}
 
Example 18
Source Project: rapidoid   Source File: ExtendedWorker.java    License: Apache License 2.0 5 votes vote down vote up
public ExtendedWorker(String name, RapidoidHelper helper, NetworkingParams net, SSLContext sslContext) {

		super(name);

		this.bufSize = net.bufSizeKB() * 1024;
		this.noDelay = net.noDelay();
		this.bufs = new BufGroup(bufSize, net.syncBufs());
		this.bufSizeLimit = 1024L * Conf.NET.entry("bufSizeLimit").or(1024); // in KB

		this.serverProtocol = net.protocol();
		this.helper = helper;
		this.sslContext = sslContext;

		this.maxPipeline = net.maxPipeline();

		final int queueSize = ConfigUtil.micro() ? 1000 : 1000000;
		final int growFactor = ConfigUtil.micro() ? 2 : 10;

		this.restarting = new ArrayBlockingQueue<>(queueSize);
		this.connecting = new ArrayBlockingQueue<>(queueSize);
		this.connected = new ArrayBlockingQueue<>(queueSize);
		this.done = new SimpleList<>(queueSize / 10, growFactor);

		this.dataIn = Insights.stats(name + ":datain");
		this.dataOut = Insights.stats(name + ":dataout");

		connections = Pools.create("connections", () -> newConnection(false), 100000);

		if (idleConnectionsCrawler != null) {
			idleConnectionsCrawler.register(allConnections);
		}
	}
 
Example 19
Source Project: rapidoid   Source File: Setups.java    License: Apache License 2.0 5 votes vote down vote up
public static Setup create(String name) {
	IoCContext ioc = IoC.createContext().name(name);
	Config config = Conf.section(name);

	Customization customization = new Customization(name, My.custom(), config);
	HttpRoutesImpl routes = new HttpRoutesImpl(name, customization);
	Screen gui = new ScreenBean();
	FastHttp http = new FastHttp(routes, config, gui);

	Setup setup = new SetupImpl(name, "main", http, ioc, config, customization, routes, gui, false);

	instances.add(setup);
	return setup;
}
 
Example 20
Source Project: rapidoid   Source File: App.java    License: Apache License 2.0 5 votes vote down vote up
public static synchronized boolean scan(String... packages) {
	String appPath = Conf.APP.entry("path").str().getOrNull();

	if (U.notEmpty(appPath)) {
		packages = appPath.split("\\s*,\\s*");
		App.path(packages);
	}

	List<Class<?>> beans = App.findBeans(packages);
	beans(beans.toArray());
	return !beans.isEmpty();
}
 
Example 21
Source Project: rapidoid   Source File: DefaultSetup.java    License: Apache License 2.0 5 votes vote down vote up
DefaultSetup() {
	Customization customization = new Customization("main", My.custom(), Conf.ROOT);
	HttpRoutesImpl routes = new HttpRoutesImpl("main", customization);

	FastHttp http = new FastHttp(routes, MAIN_CFG, gui);

	main = new SetupImpl("main", MAIN_ZONE, http, IoC.defaultContext(), MAIN_CFG, customization, routes, gui, true);
	Setups.register(main);

	initDefaults();
}
 
Example 22
Source Project: rapidoid   Source File: AuthBootstrap.java    License: Apache License 2.0 5 votes vote down vote up
public static synchronized void bootstrapAdminCredentials() {
	Config admin = Conf.USERS.sub("admin");

	if (!admin.has("password") && !admin.has("hash")) {
		String pass = randomAdminPassword();
		admin.set("password", pass);

		String maybePass = "" + Msc.maybeMasked(pass);
		Msc.logSection(AnsiColor.lightBlue("ADMIN CREDENTIALS:") + " username = admin, password = " + maybePass);
	}
}
 
Example 23
Source Project: rapidoid   Source File: HttpAdminAndDevServerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAdminServerConfig() {
	int port = 8881;
	Conf.ADMIN.set("port", port);

	sameSetup();
	sendRequests(port);

	Admin.setup().halt();
}
 
Example 24
Source Project: rapidoid   Source File: ConfigHandler.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object call() {

	List<Object> grids = U.list();
	Map<String, Object> sections = U.cast(Conf.ROOT.toMap());
	sections = Msc.protectSensitiveInfo(sections, FA.QUESTION_CIRCLE);

	Map<String, Object> root = U.map();

	for (Map.Entry<String, Object> entry : sections.entrySet()) {
		String key = entry.getKey();
		Object value = entry.getValue();

		if (value instanceof Map<?, ?>) {
			grids.add(h4(span(key).class_("label " + styleOf(key))));
			grids.add(grid((Map<String, ?>) value));
		} else {
			root.put(key, value);
		}
	}

	if (!root.isEmpty()) {
		grids.add(0, h4(span("<root>").class_("label " + styleOf("<root>"))));
		grids.add(1, grid(root));
	}

	return multi(grids);
}
 
Example 25
Source Project: rapidoid   Source File: JdbcWorkers.java    License: Apache License 2.0 5 votes vote down vote up
public JdbcWorkers(JdbcClient jdbc, BlockingQueue<Operation<Connection>> queue) {
	this.queue = queue;

	int workersN = Conf.JDBC.entry("workers").or(ConfigUtil.cpus());
	long batchTimeMs = Conf.JDBC.entry("batchTimeMs").or(5000);

	this.workers = new JdbcWorker[workersN];

	for (int i = 0; i < workers.length; i++) {
		workers[i] = new JdbcWorker(jdbc, queue, batchTimeMs);
		workers[i].start();
	}

	Log.info("Started JDBC workers", "workers", workersN, "batchTimeMs", batchTimeMs);
}
 
Example 26
Source Project: rapidoid   Source File: HikariFactory.java    License: Apache License 2.0 5 votes vote down vote up
public static DataSource createDataSourceFor(JdbcClient jdbc) {
	HikariConfig config = new HikariConfig();

	config.setJdbcUrl(jdbc.url());
	config.setUsername(jdbc.username());
	config.setPassword(jdbc.password());
	config.setDriverClassName(jdbc.driver());

	Conf.HIKARI.applyTo(config);

	return new HikariDataSource(config);
}
 
Example 27
Source Project: rapidoid   Source File: OpenAPI.java    License: Apache License 2.0 5 votes vote down vote up
public static void bootstrap(Setup setup) {
	OpenAPIDescriptor descriptor = new OpenAPIDescriptor(setup, Conf.OPENAPI);

	setup.get(Msc.specialUri("api/openapi.json"))
		.internal(true)
		.json(descriptor::getAPIDocs);

	setup.get(Msc.specialUri("api/openapi.yaml"))
		.internal(true)
		.plain(() -> YAML.stringify(descriptor.getAPIDocs()));
}
 
Example 28
public static void main(String[] args) {
	App.run(args);

	Conf.HTTP.set("maxPipeline", 128);
	Conf.HTTP.set("timeout", 0);

	new PlaintextAndJsonServer().listen(8080);
}
 
Example 29
public static void main(String[] args) {
	App.run(args);

	Conf.HTTP.set("maxPipeline", 128);
	Conf.HTTP.set("timeout", 0);
	Conf.HTTP.sub("mandatoryHeaders").set("connection", false);

	On.port(8080);

	if (Env.hasAnyProfile("mysql", "postgres")) {
		setupDbHandlers();
	} else {
		setupSimpleHandlers();
	}
}
 
Example 30
Source Project: rapidoid   Source File: MscOpts.java    License: Apache License 2.0 4 votes vote down vote up
public static boolean isTLSEnabled() {
	return Conf.TLS.is("enabled");
}