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

The following examples show how to use org.rapidoid.u.U#must() . 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: ClassMetadata.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
public static Set<Field> getInjectableFields(Class<?> clazz) {
	Set<Field> fields = U.set();

	for (Class<? extends Annotation> annotation : INJECTION_ANNOTATIONS) {
		fields.addAll(Cls.getFieldsAnnotated(clazz, annotation));
	}

	if (MscOpts.hasJPA()) {
		Class<Annotation> javaxPersistenceContext = Cls.get("javax.persistence.PersistenceContext");
		List<Field> emFields = Cls.getFieldsAnnotated(clazz, javaxPersistenceContext);

		for (Field emField : emFields) {
			U.must(emField.getType().getName().equals("javax.persistence.EntityManager"), "Expected EntityManager type!");
		}

		fields.addAll(emFields);
	}

	return fields;
}
 
Example 2
Source File: TokenAuth.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
public static UserInfo login(Req req, String username, String password) {

		LoginProvider loginProvider = Customization.of(req).loginProvider();
		U.must(loginProvider != null, "A login provider wasn't set!");

		RolesProvider rolesProvider = Customization.of(req).rolesProvider();
		U.must(rolesProvider != null, "A roles provider wasn't set!");

		try {
			boolean success = loginProvider.login(req, username, password);

			if (success) {
				Set<String> roles = rolesProvider.getRolesForUser(req, username);

				return new UserInfo(username, roles);
			}

		} catch (Throwable e) {
			throw U.rte("Login error!", e);
		}

		return null;
	}
 
Example 3
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 4
Source File: TCPClientDemo.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
private void client(Channel ch) {
	for (int i = 0; i < PIPELINE; i++) {
		Serializer.serialize(ch.output(), msg("abc", i));
		ch.send();
	}

	for (int i = 0; i < PIPELINE; i++) {
		Object s = Serializer.deserialize(ch.input());
		U.must(U.eq(msg("abc", i), s));
		resp.tick();
	}
}
 
Example 5
Source File: JPAUtil.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static <T> List<T> getPage(Query q, long skip, long limit) {

		U.must(skip < Integer.MAX_VALUE && skip >= 0);
		U.must(limit >= -1); // -1 means no limit
		limit = Math.min(limit, Integer.MAX_VALUE);

		q.setFirstResult((int) skip);
		q.setMaxResults(limit >= 0 ? (int) limit : Integer.MAX_VALUE);

		return q.getResultList();
	}
 
Example 6
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 7
Source File: Str.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static String replace(String s, String[][] repls) {
	for (String[] repl : repls) {
		U.must(repl.length == 2, "Expected pairs of [search, replacement] strings!");
		s = s.replaceAll(Pattern.quote(repl[0]), repl[1]);
	}

	return s;
}
 
Example 8
Source File: SetupImpl.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Override
public int port() {
	if (port == null) {
		port = serverConfig.entry("port").or(DEFAULT_PORT);
	}

	U.must(port >= 0, "The port of server setup '%s' is negative!", name());

	return port;
}
 
Example 9
Source File: Customization.java    From rapidoid with 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 10
Source File: Serializer.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
static Object deserialize(Buf in) {
	int n = U.num(in.readLn());
	U.must(n > 0 && n < 200);

	byte[] bytes = in.readNbytes(n);
	return Serialize.deserialize(bytes);
}
 
Example 11
Source File: ReusableWritable.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
public ReusableWritable(int size) {
	U.must(size >= 0);
	bytes = new byte[size];
}
 
Example 12
Source File: ConfigImpl.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
private void mustBeRoot() {
	RapidoidEnv.touch();
	U.must(isRoot, "Must be Config's root!");
}
 
Example 13
Source File: App.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
/**
 * Completes the initialization and starts the application.
 */
public static synchronized void ready() {
	U.must(status == AppStatus.INITIALIZING, "App.init() must be called before App.ready()!");

	onAppReady();
}
 
Example 14
Source File: Msc.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
public static void benchmarkMT(int threadsN, final String name, final int count, final CountDownLatch outsideLatch,
                               final BenchmarkOperation operation) {

	U.must(count % threadsN == 0, "The number of thread must be a factor of the total count!");
	final int countPerThread = count / threadsN;

	final CountDownLatch latch = outsideLatch != null ? outsideLatch : new CountDownLatch(threadsN);

	long time = U.time();

	final Ctx ctx = Ctxs.get();

	for (int i = 1; i <= threadsN; i++) {
		new RapidoidThread() {

			@Override
			public void run() {
				Ctxs.attach(ctx != null ? ctx.span() : null);

				try {
					doBenchmark(name, countPerThread, operation, true);
					if (outsideLatch == null) {
						latch.countDown();
					}

				} finally {
					if (ctx != null) {
						Ctxs.close();
					}
				}
			}

		}.start();
	}

	try {
		latch.await();
	} catch (InterruptedException e) {
		throw U.rte(e);
	}

	benchmarkComplete("avg(" + name + ")", threadsN * countPerThread, time);
}
 
Example 15
Source File: Err.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
public static void bounds(int value, int min, int max) {
	U.must(value >= min && value <= max, "%s is not in the range [%s, %s]!", value, min, max);
}
 
Example 16
Source File: Cls.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> Class<T> getWrapperClass(Class<T> c) {
	U.must(c.isPrimitive());
	return c.isPrimitive() ? (Class<T>) PRIMITIVE_WRAPPERS.get(c) : c;
}
 
Example 17
Source File: BeanProp.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
public void init() {
	U.must(field != null || getter != null, "Invalid property: %s", name);

	if (getter != null) getter.setAccessible(true);
	if (setter != null) setter.setAccessible(true);
	if (field != null) field.setAccessible(true);

	// TODO: improve inference from getter and setter
	if (getter != null) {
		rawType = getter.getReturnType();
	} else if (setter != null) {
		rawType = setter.getParameterTypes()[0];
	} else {
		rawType = field.getType();
	}
	type = rawType;

	Type gType = field != null ? field.getGenericType() : getter.getGenericReturnType();
	genericType = rawGenericType = Cls.generic(gType);

	if (Collection.class.isAssignableFrom(type)) {
		readOnly = false;
		propKind = PropKind.COLLECTION;

	} else if (Map.class.isAssignableFrom(type)) {
		readOnly = false;
		propKind = PropKind.MAP;

	} else if (Var.class.isAssignableFrom(type)) {
		U.notNull(genericType, "generic type");

		gType = genericType.getActualTypeArguments()[0];
		genericType = Cls.generic(gType);
		type = Cls.clazz(gType);

		readOnly = false;
		propKind = PropKind.VAR;
	}

	typeKind = Cls.kindOf(type);
	rawTypeKind = Cls.kindOf(rawType);
	declaringType = field != null ? field.getDeclaringClass() : getter.getDeclaringClass();
}
 
Example 18
Source File: FileSearch.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
public List<File> get() {
	List<File> found = U.list();

	boolean filesAndFolders = files == folders;

	U.must(U.notEmpty(location), "Location must be specified!");

	U.must(U.isEmpty(name) || U.isEmpty(regex), "You can specify either 'name' or 'regex', not both of them!");
	U.must(U.isEmpty(ignore) || U.isEmpty(ignoreRegex), "You can specify either 'ignore' or 'ignoreRegex', not both of them!");

	String matching = U.notEmpty(name) ? Str.wildcardsToRegex(name) : regex;
	String ignoring = U.notEmpty(ignore) ? Str.wildcardsToRegex(ignore) : ignoreRegex;

	Pattern mtch = U.notEmpty(matching) ? Pattern.compile(matching) : null;
	Pattern ignr = U.notEmpty(ignoring) ? Pattern.compile(ignoring) : null;

	search(new File(location), found, mtch, ignr, files || filesAndFolders, folders || filesAndFolders, recursive);

	return found;
}
 
Example 19
Source File: Msc.java    From rapidoid with Apache License 2.0 3 votes vote down vote up
public static boolean bootService(Config config, String service) {

		List<String> services = config.entry("services").list();

		for (String srvc : services) {
			U.must(ConfigOptions.SERVICE_NAMES.contains(srvc), "Unknown service: '%s'!", srvc);
		}

		return services.contains(service);
	}
 
Example 20
Source File: TLSUtil.java    From rapidoid with Apache License 2.0 3 votes vote down vote up
public static SSLContext createContext(String keystore, char[] keystorePassword, char[] keyManagerPassword,
                                       String truststore, char[] truststorePassword, boolean selfSignedTLS) {

	U.must(U.notEmpty(keystore), "The TLS keystore filename isn't configured!");

	boolean keystoreExists = new File(keystore).exists();

	U.must(keystoreExists || selfSignedTLS,
		"The keystore '%s' doesn't exist and self-signed certificate generation is disabled!", keystore);

	try {
		if (!keystoreExists && selfSignedTLS) {
			SelfSignedCertInfo info = new SelfSignedCertInfo();

			info.alias("rapidoid");
			info.password(keystorePassword);

			Log.warn("Keystore doesn't exist, creating a keystore with self-signed certificate",
				"keystore", keystore, "alias", info.alias());

			SelfSignedCertGen.generate(info, keystore, keystorePassword);
		}

		Log.info("Initializing TLS context", "keystore", keystore, "truststore", truststore);

		KeyManager[] keyManagers = initKeyManagers(keystore, keystorePassword, keyManagerPassword);
		TrustManager[] trustManagers = initTrustManagers(truststore, truststorePassword);

		SSLContext context = SSLContext.getInstance("TLS");
		context.init(keyManagers, trustManagers, null);

		return context;

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