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

The following examples show how to use org.rapidoid.u.U#safe() . 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: ClasspathScanner.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
private static boolean isAnnotated(ClassFile cfile, Class<? extends Annotation>[] annotated) {
	List attributes = U.safe(cfile.getAttributes());

	for (Object attribute : attributes) {
		if (attribute instanceof AnnotationsAttribute) {
			AnnotationsAttribute annotations = (AnnotationsAttribute) attribute;

			for (Class<? extends Annotation> ann : annotated) {
				if (annotations.getAnnotation(ann.getName()) != null) {
					return true;
				}
			}
		}
	}

	return false;
}
 
Example 2
Source File: Msc.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
public static Map<String, String> parseArgs(List<String> args) {
	Map<String, String> arguments = U.map();

	for (String arg : U.safe(args)) {
		if (!isSpecialArg(arg)) {

			String[] parts = arg.split("=", 2);
			U.must(parts.length == 2, "The argument '%s' doesn't have a key=value format!", arg);

			arguments.put(parts[0], parts[1]);

		} else {
			throw U.rte("Special arguments are not supported since v6.0. Found: " + arg);
		}
	}

	return arguments;
}
 
Example 3
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 4
Source File: JdbcClient.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
private DataSource createPool() {
	String provider = U.safe(poolProvider);

	switch (provider) {
		case "hikari":
			U.must(MscOpts.hasHikari(), "Couldn't find Hikari!");
			Log.info("Initializing JDBC connection pool with Hikari", "!url", url, "!driver", driver, "!username", username, "!password", maskedPassword());
			return HikariFactory.createDataSourceFor(this);

		case "c3p0":
			U.must(MscOpts.hasC3P0(), "Couldn't find C3P0!");
			Log.info("Initializing JDBC connection pool with C3P0", "!url", url, "!driver", driver, "!username", username, "!password", maskedPassword());
			return C3P0Factory.createDataSourceFor(this);

		default:
			throw U.rte("Unknown pool provider: '%s'!", provider);
	}
}
 
Example 5
Source File: ConfigUtil.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
static synchronized void load(String filename, Config config, List<String> loaded) {
	Res res = findConfigResource(filename);

	byte[] bytes = null;
	String realFilename = filename;

	if (res.exists()) {
		realFilename = res.getCachedFileName();
		bytes = res.getBytes();
		loaded.add(realFilename);
	}

	if (bytes != null) {
		if (bytes.length > 0) {
			Map<String, Object> configData;

			try {
				Log.debug("Loading configuration file", "filename", filename);
				configData = U.safe(YAML_OR_JSON_PARSER.parse(bytes));

			} catch (Exception e) {
				configData = U.map();
				Log.error("Couldn't parse configuration file!", "filename", realFilename);
			}

			config.update(configData);
		}

	} else {
		Log.trace("Couldn't find configuration file", "filename", filename);
	}

}
 
Example 6
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 7
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 8
Source File: JdbcClient.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
private Connection getConnectionFromDriver() throws SQLException {
	if (username != null) {
		String pass = U.safe(password);
		return DriverManager.getConnection(url, username, pass);

	} else {
		return DriverManager.getConnection(url);
	}
}
 
Example 9
Source File: Beany.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
public static String beanToStr(Object bean, boolean allowCustom) {

		Class<?> clazz = Cls.unproxy(bean.getClass());

		if (allowCustom) {
			Method m = Cls.getMethod(clazz, "toString");
			if (!m.getDeclaringClass().equals(Object.class)) {
				return bean.toString();
			}
		}

		BeanProperties props = propertiesOf(bean).annotated(ToString.class);

		if (props.isEmpty()) {

			Prop nameProp = property(bean, "name", false);
			if (nameProp != null && nameProp.getType() == String.class) {
				return U.safe((String) nameProp.get(bean));
			}

			props = propertiesOf(bean);
		}

		StringBuilder sb = new StringBuilder();

		for (Prop prop : props) {
			String name = prop.getName();
			Object value = prop.get(bean);

			if (sb.length() > 0) {
				sb.append(", ");
			}

			if (prop.getTypeKind() == TypeKind.UNKNOWN) {
				value = value == bean ? "[this]" : "[obj]";
			}

			if (value instanceof Date) {
				Date date = (Date) value;
				value = Dates.str(date);
			}

			sb.append(name);
			sb.append(": ");
			sb.append(value);
		}

		return sb.toString();
	}
 
Example 10
Source File: Beany.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
public static String beanToNiceText(Object bean, boolean allowCustom) {

		Class<?> clazz = Cls.unproxy(bean.getClass());

		if (allowCustom) {
			Method m = Cls.getMethod(clazz, "toString");
			if (!m.getDeclaringClass().equals(Object.class)) {
				return bean.toString();
			}
		}

		BeanProperties props = propertiesOf(bean).annotated(ToString.class);

		if (props.isEmpty()) {

			Prop nameProp = property(bean, "name", false);
			if (nameProp != null && nameProp.getType() == String.class) {
				return U.safe((String) nameProp.get(bean));
			}

			props = propertiesOf(bean);
		}

		StringBuilder sb = new StringBuilder();

		for (Prop prop : props) {
			String name = prop.getName();
			Object value = prop.get(bean);

			if (value != null && prop.getTypeKind() != TypeKind.UNKNOWN && prop.getTypeKind() != TypeKind.DATE) {

				if (sb.length() > 0) {
					sb.append(", ");
				}

				if (!(value instanceof String)) {
					sb.append(name);
					sb.append(": ");
				}

				sb.append(value);
			}
		}

		return sb.toString();
	}
 
Example 11
Source File: ClasspathScanner.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
private static List<String> retrieveClasses(Set<String> classpath, String packageName,
                                            Class<? extends Annotation>[] annotated, Predicate<InputStream> bytecodeFilter,
                                            Pattern regex, ClassLoader classLoader, AtomicInteger searched) {

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

	String pkgName = U.safe(packageName);
	String pkgPath = pkgName.replace('.', File.separatorChar);

	Log.trace("Starting classpath scan", "package", packageName, "annotated", annotated, "regex", regex, "loader", classLoader);

	Log.trace("Classpath details", "classpath", classpath);

	Set<String> jars = U.set();

	for (String cpe : classpath) {
		File cpEntry = new File(cpe);

		if (cpEntry.exists()) {
			if (cpEntry.isDirectory()) {
				if (shouldScanDir(cpEntry.getAbsolutePath())) {
					Log.trace("Scanning directory", "root", cpEntry.getAbsolutePath());

					File startingDir;
					if (pkgPath.isEmpty()) {
						startingDir = cpEntry;
					} else {
						startingDir = new File(cpEntry.getAbsolutePath(), pkgPath);
					}

					if (startingDir.exists()) {
						getClassesFromDir(classes, cpEntry, startingDir, pkgName, regex, annotated, bytecodeFilter, searched);
					}
				} else {
					Log.trace("Skipping directory", "root", cpEntry.getAbsolutePath());
				}
			} else if (cpEntry.isFile() && cpEntry.getAbsolutePath().toLowerCase().endsWith(".jar")) {
				jars.add(cpEntry.getAbsolutePath());
			} else {
				Log.warn("Invalid classpath entry: " + cpe);
			}
		} else {
			if (!cpe.contains("*") && !cpe.contains("?") && U.neq(cpe, ClasspathUtil.appJar())) {
				Log.warn("Classpath entry doesn't exist: " + cpe);
			}
		}
	}

	for (String jarName : jars) {
		if (shouldScanJAR(jarName)) {
			Log.trace("Scanning JAR", "name", jarName);
			getClassesFromJAR(jarName, classes, packageName, regex, annotated, bytecodeFilter, classLoader, searched);
		} else {
			Log.trace("Skipping JAR", "name", jarName);
		}
	}

	return classes;
}