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

The following examples show how to use org.rapidoid.u.U#notEmpty() . 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: HtmlPage.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
private void setupAssets(IReqInfo req, Map<String, Object> model) {
	String view = req.view();

	if (req.hasRoute(HttpVerb.GET, commonJs)) {
		js().add(commonJs);
	}

	if (req.hasRoute(HttpVerb.GET, commonCss)) {
		css().add(commonCss);
	}

	if (U.notEmpty(view)) {
		String pageJs = "/" + view + ".js";
		if (req.hasRoute(HttpVerb.GET, pageJs)) {
			js().add(pageJs);
		}

		String pageCss = "/" + view + ".css";
		if (req.hasRoute(HttpVerb.GET, pageCss)) {
			css().add(pageCss);
		}
	}

	model.put("js", withContextPath(js(), req.contextPath()));
	model.put("css", withContextPath(css(), req.contextPath()));
}
 
Example 2
Source File: ReqImpl.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
private void parseRequestBodyUsing(HttpRequestBodyParser parser) {
	if (U.notEmpty(body())) {

		Map<String, ?> bodyData = null;

		try {
			bodyData = parser.parseRequestBody(this, body);

		} catch (Exception e) {
			Log.error("Couldn't parse the request body! Please make sure the correct content type is specified in the request header!", e);
		}

		if (bodyData != null) {
			posted.putAll(bodyData);
		}
	}
}
 
Example 3
Source File: Conf.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
private static void activateRootConfig() {
	U.must(Env.isInitialized());

	String root = Env.root();

	if (U.notEmpty(root) && !APP.has("jar")) {
		APP.set("jar", Msc.path(root, "app.jar"));
	}

	String appJar = APP.entry("jar").str().getOrNull();
	if (U.notEmpty(appJar)) {
		ClasspathUtil.appJar(appJar);
	}

	boolean fancyByDefault = Env.dev() || System.console() != null;
	Log.options().fancy(LOG.entry("fancy").bool().or(fancyByDefault));

	LogLevel logLevel = LOG.entry("level").to(LogLevel.class).getOrNull();
	if (logLevel != null && !Env.test()) {
		Log.setLogLevel(logLevel);
	}

	if (GlobalCfg.quiet()) {
		Log.setLogLevel(LogLevel.ERROR); // overwrite the configured log level in quiet mode
	}
}
 
Example 4
Source File: JPA.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
public static void bind(Query query, Map<String, ?> namedArgs, Object... args) {
	if (args != null) {
		for (int i = 0; i < args.length; i++) {
			query.setParameter(i + 1, args[i]);
		}
	}

	if (namedArgs != null) {
		for (Parameter<?> param : query.getParameters()) {
			String name = param.getName();
			if (U.notEmpty(name)) {
				U.must(namedArgs.containsKey(name), "A named argument wasn't specified for the named JPQL parameter: %s", name);
				query.setParameter(name, Cls.convert(namedArgs.get(name), param.getParameterType()));
			}
		}
	}
}
 
Example 5
Source File: IoCContextImpl.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
private <T> T instantiate(Class<T> type, Map<String, Object> properties) {

		ClassMetadata meta = meta(type);

		if (U.notEmpty(meta.injectableConstructors)) {
			U.must(meta.injectableConstructors.size() == 1, "Found more than 1 @Inject-annotated constructor for: %s", type);

			Constructor<?> constr = U.single(meta.injectableConstructors);
			Class<?>[] paramTypes = constr.getParameterTypes();
			Object[] args = new Object[paramTypes.length];

			for (int i = 0; i < args.length; i++) {
				Class<?> paramType = paramTypes[i];
				String paramName = null; // FIXME inject by name
				args[i] = provideIoCInstanceOf(null, paramType, paramName, properties, false);
			}

			return Cls.invoke(constr, args);

		} else if (meta.defaultConstructor != null) {
			return Cls.invoke(meta.defaultConstructor);

		} else {
			throw U.illegal("Cannot find a default nor @Inject-annotated constructor for: %s", type);
		}
	}
 
Example 6
Source File: IoCContextImpl.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
private boolean processMetadata(ClassMetadata meta) {
	boolean processed = false;

	if (U.notEmpty(meta.typesToManage)) {
		manage(meta.typesToManage);
		processed = true;
	}

	if (U.notEmpty(meta.packagesToScan)) {
		List<Class<?>> classes = Scan.annotated(IoC.ANNOTATIONS).in(meta.packagesToScan).loadAll();

		if (U.notEmpty(classes)) {
			manage(classes);
			processed = true;
		}
	}

	return processed;
}
 
Example 7
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 8
Source File: App.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static synchronized boolean scan(String... packages) {
	String appPath = Conf.APP.entry("path").str().getOrNull();

	if (U.notEmpty(appPath)) {
		packages = appPath.split("\\s*,\\s*");
		App.path(packages);
	}

	List<Class<?>> beans = App.findBeans(packages);
	beans(beans.toArray());
	return !beans.isEmpty();
}
 
Example 9
Source File: HttpUtils.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static String resName(String path) {
	if (U.notEmpty(path) && REGEX_VALID_HTTP_RESOURCE.matcher(path).matches() && !path.contains("..")) {
		String res = Str.triml(path, "/");
		return res.isEmpty() ? "index" : Str.trimr(res, ".html");

	} else {
		throw U.rte("Invalid path!");
	}
}
 
Example 10
Source File: RespImpl.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Override
public Resp cookie(String name, String value, String... extras) {

	if (U.notEmpty(extras)) {
		value += "; " + U.join("; ", extras);
	}

	if (!cookieContainsPath(extras)) {
		value += "; path=" + HttpUtils.cookiePath();
	}

	cookies().put(name, value);

	return this;
}
 
Example 11
Source File: HttpClientUtil.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
static HttpRequestBase createRequest(HttpReq config) {

		Map<String, String> headers = U.safe(config.headers());
		Map<String, String> cookies = U.safe(config.cookies());

		String url = config.url();

		url = Msc.urlWithProtocol(url);

		HttpRequestBase req = createReq(config, url);

		for (Map.Entry<String, String> e : headers.entrySet()) {
			req.addHeader(e.getKey(), e.getValue());
		}

		if (U.notEmpty(cookies)) {
			req.addHeader("Cookie", joinCookiesAsHeader(cookies));
		}

		switch (config.verb()) {
			case POST:
			case PUT:
			case PATCH:
				HttpEntityEnclosingRequestBase entityEnclosingReq = (HttpEntityEnclosingRequestBase) req;

				if (config.body() != null) {
					entityEnclosingReq.setEntity(byteBody(config));

				} else if (U.notEmpty(config.data()) || U.notEmpty(config.files())) {
					entityEnclosingReq.setEntity(paramsBody(config.data(), config.files()));
				}
				break;
		}

		req.setConfig(reqConfig(config));

		return req;
	}
 
Example 12
Source File: Res.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
private static Res relative(String filename, String... possibleLocations) {
	File file = new File(filename);

	if (file.isAbsolute()) {
		return absolute(file);
	}

	if (U.isEmpty(possibleLocations)) {
		possibleLocations = DEFAULT_LOCATIONS;
	}

	U.must(!U.isEmpty(filename), "Resource filename must be specified!");
	U.must(!file.isAbsolute(), "Expected relative filename!");

	String root = Env.root();
	if (U.notEmpty(Env.root())) {
		String[] loc = new String[possibleLocations.length * 2];

		for (int i = 0; i < possibleLocations.length; i++) {
			loc[2 * i] = Msc.path(root, possibleLocations[i]);
			loc[2 * i + 1] = possibleLocations[i];
		}

		possibleLocations = loc;
	}

	return create(filename, possibleLocations);
}
 
Example 13
Source File: Grid.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
protected String onClickScript(Item item) {
	String uri;
	if (toUri != null) {
		uri = Lmbd.eval(toUri, item.value());
	} else {
		uri = GUI.uriFor(item.value());
		if (U.notEmpty(uri)) {
			uri = Msc.uri(uri, "view");
		}
	}

	return U.notEmpty(uri) ? U.frmt("Rapidoid.goAt('%s');", uri) : null;
}
 
Example 14
Source File: ConfigImpl.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
private void notifyChangeListener(ConfigChangeListener listener, Config previousConfig) {
	mustBeRoot();

	Config cfg = U.notEmpty(listener.keys) ? sub(listener.keys) : this;
	ConfigChanges changes = cfg.getChangesSince(previousConfig);

	if (changes.count() > 0) {
		try {
			listener.operation.execute(changes);
		} catch (Exception e) {
			Log.error("Error occurred in a configuration changes listener!", e);
		}
	}
}
 
Example 15
Source File: ConfigImpl.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
protected synchronized void initialize() {
	mustBeRoot();

	List<String> loaded = U.list();

	base.initial.putAll(Env.argsAsMap());

	overrideByEnv();

	if (useBuiltInDefaults()) {
		ConfigLoaderUtil.loadBuiltInConfig(this, loaded);
	}

	boolean useConfigFiles = U.notEmpty(getFilenameBase());

	if (useConfigFiles) {
		ConfigLoaderUtil.loadConfig(this, loaded);
	}

	overrideByEnv();

	substitutePlaceholders();

	Conf.applyConfig(this);

	if (!loaded.isEmpty()) {
		Log.info("Loaded configuration", "namespace", getFilenameBase(), "!files", loaded);
	} else {
		if (useConfigFiles) {
			Log.warn("Didn't find any configuration files", "path", getPath());
		}
	}
}
 
Example 16
Source File: Log.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
private static void printKeyValue(Appendable out, String key, Object value) throws IOException {
	boolean bold = key.startsWith("!");
	if (bold) {
		key = key.substring(1);
	}

	if (key.equalsIgnoreCase("password") || key.endsWith("password")) {
		if (value instanceof String) {
			if (U.notEmpty((String) value)) {
				value = "*****";
			}
		}
	}

	out.append(" | ");
	out.append(key);
	out.append(" = ");

	appendFancy(out, value, bold);

	if (value instanceof Throwable) {
		Throwable err = (Throwable) value;

		if (options.stackTraceOnStdErr()) {
			err.printStackTrace();

		} else {
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			err.printStackTrace(new PrintStream(stream));
			out.append("\n");
			out.append(stream.toString());
		}
	}
}
 
Example 17
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 18
Source File: Field.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
protected Tag field() {

		String name = this.prop.name();
		String desc = U.or(this.desc, prop.caption(), name);

		FieldType type = this.type;
		if (type == null) {
			type = mode != FormMode.SHOW ? getPropertyFieldType(prop) : FieldType.LABEL;
		}

		Collection<?> options = this.options;
		if (options == null) {
			options = getPropertyOptions(prop);
		}

		Boolean required = this.required();
		if (required == null) {
			required = isFieldRequired(prop);
		}

		Var<Object> var = initVar(item, prop, mode, required);

		desc = U.or(desc, name) + ": ";

		Object inp = input == null ? input_(name, desc, type, options, var) : input;

		Tag lbl = label;
		Object inputWrap;

		if (type == FieldType.RADIOS || type == FieldType.CHECKBOXES) {
			inp = layout == FormLayout.VERTICAL ? div(inp) : span(inp);
		}

		if (type == FieldType.CHECKBOX) {
			if (label == null) {
				lbl = null;
			}

			inp = div(GUI.label(inp, desc)).class_("checkbox");

			inputWrap = layout == FormLayout.HORIZONTAL ? div(inp).class_("col-sm-offset-4 col-sm-8") : inp;

		} else {
			if (label == null) {
				// if it doesn't have custom label
				if (layout != FormLayout.INLINE) {
					lbl = GUI.label(desc);
				} else {
					if (type == FieldType.RADIOS) {
						lbl = GUI.label(desc);
					} else {
						lbl = null;
					}
				}
			}

			if (layout == FormLayout.HORIZONTAL && lbl != null) {
				lbl = lbl.class_("col-sm-4 control-label");
			}

			inputWrap = layout == FormLayout.HORIZONTAL ? div(inp).class_("col-sm-8") : inp;
		}

		boolean hasErrors = U.notEmpty(var.errors());
		Tag err = hasErrors ? span(U.join(", ", var.errors())).class_("field-error") : null;

		Tag group = lbl != null ? div(lbl, inputWrap, err) : div(inputWrap, err);
		group = group.class_(hasErrors ? "form-group with-validation-errors" : "form-group");

		if (hasErrors) {
			group = group.attr("data-has-validation-errors", "yes");
			GUI.markValidationErrors();
		}

		return group;
	}
 
Example 19
Source File: AbstractInput.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
protected Var<?> _var() {
	return var != null ? var : U.notEmpty(name) ? GUI.var(name) : null;
}
 
Example 20
Source File: ResponseRenderer.java    From rapidoid with Apache License 2.0 3 votes vote down vote up
private static boolean shouldRenderView(Resp resp) {
	if (!resp.mvc()) return false;

	Object result = resp.result();
	if (result == null) return true;

	if (((RespImpl) resp).hasCustomView()) return U.notEmpty(resp.view());

	return true;
}