org.rapidoid.setup.My Java Examples

The following examples show how to use org.rapidoid.setup.My. 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: RestServer.java    From apollo with Apache License 2.0 6 votes vote down vote up
private void registerLoginProvider() {
    My.loginProvider((req, username, password) -> {
        User requestedUser = userDao.getUser(username);
        if (requestedUser == null) {
            req.response().code(HttpStatus.UNAUTHORIZED);
            return false;
        }

        if (!requestedUser.isEnabled()) {
            req.response().code(HttpStatus.FORBIDDEN);
            return false;
        }

        if (PasswordManager.checkPassword(password, requestedUser.getHashedPassword())) {
            return true;
        } else {
            req.response().code(HttpStatus.UNAUTHORIZED);
            return false;
        }
    });
}
 
Example #2
Source File: HttpWrappersTest.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldTransformRespResult() {
	My.wrappers(wrapper("wrap1"), wrapper("wrap2"));

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

	On.get("/req").serve(req -> {
		req.response().plain("FOO");
		return req;
	});

	On.get("/resp").serve((Resp resp) -> resp.plain("BAR"));

	On.get("/json").json(() -> 123);

	On.get("/html").html(req -> "<p>hello</p>");

	On.get("/null").json(req -> null);

	onlyGet("/x");
	onlyGet("/req");
	onlyGet("/resp");
	onlyGet("/json");
	onlyGet("/html");
	onlyGet("/null");
}
 
Example #3
Source File: JMustacheViewResolverTest.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Test
public void testRendering() {
	My.templatesPath("view-rendering");

	JMustacheViewResolver viewResolver = Integrate.jMustacheViewResolver();
	viewResolver.setCustomizer(compiler -> compiler.defaultValue("DEFAULT"));

	My.viewResolver(viewResolver);

	On.get("/").view("mtmpl").mvc((req, resp) -> {
		resp.model("y", "bar");
		return U.map("x", "foo");
	});

	getReq("/");
}
 
Example #4
Source File: JPACustomizationTest.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomEMFWithoutReq() {
	JPA.bootstrap(path());

	AtomicInteger n = new AtomicInteger();

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

	for (int i = 0; i < total; i++) {
		JPA.transaction(() -> {
			Book book = JPA.insert(new Book("b"));
			notNull(book.getId());
		});
	}

	eq(n.get(), total);
}
 
Example #5
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 #6
Source File: JPACustomizationTest.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomEMWithoutReq() {
	JPA.bootstrap(path());

	AtomicInteger n = new AtomicInteger();

	My.entityManagerProvider(req -> {
		isNull(req);
		n.incrementAndGet();
		return JPA.provideEmf().createEntityManager();
	});

	for (int i = 0; i < total; i++) {
		JPA.transaction(() -> {
			Book book = JPA.insert(new Book("b"));
			notNull(book.getId());
		});
	}

	eq(n.get(), total);
}
 
Example #7
Source File: JPACustomizationTest.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomEMWithReq() {
	JPA.bootstrap(path());

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

	AtomicInteger n = new AtomicInteger();

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

	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 #8
Source File: HttpXmlAPITest.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Test
public void testXmlRequestBody() {
	On.post("/echo").xml((ReqHandler) req -> {
		Point point = new Point();
		point.coordinates = req.data();
		return point;
	});

	My.xmlMapper(XML.newMapper());
	String resp = Self.post("/echo")
		.body("<point><x>12.3</x><y>456</y></point>".getBytes())
		.contentType("application/xml")
		.fetch();

	eq(resp, "<Point><coordinates><x>12.3</x><y>456</y></coordinates></Point>");
}
 
Example #9
Source File: RestServer.java    From apollo with Apache License 2.0 6 votes vote down vote up
private void registerRolesProvider() {
    My.rolesProvider((req, username) -> {
        try {
            User user = userDao.getUser(username);
            if (!user.isEnabled()) {
                req.response().code(HttpStatus.FORBIDDEN);
                return null;
            }
            if (user.isAdmin()) {
                return U.set(Role.ADMINISTRATOR);
            }
            return U.set(Role.ANYBODY);

        } catch (Exception e) {
            logger.error("Got exception while getting user roles! setting to ANYBODY", e);
            return U.set(Role.ANYBODY);
        }
    });
}
 
Example #10
Source File: Main.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

		/* Use the built-in entity manager, and decorate it */

		My.entityManagerProvider(req -> {
			EntityManager em = JPA.em();
			/// em = new SomeEntityManagerDecorator(em);
			return em;
		});

	}
 
Example #11
Source File: CustomizationTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void customJsonBodyParser() {
	My.jsonRequestBodyParser((req, body) -> U.map("uri", req.uri(), "parsed", JSON.parse(body)));

	On.post("/abc").json(req -> req.data());
	On.req(req -> req.posted());

	postData("/abc?multipart", U.map("x", 13579, "foo", "bar"));
	postData("/abc2?multipart", U.map("x", 13579, "foo", "bar"));

	postJson("/abc?custom", U.map("x", 13579, "foo", "bar"));
	postJson("/abc2?custom", U.map("x", 13579, "foo", "bar"));
}
 
Example #12
Source File: HttpWrappersTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldTransformErrorsWithCatchingWrappers() {
	My.wrappers(wrapper("wrap1"), catchingWrapper("wrap2"));

	On.get("/err").plain(() -> {
		throw U.rte("Intentional error!");
	});

	onlyGet("/err");
}
 
Example #13
Source File: HttpWrappersTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldThrowErrorsWithNonCatchingWrappers() {
	My.wrappers(wrapper("wrap1"), wrapper("wrap2"));

	On.get("/err").plain(() -> {
		throw U.rte("Intentional error!");
	});

	onlyGet("/err");
}
 
Example #14
Source File: HttpWrappersTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultWrappers() {
	My.wrappers(wrapper("def"));

	On.post("/z").plain("Zzz");

	onlyPost("/z");
}
 
Example #15
Source File: HttpModule.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Override
public void cleanUp() {
	My.reset();
	App.resetGlobalState();
	On.changes().ignore();

	Setups.clear();

	Env.reset();
}
 
Example #16
Source File: MustacheJavaViewResolverTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void testRendering() {
	My.templatesPath("view-rendering");

	MustacheJavaViewResolver viewResolver = Integrate.mustacheJavaViewResolver();

	viewResolver.setCustomizer(compiler -> {

		compiler.setObjectHandler(new ReflectionObjectHandler() {
			@Override
			public String stringify(Object object) {
				return "[" + object + "]";
			}
		});

		return compiler;
	});

	My.viewResolver(viewResolver);

	On.get("/").view("mtmpl").mvc((req, resp) -> {
		resp.model("y", "bar");
		return U.map("x", "foo");
	});

	getReq("/");
}
 
Example #17
Source File: CustomizationTest.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
@Test
public void customErrorHandlerByType() {

	App.beans(new Object() {
		@GET
		public void err5() {
			throw new SecurityException("INTENTIONAL - Access denied!");
		}
	});

	My.error(NullPointerException.class).handler((req1, resp, e) -> "MY NPE");
	My.error(RuntimeException.class).handler((req1, resp, e) -> e instanceof NotFound ? null : "MY RTE");

	On.error(SecurityException.class).handler((req1, resp, e) -> {
		resp.code(403);
		return U.map("error", "Access denied!");
	});

	My.error(SecurityException.class).handler((req1, resp, e) -> "MY SEC");

	On.get("/err1").json(req -> {
		throw new NullPointerException();
	});

	On.post("/err2").json(req -> {
		throw new RuntimeException();
	});

	On.get("/err3").json(req -> {
		throw new SecurityException("INTENTIONAL - Access denied!");
	});

	On.get("/err4").json(req -> {
		throw new OutOfMemoryError("INTENTIONAL - Out of memory!");
	});

	onlyGet("/err1");
	onlyPost("/err2");
	onlyGet("/err3");
	onlyGet("/err4");
	onlyGet("/err5");
}
 
Example #18
Source File: HttpTemplatesPathTest.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
@Test
public void testTemplatesPath3() {
	My.templatesPath("test-templates");
	eq(App.custom().templatesPath(), U.array("test-templates"));
	setupAndTest();
}
 
Example #19
Source File: Main.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
	App.bootstrap(args);

	Boot.auth();

	On.get("/").html((req, resp) -> "this is public!");

	On.get("/manage").roles("manager").html((req, resp) -> "this is private!");

	/* Dummy login: successful if the username is the same as the password */

	My.loginProvider((req, username, password) -> username.equals(password));

	/* Gives the 'manager' role to every logged-in user */

	My.rolesProvider((req, username) -> U.set("manager"));
}
 
Example #20
Source File: HttpHandlerTest.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
@Test
public void testFastHttpHandler() {
	Customization customization = new Customization("example", My.custom(), new ConfigImpl());
	HttpRoutesImpl routes = new HttpRoutesImpl("example", customization);
	FastHttp http = new FastHttp(routes);

	routes.on("get", "/abc", (req, resp) -> resp.json(req.data()));

	routes.on("get,post", "/xyz", (req, resp) -> resp.html(U.list(req.uri(), req.data())));

	Server server = http.listen(7779);

	onlyGet(7779, "/abc?x=1&y=foo");

	getAndPost(7779, "/xyz?aa=foo&bb=bar&c=true");

	server.shutdown();
}
 
Example #21
Source File: Server.java    From rpc-benchmark with Apache License 2.0 3 votes vote down vote up
public static void main(String[] args) {

		App.bootstrap(args);

		My.custom().objectMapper(JsonUtils.objectMapper);

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

		On.port(port);
	}
 
Example #22
Source File: Main.java    From rapidoid with Apache License 2.0 3 votes vote down vote up
public static void main(String[] args) {
	App.bootstrap(args);

	My.rolesProvider((req, username) -> username.equals("bob") ? U.set("manager") : U.set());

	On.get("/hey").roles("manager").json(() -> U.map("msg", "ok"));

	// generate a token
	String token = Tokens.serialize(U.map("_user", "bob"));

	// demo request, prints {"msg":"ok"}
	Self.get("/hey?_token=" + token).print();
}
 
Example #23
Source File: IsolatedIntegrationTest.java    From rapidoid with Apache License 2.0 3 votes vote down vote up
@BeforeEach
public void openContext() {
	TimeZone.setDefault(TimeZone.getTimeZone("CET"));

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

	RapidoidModules.getAll(); // all modules must be present
	RapidoidIntegrationTest.before(this);

	JPAUtil.reset();

	Conf.ROOT.setPath(getTestNamespace());

	My.reset();

	App.resetGlobalState();

	On.changes().ignore();

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

	App.path(getTestPackageName());

	verifyNoRoutes();

	U.must(Msc.isInsideTest());

	Env.reset();

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

	U.must(Msc.isInsideTest());

	RapidoidIntegrationTest.start(this);
}
 
Example #24
Source File: Main.java    From rapidoid with Apache License 2.0 3 votes vote down vote up
public static void main(String[] args) {

		/* Dummy template loader - constructs templates on-the-fly */

		My.templateLoader(filename -> {
			String tmpl = "In " + filename + ": x = <b>${x}</b>";
			return tmpl.getBytes();
		});

		// The URL parameters will be the MVC model

		On.get("/showx").mvc(Req::params);
	}
 
Example #25
Source File: Main.java    From rapidoid with Apache License 2.0 3 votes vote down vote up
public static void main(String[] args) {

		/* The EntityManagerFactory's should be properly initialized */

		EntityManagerFactory emf1 = null; // FIXME
		EntityManagerFactory emf2 = null; // FIXME

		My.entityManagerFactoryProvider(req -> req.path().startsWith("/db1/") ? emf1 : emf2);

	}