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

The following examples show how to use org.rapidoid.u.U#or() . 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: IoCContextImpl.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
private Object provideSpecialInstance(Class<?> type, String name) {

		String cls = type.getName();

		if (type.equals(IoCContext.class)) {
			return U.or(wrapper, this);
		}

		if (cls.equals("javax.persistence.EntityManager") && MscOpts.hasRapidoidJPA()) {
			return OptionalJPAUtil.getSharedContextAwareEntityManagerProxy();
		}

		if (cls.equals("javax.persistence.EntityManagerFactory") && MscOpts.hasRapidoidJPA()) {
			return OptionalJPAUtil.getSharedEntityManagerFactoryProxy();
		}

		return null;
	}
 
Example 2
Source File: ReqImpl.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
private void respond(int code, RespBody body) {
	MediaType contentType = HttpUtils.getDefaultContentType();

	if (tokenChanged.get()) {
		HttpUtils.saveTokenBeforeRenderingHeaders(this, token);
	}

	if (sessionChanged.get()) {
		saveSession(session.decorated());
	}

	if (response != null) {
		contentType = U.or(response.contentType(), contentType);
	}

	renderResponse(code, contentType, body);
}
 
Example 3
Source File: Grid.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
protected Tag itemRow(List<Property> properties, Item item) {
	Tag row = tr();

	for (Property prop : properties) {
		Object value = prop.get(item);
		value = U.or(value, "");
		row = row.append(cell(GUI.display(value)));
	}

	if (rowCmd != null) {
		row = row.cmd(rowCmd, item.value());
		row = row.class_("pointer");

	} else {
		String js = onClickScript(item);
		if (U.notEmpty(js)) {
			row = row.onclick(js);
			row = row.class_("pointer");
		}
	}

	return row;
}
 
Example 4
Source File: ConfigImpl.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void set(String key, Object value, boolean overridenByEnv) {
	makeSureIsInitialized();

	String[] keys = key.split("\\.");
	if (keys.length > 1) {
		Config cfg = sub(Arr.sub(keys, 0, -1));
		cfg.set(U.last(keys), value, overridenByEnv);
		return;
	}

	if (overridenByEnv) {
		value = U.or(globalOrArgConfigByRelativeKey(key), value);
	}

	synchronized (base.properties) {
		asMap().put(key, value);
	}
}
 
Example 5
Source File: ResponseRenderer.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
public static byte[] renderMvc(ReqImpl req, Resp resp) {

		Object result = resp.result();
		String content = null;

		if (shouldRenderView(resp)) {
			boolean mandatory = (((RespImpl) resp).hasCustomView());

			ByteArrayOutputStream out = new ByteArrayOutputStream();
			boolean rendered = renderView(req, resp, result, mandatory, out);
			if (rendered) content = new String(out.toByteArray());
		}

		if (content == null) {
			Object respResult = U.or(result, "");
			content = new String(HttpUtils.responseToBytes(req, respResult, MediaType.HTML_UTF_8, null));
		}

		return renderPage(req, content);
	}
 
Example 6
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 7
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 8
Source File: StaticResourcesHandler.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Override
public HttpStatus handle(Channel ctx, boolean isKeepAlive, Req req) {

	if (!HttpUtils.isGetReq(req)) return HttpStatus.NOT_FOUND;

	try {
		String[] staticFilesLocations = customization.staticFilesPath();
		if (!U.isEmpty(staticFilesLocations)) {

			Res res = HttpUtils.staticResource(req, staticFilesLocations);
			if (res != null) {

				StaticFilesSecurity staticFilesSecurity = customization.staticFilesSecurity();

				if (staticFilesSecurity.canServe(req, res)) {
					byte[] bytes = res.getBytesOrNull();

					if (bytes != null) {
						MediaType contentType = U.or(MediaType.getByFileName(res.getName()), MediaType.BINARY);
						HttpIO.INSTANCE.write200(HttpUtils.maybe(req), ctx, isKeepAlive, contentType, bytes);
						return HttpStatus.DONE;
					}
				}
			}
		}

		return HttpStatus.NOT_FOUND;

	} catch (Exception e) {
		return HttpIO.INSTANCE.errorAndDone(req, e, LogLevel.ERROR);
	}
}
 
Example 9
Source File: Pager.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
protected int pageNumber() {
	Integer pageNum = Cls.convert(req().params().get(param), Integer.class);
	int value = U.or(pageNum, initial, min, 1);

	if (min != null) {
		value = Math.max(min, value);
	}

	if (max != null) {
		value = Math.min(max, value);
	}

	return value;
}
 
Example 10
Source File: HttpWrappers.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
private static HttpWrapper[] getConfiguredWrappers(FastHttp http, RouteOptions options) {
	return U.or(
		options.wrappers(), // wrappers specific to the route
		http.custom().wrappers(), // or wrappers for the http setup
		new HttpWrapper[0] // or no wrappers
	);
}
 
Example 11
Source File: HttpWrappers.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
static HttpWrapper[] assembleWrappers(FastHttp http, RouteOptions options) {
	List<HttpWrapper> wrappers = U.list();

	wrappers.add(new HttpAuthWrapper(options.roles()));

	TransactionMode txMode = U.or(options.transaction(), TransactionMode.NONE);
	if (txMode != TransactionMode.NONE) {
		wrappers.add(new HttpTxWrapper(txMode));
	}

	Collections.addAll(wrappers, getConfiguredWrappers(http, options));

	return U.arrayOf(HttpWrapper.class, wrappers);
}
 
Example 12
Source File: GlobalCfg.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static String get(String name) {
	String value = U.or(System.getProperty(name), System.getenv(name));
	if (value != null) return value;

	value = U.or(System.getProperty(name.toUpperCase()), System.getenv(name.toUpperCase()));
	if (value != null) return value;

	value = U.or(System.getProperty(name.toLowerCase()), System.getenv(name.toLowerCase()));
	return value;
}
 
Example 13
Source File: Env.java    From rapidoid with 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 14
Source File: OAuthTokenHandler.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
@Override
public Object execute(Req req) throws Exception {
	String code = req.param("code");
	String state = req.param("state");

	Log.debug("Received OAuth code", "code", code, "state", state);

	if (code != null && !U.isEmpty(state)) {

		String id = clientId.str().get();
		String secret = clientSecret.str().get();

		char statePrefix = state.charAt(0);
		U.must(statePrefix == 'P' || statePrefix == 'N', "Invalid OAuth state prefix!");
		state = state.substring(1);

		U.must(stateCheck.isValidState(state, secret, req.sessionId()), "Invalid OAuth state!");

		boolean popup = statePrefix == 'P';
		Log.debug("OAuth validated", "popup", popup);

		String domain = oauthDomain.getOrNull();
		String redirectUrl = U.notEmpty(domain) ? domain + callbackPath : HttpUtils.constructUrl(req, callbackPath);

		TokenRequestBuilder reqBuilder = OAuthClientRequest.tokenLocation(provider.getTokenEndpoint())
			.setGrantType(GrantType.AUTHORIZATION_CODE)
			.setClientId(id)
			.setClientSecret(secret)
			.setRedirectURI(redirectUrl)
			.setCode(code);

		OAuthClientRequest request = paramsInBody() ? reqBuilder.buildBodyMessage() : reqBuilder.buildBodyMessage();

		OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());

		String accessToken = token(request, oAuthClient);

		String profileUrl = Msc.fillIn(provider.getProfileEndpoint(), "token", accessToken);

		OAuthClientRequest bearerClientRequest = new OAuthBearerClientRequest(profileUrl).setAccessToken(
			accessToken).buildQueryMessage();

		OAuthResourceResponse res = oAuthClient.resource(bearerClientRequest,
			org.apache.oltu.oauth2.common.OAuth.HttpMethod.GET, OAuthResourceResponse.class);

		U.must(res.getResponseCode() == 200, "OAuth response error!");

		Map<String, Object> auth = JSON.parseMap(res.getBody());

		String email = (String) U.or(auth.get("email"), auth.get("emailAddress"));
		String firstName = (String) U.or(auth.get("firstName"), U.or(auth.get("first_name"), auth.get("given_name")));
		String lastName = (String) U.or(auth.get("lastName"), U.or(auth.get("last_name"), auth.get("family_name")));
		String name = U.or((String) auth.get("name"), firstName + " " + lastName);

		String username = email;
		Set<String> roles = customization.rolesProvider().getRolesForUser(req, username);

		UserInfo user = new UserInfo(username, roles);
		user.name = name;
		user.email = email;
		user.oauthProvider = provider.getName();
		user.oauthId = String.valueOf(auth.get("id"));

		req.response().authorize(user);

		return req.response().redirect("/");

	} else {
		String error = req.param("error");
		if (error != null) {
			Log.warn("OAuth error", "error", error);
			throw U.rte("OAuth error!");
		}
	}

	throw U.rte("Invalid OAuth request!");
}
 
Example 15
Source File: Msc.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
public static ErrCodeAndMsg getErrorCodeAndMsg(Throwable err) {
	Throwable cause = Msc.rootCause(err);

	int code;
	String defaultMsg;
	String msg = cause.getMessage();

	if (cause instanceof SecurityException) {
		code = 403;
		defaultMsg = "Access Denied!";

	} else if (cause.getClass().getSimpleName().equals("NotFound")) {
		code = 404;
		defaultMsg = "The requested resource could not be found!";

	} else if (Msc.isValidationError(cause)) {
		code = 422;
		defaultMsg = "Validation Error!";

		if (cause.getClass().getName().equals("javax.validation.ConstraintViolationException")) {
			Set<ConstraintViolation<?>> violations = ((ConstraintViolationException) cause).getConstraintViolations();

			StringBuilder sb = new StringBuilder();
			sb.append("Validation failed: ");

			for (Iterator<ConstraintViolation<?>> it = U.safe(violations).iterator(); it.hasNext(); ) {
				ConstraintViolation<?> v = it.next();

				sb.append(v.getRootBeanClass().getSimpleName());
				sb.append(".");
				sb.append(v.getPropertyPath());
				sb.append(" (");
				sb.append(v.getMessage());
				sb.append(")");

				if (it.hasNext()) {
					sb.append(", ");
				}
			}

			msg = sb.toString();
		}

	} else {
		code = 500;
		defaultMsg = "Internal Server Error!";
	}

	msg = U.or(msg, defaultMsg);
	return new ErrCodeAndMsg(code, msg);
}
 
Example 16
Source File: AbstractInput.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
protected Object _valOr(Object initial) {
	Var<?> _var = _var();
	Object value = _var != null ? _var.get() : null;
	return U.or(value, initial);
}
 
Example 17
Source File: AbstractInput.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
protected String _name() {
	return U.or(name, var != null ? var.name() : null);
}
 
Example 18
Source File: ReqImpl.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
@Override
public String header(String name, String defaultValue) {
	return U.or(headers().get(name.toLowerCase()), defaultValue);
}
 
Example 19
Source File: AbstractModel.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> T getExtra(String name, T defaultValue) {
	return (T) U.or(extras.get(name), defaultValue);
}
 
Example 20
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;
	}