Java Code Examples for org.rapidoid.u.U

The following examples show how to use org.rapidoid.u.U. 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: apollo   Source File: RestServer.java    License: 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 2
Source Project: rapidoid   Source File: AbstractCommand.java    License: 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 3
Source Project: rapidoid   Source File: Secure.java    License: 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 4
Source Project: rapidoid   Source File: OpenAPIDemo.java    License: 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 5
Source Project: rapidoid   Source File: Cls.java    License: 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 6
Source Project: rapidoid   Source File: Coll.java    License: 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 7
Source Project: rapidoid   Source File: RespImpl.java    License: 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 8
Source Project: rapidoid   Source File: X.java    License: 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 9
Source Project: rapidoid   Source File: ClasspathUtil.java    License: 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 10
Source Project: rapidoid   Source File: IO.java    License: 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 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 12
Source Project: rapidoid   Source File: Highlight.java    License: 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 13
Source Project: rapidoid   Source File: JSTest.java    License: 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 Project: rapidoid   Source File: Cls.java    License: 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 15
Source Project: rapidoid   Source File: Str.java    License: 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 16
Source Project: rapidoid   Source File: IO.java    License: Apache License 2.0 5 votes vote down vote up
public static List<String> readLines(BufferedReader reader) {
	List<String> lines = U.list();

	try {
		String line;
		while ((line = reader.readLine()) != null) {
			lines.add(line);
		}
	} catch (IOException e) {
		throw U.rte(e);
	}

	return lines;
}
 
Example 17
Source Project: rapidoid   Source File: Env.java    License: Apache License 2.0 5 votes vote down vote up
static String initial(String key) {
	Map<String, String> args = Env.argsAsMap();

	return (String) U.or(
		args.get(key),
		args.get(key.toLowerCase()),
		args.get(key.toUpperCase()),
		Env.properties().get(key)
	);
}
 
Example 18
Source Project: rapidoid   Source File: JPATool.java    License: 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 19
Source Project: rapidoid   Source File: LambdaParamNamesTest.java    License: 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 20
Source Project: rapidoid   Source File: Res.java    License: 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 21
Source Project: rapidoid   Source File: Customization.java    License: Apache License 2.0 5 votes vote down vote up
public String[] templatesPath() {

		if (templateLoader != null || defaults == null) {
			U.must(templateLoader instanceof DefaultTemplateLoader, "A custom template loader was configured!");
			return ((DefaultTemplateLoader) templateLoader).templatesPath();

		} else {
			return defaults.templatesPath();
		}
	}
 
Example 22
Source Project: rapidoid   Source File: Secure.java    License: Apache License 2.0 5 votes vote down vote up
public static DataPermissions getObjectPermissions(String username, Set<String> roles, Object target) {
	U.notNull(target, "target");
	Class<?> clazz = target.getClass();
	clazz = Cls.unproxy(clazz);

	if (Collection.class.isAssignableFrom(clazz) || Map.class.isAssignableFrom(clazz)
		|| Object[].class.isAssignableFrom(clazz)) {
		return DataPermissions.ALL;
	}

	if (!hasRoleBasedAccess(username, roles, clazz, null)) {
		return DataPermissions.NONE;
	}

	CanRead canRead = Metadata.classAnnotation(clazz, CanRead.class);
	CanInsert canInsert = Metadata.classAnnotation(clazz, CanInsert.class);
	CanChange canChange = Metadata.classAnnotation(clazz, CanChange.class);
	CanDelete canDelete = Metadata.classAnnotation(clazz, CanDelete.class);
	CanManage canManage = Metadata.classAnnotation(clazz, CanManage.class);

	if (canRead == null && canInsert == null && canChange == null && canDelete == null && canManage == null) {
		return DataPermissions.ALL;
	}

	boolean read = canRead == null || hasAnyRole(username, roles, roles(canRead.value()), clazz, target);

	boolean insert = canInsert != null && hasAnyRole(username, roles, roles(canInsert.value()), clazz, target);
	boolean change = canChange != null && hasAnyRole(username, roles, roles(canChange.value()), clazz, target);
	boolean delete = canDelete != null && hasAnyRole(username, roles, roles(canDelete.value()), clazz, target);

	boolean manage = canManage != null && hasAnyRole(username, roles, roles(canManage.value()), clazz, target);
	insert |= manage;
	change |= manage;
	delete |= manage;

	return DataPermissions.from(read, insert, change, delete);
}
 
Example 23
Source Project: rapidoid   Source File: CancelWatchTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCancelAll() {
	// expecting a lot of content with frequent changes
	String userHome = System.getProperty("user.home");

	Operation<String> noOp = obj -> {
		// do nothing
	};

	for (int i = 0; i < 30; i++) {
		Watch.dir(userHome, noOp);
		U.sleep(100);
		Watch.cancelAll();
	}
}
 
Example 24
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 25
Source Project: rapidoid   Source File: ConfigImpl.java    License: Apache License 2.0 5 votes vote down vote up
private boolean substitutePlaceholders(final Map<String, String> flat, final Set<String> changedKeys) {
	final BoolWrap changed = new BoolWrap();

	for (Map.Entry<String, String> e : U.map(flat).entrySet()) {
		final String cfgKey = e.getKey();
		String val = e.getValue();

		if (val.contains("${")) {

			val = Str.replace(val, "\\$\\{([^\\}]+)\\}", src -> {

				String name = src[1];
				Object value = flat.get(name);

				if (value == null) {
					value = GlobalCfg.get(name);
				}

				if (value == null) {
					value = getSpecialValue(name);
				}

				U.must(value != null, "Cannot find configuration entry '%s' for key '%s'!", name, cfgKey);

				changed.value = true;
				changedKeys.add(cfgKey);

				return value.toString();
			});

			flat.put(cfgKey, val);
		}
	}

	return changed.value;
}
 
Example 26
Source Project: rapidoid   Source File: BeanListItems.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private List<Property> filterProperties(String[] properties) {
	if (isEmpty() || U.isEmpty(properties)) {
		return Collections.EMPTY_LIST;
	}

	Object item0 = get(0).value();
	return Models.propertiesOf(item0, properties);
}
 
Example 27
Source Project: rapidoid   Source File: KeyValueRanges.java    License: 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 28
Source Project: rapidoid   Source File: WritableOutputStream.java    License: 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 29
Source Project: rapidoid   Source File: HttpRoutesImpl.java    License: 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 30
Source Project: rapidoid   Source File: JPATool.java    License: 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);
	}
}