org.rapidoid.setup.On Java Examples

The following examples show how to use org.rapidoid.setup.On. 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 File: HttpSyncAsyncMixTest.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Test
public void testSyncAsyncMix() {

	On.get("/").plain((Resp resp, Integer n) -> {
		if (n % 2 == 0) return n;

		return Jobs.after(3).milliseconds(() -> resp.result(n * 10).done());
	});

	// it is important to use only 1 connection
	HttpClient client = HTTP.client().reuseConnections(true).keepAlive(true).maxConnTotal(1);

	for (int i = 0; i < ROUNDS; i++) {
		int expected = i % 2 == 0 ? i : i * 10;
		client.get(localhost("/?n=" + i)).expect("" + expected);
		client.get(localhost("/abcd.txt")).expect("ABCD");
	}

	client.close();
}
 
Example #2
Source File: AsyncHttpServerTest.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncHttpServerNested() {
	On.req(req -> {
		U.must(!req.isAsync());
		req.async();
		U.must(req.isAsync());

		async(() -> appendTo(req, "O", false, () -> async(() -> {
			appendTo(req, "K", true, null);
			// req.done() is in "appendTo"
		})));

		return req;
	});

	assertTimeout(Duration.ofSeconds(20), () -> {
		Self.get("/").expect("OK").execute();
		Self.get("/").expect("OK").benchmark(1, 100, REQUESTS);
		Self.post("/").expect("OK").benchmark(1, 100, REQUESTS);
	});
}
 
Example #3
Source File: Main.java    From rapidoid with 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 #4
Source File: JPACustomizationTest.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomEMFWithReq() {
	JPA.bootstrap(path());

	On.post("/tx").transaction().json(() -> JPA.insert(new Book("posted")));

	AtomicInteger n = new AtomicInteger();

	My.entityManagerFactoryProvider(req -> {
		notNull(req);
		n.incrementAndGet();
		return JPA.provideEmf();
	});

	for (int i = 0; i < total; i++) {
		int expectedId = i + 1;
		HTTP.post(localhost("/tx"))
			.expect()
			.entry("id", expectedId)
			.entry("title", "posted");
	}

	eq(n.get(), total);
}
 
Example #5
Source File: HttpVerbsTest.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpVerbs() {
	On.get("/testGet").html("get:success");
	On.post("/testPost").html("post:success");
	On.put("/testPut").html("put:success");
	On.delete("/testDelete").html("delete:success");
	On.patch("/testPatch").html("patch:success");
	On.options("/testOptions").html("options:success");
	On.head("/testHead").html(""); // no body for the HEAD verb
	On.trace("/testTrace").html("trace:success");

	eq(HTTP.get(localhost("/testGet")).fetch(), "get:success");
	eq(HTTP.post(localhost("/testPost")).fetch(), "post:success");
	eq(HTTP.put(localhost("/testPut")).fetch(), "put:success");
	eq(HTTP.delete(localhost("/testDelete")).fetch(), "delete:success");
	eq(HTTP.patch(localhost("/testPatch")).fetch(), "patch:success");
	eq(HTTP.options(localhost("/testOptions")).fetch(), "options:success");
	eq(HTTP.head(localhost("/testHead")).fetch(), ""); // no body for the HEAD verb
	eq(HTTP.trace(localhost("/testTrace")).fetch(), "trace:success");
}
 
Example #6
Source File: HttpTestCommons.java    From rapidoid with 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 #7
Source File: HttpTransactionTest.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Test
public void testWebTx() {
	JPA.bootstrap(path());

	On.get("/allBooks").json(() -> JPA.of(Book.class).all());
	On.post("/books").json((Book b) -> JPA.insert(b));

	On.post("/del").transaction().json((Long id) -> {
		JPA.delete(Book.class, id);
		JPA.flush(); // optional
		return U.list("DEL " + id, JPA.getAllEntities());
	});

	postData("/books?title=a", U.map("title", "My Book 1"));
	postData("/books?title=b", U.map("title", "My Book 2"));

	onlyGet("/allBooks");

	onlyPost("/del?id=1");
	onlyPost("/del?id=2");
}
 
Example #8
Source File: HttpChunkedStreamTest.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Test
public void testChunkedEncoding() {
	On.req(req -> {
		OutputStream out = req.out();

		out.write("ab".getBytes());
		out.write("c".getBytes());
		out.flush();

		out.write("d".getBytes());

		out.close();

		return req;
	});

	getReq("/");

	assertTimeout(Duration.ofSeconds(20), () -> {
		Self.get("/").expect("abcd").execute();
		Self.get("/").expect("abcd").benchmark(1, 100, REQUESTS);
		Self.post("/").expect("abcd").benchmark(1, 100, REQUESTS);
	});
}
 
Example #9
Source File: Main.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

		/* The handler for [/msg] returns the model */
		/* The default view name is [msg] */
		/* So the corresponding template is [templates/msg.html] */

		On.page("/msg").mvc(() -> U.map("count", 12, "oki", GUI.btn("OK")));

		/* A custom view name can be assigned. */
		/* In this case the default view name is [abc], */
		/* but a custom view name [msg] was specified */

		On.get("/abc").view("msg").mvc((Req req, Resp resp) -> U.map("count", 100, "oki", ""));
	}
 
Example #10
Source File: HttpUnmanagedTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnmanagedHandlersWithNormalJSON2() {

	On.post("/json").managed(false).serve((Req req, Resp resp) -> {
		resp.contentType(MediaType.JSON)
			.code(500)
			.header("hdr1", "val1")
			.cookie("cook1", "the-cookie");

		return DATA;
	});

	onlyPost("/json");
}
 
Example #11
Source File: TxErrorHandlerTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void txWrapperShouldNotDisruptCustomErrorHandling() {
	JPA.bootstrap(path());

	App.beans(new TxCtrl());

	On.error(IllegalArgumentException.class).handler((req, resp, e) -> {
		resp.code(400);
		return U.map("error", "Invalid data!");
	});

	onlyGet("/x");
}
 
Example #12
Source File: Main.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	On.req(req -> {
		int counter = req.token("n", 0) + 1;
		req.token().put("n", counter);
		return counter;
	});
}
 
Example #13
Source File: Main.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	On.req(req -> {
		int counter = req.session("n", 0) + 1;
		req.session().put("n", counter);
		return counter;
	});
}
 
Example #14
Source File: Main.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	App.bootstrap(args);

	On.get("/a*").json(Req::uri);

	Reverse.proxy("/g")
		.roles("administrator")
		.cacheTTL(1000)
		.to("http://upstream1:8080", "http://upstream2:8080")
		.add();
}
 
Example #15
Source File: HttpHtmlApiTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void test35() {
	On.get("/future").html((Req req, Resp resp) -> Jobs.after(1).seconds(() -> {
		resp.result("finished!").done();
	}));

	onlyGet("/future");
}
 
Example #16
Source File: HttpChunkedResponseTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void testChunkedEncodingAsync() {
	On.req((req, resp) -> {
		U.must(!req.isAsync());
		req.async();
		U.must(req.isAsync());

		async(() -> {
			resp.chunk("ab".getBytes());

			async(() -> {
				resp.chunk("c".getBytes());

				async(() -> {
					resp.chunk("d".getBytes());
					req.done();
				});
			});
		});

		return req;
	});

	getReq("/");

	assertTimeout(Duration.ofSeconds(20), () -> {
		Self.get("/").expect("abcd").execute();
		Self.get("/").expect("abcd").benchmark(1, 100, REQUESTS);
		Self.post("/").expect("abcd").benchmark(1, 100, REQUESTS);
	});
}
 
Example #17
Source File: HttpRecursiveMainEntryTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void testSequentialControllerRegistration() {
	App.path(path());

	App.scan();
	On.get("/a").plain("A");

	onlyGet("/a");
	onlyGet("/b");
	onlyGet("/c");
}
 
Example #18
Source File: BeanFormRenderingTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void testBeanFormBindingAndRendering() {
	On.page("/").html(() -> GUI.edit(new Dude("unknown", 100)));

	getAndPost("/");
	getAndPost("/?name=foo&age=12345");

	postData("/?bad-age", U.map("name", "Mozart", "age", "123f"));
	postData("/?name=hey&age=77", U.map("name", "Bach"));
}
 
Example #19
Source File: Main.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void setupDbHandlers() {
	JdbcClient jdbc = JDBC.api();

	if (Env.hasProfile("mysql")) {
		jdbc.url("jdbc:mysql://tfb-database:3306/hello_world?" + Helper.MYSQL_CONFIG);

	} else if (Env.hasProfile("postgres")) {
		jdbc.url("jdbc:postgresql://tfb-database:5432/hello_world?" + Helper.POSTGRES_CONFIG);

	} else {
		throw Err.notExpected();
	}

	On.get("/fortunes").managed(false).html(new FortunesHandler(jdbc));
}
 
Example #20
Source File: WebShutdownTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void step2() {
	App.run(new String[0]);

	On.get("/x").plain("X");

	onlyGet("/x");
}
 
Example #21
Source File: WidgetRenderingTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void testFormBindingAndRendering() {
	On.page("/").html(() -> GUI.edit(U.map("name", "unknown", "age", 100)));

	getAndPost("/");
	getAndPost("/?name=foo&age=12345"); // URL params are ignored

	postData("/?age=1", U.map("name", "Mozart", "age", "123f"));
	postData("/?name=hey&age=77", U.map("name", "Bach"));
}
 
Example #22
Source File: HttpServerHeadersTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRenderRabbit() { // :)
	On.get("/rabbit.jpg").html((ReqHandler) x -> x.response().file(IO.file("rabbit.jpg")));

	byte[] rabbit = IO.loadBytes("rabbit.jpg");

	for (int i = 0; i < N; i++) {
		eq(getBytes("/rabbit.jpg"), rabbit);
	}
}
 
Example #23
Source File: JSONRenderingTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void testJSONParsingWithoutJsonHeaderPUT() {
	// simply return the same object
	On.put("/movie").json((Movie m) -> m);

	Movie movie = new Movie("test title", 1999);
	onlyPut("/movie", JSON.stringify(movie));
}
 
Example #24
Source File: HttpErrorTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithHandlerException() {
	On.get("/err").json(() -> {
		Err.secure(false, "Not secure!");
		return 123;
	});

	onlyGet("/err");

	On.get("/err2").html(() -> {
		throw new NullPointerException();
	});

	onlyGet("/err2");
}
 
Example #25
Source File: HttpResponseStreamTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
	public void testOutputStream() {
		On.req(req -> {
			IO.write(req.response().out(), req.data().toString());
			req.response().out().close(); // FIXME remove this, auto-close on Req done
//			req.done(); // FIXME fails (job already finished)
			return req;
		});

		getReq("/?msg=hello!");
		postData("/", U.map("x", 123));
	}
 
Example #26
Source File: Main.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	App.bootstrap(args);

	String fooUpstream = "localhost:8080/foo";

	Reverse.proxy("/bar").to(fooUpstream).add();
	Reverse.proxy("/").to(fooUpstream).add();

	On.get("/foo").html("FOO");
	On.get("/foo/hi").html("FOO HI");
	On.get("/foo/hello").html("FOO HELLO");
	On.get("/bar/hi").html("BAR HI");
}
 
Example #27
Source File: HttpCookiesTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpCookies() {

	On.req((ReqRespHandler) (req, resp) -> {
		resp.cookie(req.uri(), "" + req.cookies().size());
		return resp.json(req.cookies());
	});

	multiThreaded(THREADS, ROUNDS, this::checkCookies);
}
 
Example #28
Source File: Main.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

		/* Returning the request or response object means the response was constructed */

		On.get("/").html((Req req) -> {
			Resp resp = req.response();
			resp.contentType(MediaType.JSON);
			resp.result("hello");
			return resp;
		});
	}
 
Example #29
Source File: HttpTestCommons.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@AfterEach
public void closeContext() {
	if (Admin.setup().isRunning()) {
		if (Admin.setup().port() == On.setup().port()) {
			Admin.setup().reset();
		} else {
			Admin.setup().shutdown();
		}
	}
}
 
Example #30
Source File: HttpCookiesTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoCookies() {

	On.req((ReqRespHandler) (req, resp) -> {
		isTrue(req.cookies().isEmpty());
		return req.cookies().size();
	});

	multiThreaded(THREADS, ROUNDS, () -> {
		checkNoCookies(true);
		checkNoCookies(false);
	});
}