org.rapidoid.u.U Java Examples

The following examples show how to use org.rapidoid.u.U. 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: Str.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
public static String render(Iterable<?> items, String itemFormat, String sep) {
	StringBuilder sb = new StringBuilder();

	int i = 0;
	Iterator<?> it = items.iterator();
	while (it.hasNext()) {
		Object item = it.next();
		if (i > 0) {
			sb.append(sep);
		}

		sb.append(U.frmt(itemFormat, item));
		i++;
	}

	return sb.toString();
}
 
Example #2
Source File: Coll.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> List<T> range(Iterable<T> items, int from, int to) {
	U.must(from <= to, "'from' (%s) must be <= 'to' (%s)!", from, to);

	if (from == to) {
		return Collections.emptyList();
	}

	if (items instanceof Results) {
		Results results = (Results) items;
		return results.page(from, to - from);
	}

	List<?> list = (items instanceof List<?>) ? (List<?>) items : U.list(items);

	from = Math.min(from, list.size());
	to = Math.min(to, list.size());

	return U.cast(list.subList(from, to));
}
 
Example #3
Source File: RespImpl.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
public void chunk(final byte[] data, final int offset, final int length) {
	U.notNull(data, "data");

	resume(() -> {
		Buf out = req.channel().output();

		out.append(Integer.toHexString(length));
		out.append("\r\n");
		out.append(data, offset, length);
		out.append("\r\n");

		req.channel().send();

		return false;
	});
}
 
Example #4
Source File: Secure.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
public static boolean hasRole(String username, Set<String> roles, String role, Class<?> clazz, Object record) {

		if (Role.ANYBODY.equalsIgnoreCase(role)) {
			return true;
		}

		if (U.isEmpty(username) || U.isEmpty(role)) {
			return false;
		}

		if (record != null) {

			if (role.equalsIgnoreCase(Role.OWNER)) {
				return isOwnerOf(username, record);
			}

			if (role.equalsIgnoreCase(Role.SHARED_WITH)) {
				return isSharedWith(username, record);
			}
		}

		return hasRole(username, roles, role);
	}
 
Example #5
Source File: X.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
public static ReqRespHandler manage(final Class<?> entityType, final String baseUri) {
	return (ReqRespHandler) (req, resp) -> {
		if (resp.screen().title() == null) {
			resp.screen().title("Manage " + English.plural(name(entityType)));
		}

		long count = JPA.count(entityType);
		int pageSize = 10;
		int pages = (int) Math.ceil(count / (double) pageSize);
		int page = U.or(Cls.convert(req.params().get("page"), Integer.class), 1);

		IRange range = Range.of((page - 1) * pageSize, pageSize);
		List<?> records = JPA.of(entityType).page(range.start(), range.length());

		Grid grid = GUI.grid(records);

		Btn add = GUI.btn("Add " + name(entityType)).primary().go(baseUri + "/add");

		Pager pager = GUI.pager("page").min(1).max(pages).right(true);

		return GUI.multi(grid, GUI.div(pager, add));
	};
}
 
Example #6
Source File: ClasspathUtil.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
public static List<Class<?>> loadClasses(ScanParams scanParams) {
	List<String> classNames = ClasspathScanner.scan(scanParams);
	List<Class<?>> classes = U.list();

	ClassLoader classLoader = U.or(scanParams.classLoader(), defaultClassLoader);

	for (String clsName : classNames) {
		try {
			Log.trace("Loading class", "name", clsName);
			classes.add(classLoader != null ? Class.forName(clsName, true, classLoader) : Class.forName(clsName));
		} catch (Throwable e) {
			Log.debug("Error while loading class", "name", clsName, "error", e);
		}
	}

	return classes;
}
 
Example #7
Source File: OpenAPIDemo.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	Setup setup = On.setup();

	RouteMeta meta = new RouteMeta();
	meta.id("test1").summary("Test 1")
		.tags(U.set("tag1", "tag2"))
		.inputSchema(DataSchemas.openAPI("in", OpenAPIModel.arraySchema("string")))
		.outputSchema(DataSchemas.openAPI("out", OpenAPIModel.arraySchema("string")));

	On.get("/test1/").meta(meta).plain("hello");

	On.get("/test2/foo").plain("hello");
	On.get("/test2/output").json("hello");
	On.post("/test2/output").xml("hello");
	On.delete("/test2/output").serve("hello");

	OpenAPI.bootstrap(setup);
}
 
Example #8
Source File: Cls.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
public static List<Annotation> getAnnotations(Class<?> clazz) {
	List<Annotation> allAnnotations = U.list();

	try {
		for (Class<?> c = clazz; c.getSuperclass() != null; c = c.getSuperclass()) {
			Annotation[] annotations = c.getDeclaredAnnotations();
			for (Annotation an : annotations) {
				allAnnotations.add(an);
			}
		}

	} catch (Exception e) {
		throw U.rte("Cannot get annotations!", e);
	}

	return allAnnotations;
}
 
Example #9
Source File: Cls.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
public static <T> Class<T> get(String className) {

		if (className.equals("byte")) return U.cast(byte.class);
		if (className.equals("short")) return U.cast(short.class);
		if (className.equals("int")) return U.cast(int.class);
		if (className.equals("long")) return U.cast(long.class);
		if (className.equals("float")) return U.cast(float.class);
		if (className.equals("double")) return U.cast(double.class);
		if (className.equals("boolean")) return U.cast(boolean.class);

		if (className.endsWith("[]")) {
			String cls = Str.trimr(className, "[]");
			return U.cast(Array.newInstance(get(cls), 0).getClass());
		}

		try {
			return U.cast(Class.forName(className));
		} catch (ClassNotFoundException e) {
			throw U.rte(e);
		}
	}
 
Example #10
Source File: IO.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
public static byte[] loadBytes(InputStream input) {

		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] buffer = new byte[16 * 1024];

		try {
			int readN;

			while ((readN = input.read(buffer)) != -1) {
				output.write(buffer, 0, readN);
			}

		} catch (IOException e) {
			throw U.rte(e);
		}

		return output.toByteArray();
	}
 
Example #11
Source File: AbstractCommand.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
public boolean clicked() {
	if (command != null) {
		IReqInfo req = ReqInfo.get();

		if (!req.isGetReq()) {
			String event = GUI.getCommand();

			if (U.notEmpty(event) && U.eq(event, command)) {
				Object[] args = new Object[cmdArgs.length];

				for (int i = 0; i < args.length; i++) {
					args[i] = U.or(req.data().get("_" + i), "");
				}

				return Arrays.equals(args, cmdArgs);
			}
		}
	}

	return false;
}
 
Example #12
Source File: C3P0Factory.java    From rapidoid with 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 #13
Source File: JSTest.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Test
public void testCompileJS() throws ScriptException {
	eq(((Number) JS.compile("1 + 2").eval()).intValue(), 3);
	eq(JS.compile("1 + 'ab'").eval(), "1ab");

	Map<String, Object> map = U.cast(U.map("U", new U()));
	SimpleBindings bindings = new SimpleBindings(map);

	Object res1;
	try {
		// Rhino style
		res1 = JS.compile("(function (x) { return U.str(x); })('hey')").eval(bindings);
	} catch (Exception e) {
		// Nashorn style
		res1 = JS.compile("(function (x) { return U.class.static.str(x); })('hey')").eval(bindings);
	}

	eq(res1, "hey");
}
 
Example #14
Source File: Highlight.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
protected Tag complexHighlight() {
	List<Object> parts = U.list();
	Pattern p = Pattern.compile(regex);
	Matcher m = p.matcher(text);

	int end = 0;
	while (m.find()) {
		String match = m.group();
		parts.add(text.substring(end, m.start()));
		parts.add(GUI.highlight(match));
		end = m.end();
	}

	parts.add(text.substring(end));

	return span(parts);
}
 
Example #15
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 #16
Source File: Crypto.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static synchronized CryptoKey getSecretKey() {
	if (secretKey == null) {
		initSecret();
	}

	U.notNull(secretKey, "secret key");
	return secretKey;
}
 
Example #17
Source File: LambdaParamNamesTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void testLambdaParamNamesWithOnlyLocalVariables() {
	int n = 123;

	ThreeParamLambda<String, Req, Integer, Resp> lambda = (Req req, Integer x, Resp resp) -> "ok";

	eq(Cls.getLambdaParameterNames(lambda), U.array("req", "x", "resp"));
}
 
Example #18
Source File: KeyValueRanges.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
private boolean isJSON(Buf src, BufRanges contentTypes, int index) {
	if (contentTypes.count > 0) {
		U.must(contentTypes.count > index);
		BufRange ct = contentTypes.get(index);
		return !ct.isEmpty() && ct.str(src.bytes()).startsWith("application/json");

	} else {
		return false;
	}
}
 
Example #19
Source File: Res.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
protected byte[] load(String filename) {
	File file = IO.file(filename);

	if (file.exists()) {

		if (!file.isFile() || file.isDirectory()) {
			return null;
		}

		// a normal file on the file system
		Log.trace("Resource file exists", "name", name, "file", file);

		long lastModif;
		try {
			lastModif = Files.getLastModifiedTime(file.toPath()).to(TimeUnit.MILLISECONDS);

		} catch (IOException e) {
			// maybe it doesn't exist anymore
			lastModif = U.time();
		}

		if (lastModif > this.lastModified || !filename.equals(cachedFileName)) {
			Log.debug("Loading resource file", "name", name, "file", file);
			this.lastModified = file.lastModified();
			this.hidden = file.isHidden();
			return IO.loadBytes(filename);

		} else {
			Log.trace("Resource file not modified", "name", name, "file", file);
			return bytes;
		}

	} else {
		// it might not exist or it might be on the classpath or compressed in a JAR
		Log.trace("Trying to load classpath resource", "name", name, "file", file);
		this.hidden = false;
		return IO.loadBytes(filename);
	}
}
 
Example #20
Source File: WithContextTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void testNestedContext() {
	CountDownLatch latch = new CountDownLatch(JOB_COUNT + 1);

	eq(ctxInfo(), "null:[]:false");

	With.user(new UserInfo("root", U.set("admin"))).run(() -> {
		eq(ctxInfo(), "root:[admin]:true");

		for (int i = 0; i < JOB_COUNT; i++) {
			int n = i;

			With.user(new UserInfo("user" + n, U.set("manager" + n))).run(() -> {
				eq(ctxInfo(), U.frmt("user%s:[manager%s]:true", n, n));
				latch.countDown();
			});
		}

		eq(ctxInfo(), "root:[admin]:true");
		latch.countDown();
	});

	eq(ctxInfo(), "null:[]:false");

	Wait.on(latch, 10, TimeUnit.SECONDS);

	eq(latch.getCount(), 0);

	eq(ctxInfo(), "null:[]:false");
}
 
Example #21
Source File: JPATool.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <E> List<E> getAllEntities() {
	List<E> all = U.list();

	for (EntityType<?> entityType : getEntityTypes()) {
		all.addAll((List<E>) of(entityType.getJavaType()).all());
	}

	return all;
}
 
Example #22
Source File: ConfigHelp.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
private static void showOpts(List<ConfigOption> opts) {
	for (ConfigOption opt : opts) {

		Object def = opt.getDefaultValue();
		String desc = opt.getDesc();

		if (def != null) {
			desc = U.frmt("%s (default: %s)", desc, def);
		}

		opt(opt.getName(), desc);
	}
}
 
Example #23
Source File: JS.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T eval(String js, Map<String, ?> bindings) throws ScriptException {
	ScriptEngineManager factory = new ScriptEngineManager();
	ScriptEngine engine = factory.getEngineByName("JavaScript");

	if (bindings != null) {
		Map<String, Object> map = U.cast(bindings);
		return (T) engine.eval(js, new SimpleBindings(map));
	} else {
		return (T) engine.eval(js);
	}
}
 
Example #24
Source File: WritableOutputStream.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Override
public void writeBytes(byte[] src) {
	try {
		outputStream.write(src);
	} catch (IOException e) {
		throw U.rte(e);
	}
}
 
Example #25
Source File: HttpRoutesImpl.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Override
public boolean hasRouteOrResource(HttpVerb verb, String uri) {
	if (verb == HttpVerb.GET) {
		String[] staticFilesLocations = custom().staticFilesPath();
		if (U.notEmpty(staticFilesLocations)) {
			String filename = Str.triml(uri, '/');
			if (filename.isEmpty()) filename = "index.html";
			if (Res.from(filename, staticFilesLocations).exists()) return true;
		}
	}

	return find(verb, uri) != null;
}
 
Example #26
Source File: JPATool.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public <E> E transactional(Callable<E> action, boolean readOnly) {
	ensureNotInRollbackOnlyTransation();

	EntityTransaction tx = em.getTransaction();
	U.notNull(tx, "transaction");

	boolean newTx = !tx.isActive();

	if (newTx) {
		tx.begin();
	}

	if (readOnly) {
		tx.setRollbackOnly();
	}

	try {
		E result = action.call();

		if (newTx) {
			if (tx.getRollbackOnly()) {
				tx.rollback();
			} else {
				tx.commit();
			}
		}

		return result;

	} catch (Throwable e) {

		if (newTx) {
			if (tx.isActive()) {
				tx.rollback();
			}
		}

		throw U.rte("Transaction execution error, rolled back!", e);
	}
}
 
Example #27
Source File: ConfigurationTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void testPostgresProfile() {
	if (TLS_ENABLED) return;

	Env.setArgs("profiles=postgres");

	eq(Env.profiles(), U.set("postgres", "test"));

	verifyJson("jdbc-postgres-profile", Conf.JDBC.toMap());
	verifyJson("hibernate-postgres-profile", Conf.HIBERNATE.toMap());
	verifyJson("root", Conf.ROOT.toMap());
}
 
Example #28
Source File: JSTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void testEvalJS() throws ScriptException {
	eq(((Number) JS.eval("1 + 2")).intValue(), 3);
	eq(JS.eval("1 + 'ab'"), "1ab");
	eq(JS.eval("(function (x) { return x.toUpperCase(); })('abc')"), "ABC");
	eq(JS.eval("x + y + y.length", U.map("x", "10", "y", "abcd")), "10abcd4");
}
 
Example #29
Source File: HttpPojoApiTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void test7() {
	App.beans(new Object() {
		@POST
		public Object test7(Req req, Resp resp) {
			return U.list("a", 123, true);
		}
	});

	notFound("/");
	onlyPost("/test7");
}
 
Example #30
Source File: ReverseProxy.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
private void process(final Req req, final Resp resp, final ProxyMapping mapping, final int attempts, final long since) {
	final String targetUrl = mapping.getTargetUrl(req);

	Map<String, String> headers = U.map(req.headers());

	headers.remove("transfer-encoding");
	headers.remove("content-length");

	addExtraRequestHeaders(req, headers);

	HttpClient client = getOrCreateClient();

	client.req()
		.verb(req.verb())
		.url(targetUrl)
		.headers(headers)
		.cookies(req.cookies())
		.body(req.body())
		.raw(true)
		.execute((result, error) -> {
			if (error == null) {

				resp.code(result.code());
				resp.body(result.bodyBytes());

				// process the response headers
				SimpleHttpResp proxyResp = new SimpleHttpResp();
				HttpUtils.proxyResponseHeaders(result.headers(), proxyResp);

				if (proxyResp.contentType != null) resp.contentType(proxyResp.contentType);
				if (proxyResp.headers != null) resp.headers().putAll(proxyResp.headers);
				if (proxyResp.cookies != null) resp.cookies().putAll(proxyResp.cookies);

				resp.done();

			} else {
				handleError(error, req, resp, mapping, attempts, since);
			}
		});
}