Java Code Examples for org.rapidoid.u.U#isEmpty()

The following examples show how to use org.rapidoid.u.U#isEmpty() . 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: IO.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
public static Map<String, String> loadMap(String filename) {
	InputStream input = resourceAsStream(filename);
	if (input == null) {
		return null;
	}

	BufferedReader reader = new BufferedReader(new InputStreamReader(input));
	Map<String, String> linesMap = U.map();

	try {
		String line;
		while ((line = reader.readLine()) != null) {
			if (!U.isEmpty(line)) {
				String[] parts = line.split("=", 2);
				linesMap.put(parts[0], parts.length > 1 ? parts[1] : "");
			}
		}
	} catch (IOException e) {
		throw U.rte(e);
	}

	return linesMap;
}
 
Example 2
Source File: Secure.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
protected static boolean hasRole(String username, Set<String> roles, String role) {
	if (hasSpecialRoleInDevMode(username, role)) {
		return true;
	}

	if (role.equalsIgnoreCase(Role.LOGGED_IN)) {
		return !U.isEmpty(username);
	}

	for (String r : roles) {
		if (r.equalsIgnoreCase(role)) {
			return true;
		}
	}

	return false;
}
 
Example 3
Source File: Secure.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
public static boolean isSharedWith(String username, Object record) {
	if (U.isEmpty(username) || record == null) {
		return false;
	}

	Object sharedWith = Beany.getPropValue(record, "sharedWith", null);

	if (sharedWith != null && sharedWith instanceof Collection<?>) {
		for (Object user : (Collection<?>) sharedWith) {
			if (username.equalsIgnoreCase(Beany.getPropValue(user, "username", ""))) {
				return true;
			}
		}
	}

	return false;
}
 
Example 4
Source File: HttpManagedHandlerDecorator.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
private void handleWithWrappers(Channel channel, boolean isKeepAlive, MediaType contentType,
                                Req req, HttpWrapper[] wrappers) {
	Object result;

	try {

		if (!U.isEmpty(wrappers)) {
			result = wrap(channel, isKeepAlive, req, 0, wrappers);
		} else {
			result = handleReqAndPostProcess(channel, isKeepAlive, req);
		}

	} catch (Throwable e) {
		result = e;
	}

	complete(channel, isKeepAlive, contentType, req, result);
}
 
Example 5
Source File: AppDeployMojo.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
private void initConfig() {
	Config config = new ConfigImpl("deploy");
	config.setPath(project.getBasedir().toString());

	Map<String, Object> cfg = config.toMap();

	if (U.isEmpty(token)) token = U.safe(U.str(cfg.get("token")));

	if (U.isEmpty(servers)) {
		Object srvrs = cfg.get("servers");

		if (srvrs instanceof String) {
			servers = (String) srvrs;

		} else if (srvrs instanceof List) {
			List list = (List) srvrs;
			servers = U.join(", ", list);
		}
	}
}
 
Example 6
Source File: HttpAuthWrapper.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Override
public Object wrap(final Req req, final HandlerInvocation invocation) throws Exception {
	TokenAuthData auth = HttpUtils.getAuth(req);

	String username = auth != null ? auth.user : null;

	if (U.isEmpty(username)) {
		HttpUtils.clearUserData(req);
	}

	Set<String> roles = userRoles(req, username);
	Set<String> scope = auth != null ? auth.scope : null;

	if (U.notEmpty(requiredRoles) && !Secure.hasAnyRole(username, roles, requiredRoles)) {
		throw new SecurityException("The user doesn't have the required roles!");
	}

	Ctx ctx = Ctxs.required();
	ctx.setUser(new UserInfo(username, roles, scope));

	return invocation.invoke();
}
 
Example 7
Source File: Auth.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
public static boolean login(String username, String password) {
	if (U.isEmpty(username) || password == null) {
		return false;
	}

	if (!Conf.USERS.has(username)) {
		return false;
	}

	Config user = Conf.USERS.sub(username);

	if (user.isEmpty()) {
		return false;
	}

	String pass = user.entry("password").str().getOrNull();
	String hash = user.entry("hash").str().getOrNull();

	return (pass != null && U.eq(password, pass)) || (hash != null && Crypto.passwordMatches(password, hash));
}
 
Example 8
Source File: PojoHandlersSetup.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
private String uriOf(Annotation ann) {
	Method valueMethod = Cls.getMethod(ann.getClass(), "value");
	String uri = Cls.invoke(valueMethod, ann);

	if (U.isEmpty(uri)) {
		Method uriMethod = Cls.getMethod(ann.getClass(), "uri");
		uri = Cls.invoke(uriMethod, ann);
	}

	return uri;
}
 
Example 9
Source File: Msc.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
private static String constructPath(String separator, boolean preserveFirstSegment, boolean uriEscape, String... parts) {
	String s = "";

	for (int i = 0; i < parts.length; i++) {
		String part = U.safe(parts[i]);

		// trim '/'s and '\'s
		if (!preserveFirstSegment || i > 0) {
			part = Str.triml(part, "/");
		}

		if (!preserveFirstSegment || part.length() > 1 || i > 0) {
			part = Str.trimr(part, "/");
			part = Str.trimr(part, "\\");
		}

		if (!U.isEmpty(part)) {
			if (!s.isEmpty() && !s.endsWith(separator)) {
				s += separator;
			}

			if (uriEscape) part = URIs.urlEncode(part);

			s += part;
		}
	}

	return s;
}
 
Example 10
Source File: LogbackUtil.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static void setupLogger() {
	ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();

	if (loggerFactory instanceof LoggerContext) {
		LoggerContext lc = (LoggerContext) loggerFactory;

		if (U.isEmpty(lc.getCopyOfPropertyMap())) {
			Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME);
			root.setLevel(Level.INFO);
		}
	}
}
 
Example 11
Source File: Environment.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public synchronized void setProfiles(String... activeProfiles) {

		if (U.isEmpty(profiles)) {
			profiles = Coll.synchronizedSet();
			profilesView = Collections.unmodifiableSet(profiles);
		}

		Collections.addAll(this.profiles, activeProfiles);

		this.mode = null;
		initModeAndProfiles();

		if (!silent())
			Log.info("Activating custom profiles", "!activating", activeProfiles, "!resulting profiles", this.profiles, "!resulting mode", this.mode);
	}
 
Example 12
Source File: ReqImpl.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
private void parseRequestBody() {
	if (U.isEmpty(body())) return;

	String contentTypeHeader = header("Content-Type", "application/json");

	if (contentTypeHeader.startsWith("application/json")) {
		parseRequestBodyUsing(custom().jsonRequestBodyParser());

	} else if (contentTypeHeader.startsWith("application/xml")) {
		parseRequestBodyUsing(custom().xmlRequestBodyParser());

	} else {
		throw U.rte("Couldn't parse the request body - unsupported content type: " + contentTypeHeader);
	}
}
 
Example 13
Source File: ClasspathScanner.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
private static List<String> scanClasses(ScanParams params) {
	String[] pkgs = params.in();

	String rootPackage = ClasspathUtil.getRootPackage();
	if (U.isEmpty(pkgs)) {
		pkgs = rootPackage != null ? new String[]{rootPackage} : new String[]{""};
	}

	long startingAt = U.time();

	String regex = params.matching();
	Pattern pattern = U.notEmpty(regex) ? Pattern.compile(regex) : null;

	if (regex != null) {
		Log.info("Scanning classpath", "!annotated", Msc.annotations(params.annotated()), "!packages", Arrays.toString(pkgs), "!matching", regex);
	} else {
		Log.info("Scanning classpath", "!annotated", Msc.annotations(params.annotated()), "!packages", Arrays.toString(pkgs));
	}

	Set<String> classpath = U.notEmpty(params.classpath()) ? U.set(params.classpath()) : ClasspathUtil.getClasspath();
	AtomicInteger searched = new AtomicInteger();
	Set<String> classes = U.set();

	for (String pkg : pkgs) {
		classes.addAll(retrieveClasses(classpath, pkg, params.annotated(), params.bytecodeFilter(), pattern, params.classLoader(), searched));
	}

	List<String> classList = U.list(classes);

	long timeMs = U.time() - startingAt;

	Log.info("Finished classpath scan", "time", Msc.maybeMasked(timeMs) + "ms", "searched", searched.get(), "!found", Msc.classNames(classList));

	return classList;
}
 
Example 14
Source File: Dates.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static Date date(String value) {
	if (U.isEmpty(value)) {
		return null;
	}

	String[] parts = value.split("(\\.|-|/)");

	int a = parts.length > 0 ? U.num(parts[0]) : -1;
	int b = parts.length > 1 ? U.num(parts[1]) : -1;
	int c = parts.length > 2 ? U.num(parts[2]) : -1;

	switch (parts.length) {
		case 3:
			if (isDay(a) && isMonth(b) && isYear(c)) {
				return date(a, b, c);
			} else if (isYear(a) && isMonth(b) && isDay(c)) {
				return date(c, b, a);
			}
			break;
		case 2:
			if (isDay(a) && isMonth(b)) {
				return date(a, b, thisYear());
			}
			break;
		default:
	}

	throw U.rte("Invalid date: " + value);
}
 
Example 15
Source File: Secure.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static boolean isOwnerOf(String username, Object record) {
	if (U.isEmpty(username) || record == null) {
		return false;
	}

	Object owner = Beany.getPropValue(record, "createdBy", null);

	return owner instanceof String && username.equalsIgnoreCase((String) owner);
}
 
Example 16
Source File: Grid.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
private Object renderGridPage(Pager pager, Iterable<?> rows, boolean isLastPage) {
	Iterator<?> it = rows.iterator();
	boolean hasData = it.hasNext();

	if (pager != null && (isLastPage || !hasData)) {
		pager.max(pager.pageNumber());
	}

	if (!hasData) {
		return U.list(noDataAvailable(), pager); // no data
	}

	Class<?> type = it.next().getClass();

	Items itemsModel;
	if (rows instanceof Items) {
		itemsModel = (Items) rows;
	} else {
		itemsModel = Models.beanItems(type, U.array(rows));
	}

	final List<Property> props = itemsModel.properties(columns);
	boolean ordered = !U.isEmpty(orderBy);
	Var<String> order = null;
	String currentOrder = orderBy;

	if (ordered) {
		order = GUI.var("_o" + seq("order"), orderBy);
		currentOrder = order.get();
		itemsModel = itemsModel.orderedBy(currentOrder);
	}

	Tag header = tableHeader(props, order);
	Tag body = tableBody(props, itemsModel);

	return fullTable(header, body, pager);
}
 
Example 17
Source File: HttpUtils.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static Map<String, Serializable> initAndDeserializeToken(Req req) {
	String token = req.cookie(TOKEN, null);

	if (U.isEmpty(token)) {
		token = req.data(TOKEN, null);
	}

	return Tokens.deserialize(token);
}
 
Example 18
Source File: PojoHandlersSetup.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
private String pathOf(Method method, String ctxPath, String uri) {
	String path = !U.isEmpty(uri) ? uri : method.getName();
	return Msc.uri(ctxPath, path);
}
 
Example 19
Source File: ParamRetrievers.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
private static String name(String methodParamName, String annotatedName) {
	return !U.isEmpty(annotatedName) ? annotatedName : methodParamName;
}
 
Example 20
Source File: Booter.java    From rapidoid with Apache License 2.0 3 votes vote down vote up
public Booter jpa(String... packages) {
	if (U.isEmpty(packages)) packages = App.path();

	JPA.bootstrap(packages);

	return this;
}