Java Code Examples for org.rapidoid.setup.On

The following examples show how to use org.rapidoid.setup.On. 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: HttpVerbsTest.java    License: 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 2
Source Project: rapidoid   Source File: AsyncHttpServerTest.java    License: 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 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 4
Source Project: rapidoid   Source File: HttpTransactionTest.java    License: 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 5
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 6
Source Project: rapidoid   Source File: JPACustomizationTest.java    License: 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 7
Source Project: rapidoid   Source File: HttpSyncAsyncMixTest.java    License: 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 8
Source Project: rapidoid   Source File: HttpChunkedStreamTest.java    License: 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 Project: rapidoid   Source File: HttpChunkedStreamTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testChunkedEncodingAsync() {
	On.req(req -> {
		U.must(!req.isAsync());
		req.async();
		U.must(req.isAsync());

		OutputStream out = req.out();

		async(() -> {
			out.write("ab".getBytes());
			out.flush();

			async(() -> {
				out.write("c".getBytes());
				out.flush();

				async(() -> {
					out.write("d".getBytes());
					out.close();
					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 10
Source Project: rapidoid   Source File: HttpHtmlApiTest.java    License: 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 11
Source Project: rapidoid   Source File: HttpChunkedResponseTest.java    License: 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 12
Source Project: rapidoid   Source File: HttpHtmlApiTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test28() {
	On.get("/test28").html((ReqRespHandler) (req, resp) -> {
		resp.headers().put("hdr1", "HDRX");
		resp.headers().put("hdr2", "hdry");
		return resp.result("RESULT 28");
	});

	onlyGet("/test28");
}
 
Example 13
Source Project: rapidoid   Source File: LambdaHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testLambdaHandlerWithAnonymousClass() {
	TwoParamLambda<Resp, Req, Integer> oneParamLambda = new TwoParamLambda<Resp, Req, Integer>() {
		@Override
		public Resp execute(Req param, Integer x) {
			return param.response().result("x=" + x);
		}
	};

	On.get("/test").json(oneParamLambda);

	onlyGet("/test?x=123");
}
 
Example 14
Source Project: rapidoid   Source File: LambdaHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testLambdaHandlerWithLambda() {
	TwoParamLambda<Resp, Req, Integer> oneParamLambda = (Req param, Integer y) -> param.response().result("y=" + y);

	On.get("/test").html(oneParamLambda);

	onlyGet("/test?y=456");
}
 
Example 15
Source Project: rapidoid   Source File: HttpMainEntryTest.java    License: 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");
}
 
Example 16
Source Project: rapidoid   Source File: Main.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	/* The response type will be JSON, instead of HTML */

	On.get("/").html((Req req) -> {
		Resp resp = req.response();
		resp.contentType(MediaType.JSON);
		resp.result("abc");
		return resp;
	});
}
 
Example 17
Source Project: rapidoid   Source File: Main.java    License: 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 18
Source Project: rapidoid   Source File: Main.java    License: 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 19
Source Project: rapidoid   Source File: Main.java    License: 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 20
Source Project: rapidoid   Source File: Main.java    License: 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 21
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 22
Source Project: rapidoid   Source File: HttpResponseStreamTest.java    License: 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 23
Source Project: rapidoid   Source File: Main.java    License: 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 24
Source Project: rapidoid   Source File: HttpCookiesTest.java    License: 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 25
Source Project: rapidoid   Source File: Main.java    License: 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 26
Source Project: rapidoid   Source File: HttpCookiesTest.java    License: 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);
	});
}
 
Example 27
Source Project: rapidoid   Source File: HttpTestCommons.java    License: 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 28
Source Project: rapidoid   Source File: HttpErrorTest.java    License: 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 29
Source Project: rapidoid   Source File: JSONRenderingTest.java    License: 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 30
Source Project: rapidoid   Source File: HttpServerHeadersTest.java    License: 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);
	}
}