cz.jalasoft.util.configuration.ConfigutrationInterfaceValidator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of JalasoftUtils Show documentation
Show all versions of JalasoftUtils Show documentation
A collection of utility classes that might be useful.
The newest version!
package cz.jalasoft.util.configuration;
import cz.jalasoft.util.configuration.annotation.Key;
import cz.jalasoft.util.configuration.annotation.KeyPrefix;
import cz.jalasoft.util.configuration.exception.InvalidPretenderTypeException;
import cz.jalasoft.util.configuration.exception.InvalidPropertyMethod;
import java.lang.reflect.Method;
import static java.util.Arrays.*;
/**
* @author Honza Lastovicka ([email protected])
* @since 2016-07-26.
*/
final class ConfigutrationInterfaceValidator {
private final ConverterRegistry converterRegistry;
ConfigutrationInterfaceValidator(ConverterRegistry converterRegistry) {
this.converterRegistry = converterRegistry;
}
void validate(Class> type) {
assertInterface(type);
assertKeyPrefixAnnotationIfPresent(type);
assertDeclaredMethods(type);
}
private void assertInterface(Class> type) {
if (!type.isInterface()) {
throw new InvalidPretenderTypeException(type, "Type is not an interface.");
}
}
private void assertKeyPrefixAnnotationIfPresent(Class> type) {
if (!type.isAnnotationPresent(KeyPrefix.class)) {
return;
}
KeyPrefix prefixAnnotation = type.getAnnotation(KeyPrefix.class);
String prefix = prefixAnnotation.value();
if (prefix.isEmpty()) {
throw new InvalidPretenderTypeException(type, "Key prefix must not be empty.");
}
}
private void assertDeclaredMethods(Class> type) {
Method[] declaredMethods = type.getDeclaredMethods();
stream(declaredMethods)
.forEach(this::assertDeclaredMethod);
}
private void assertDeclaredMethod(Method method) {
assertZeroArguments(method);
assertReturnValue(method);
assertKeyAnnotationIfPresent(method);
}
private void assertZeroArguments(Method method) {
int paramsCount = method.getParameterCount();
if (paramsCount == 0) {
return;
}
if (paramsCount > 0) {
throw new InvalidPropertyMethod(method, "Number of arguments is " + paramsCount + ". Must be zero.");
}
}
private void assertReturnValue(Method method) {
Class> returnType = method.getReturnType();
if (returnType.equals(Void.class)) {
throw new InvalidPropertyMethod(method, "Return type must not br Void.");
}
}
private void assertKeyAnnotationIfPresent(Method method) {
if (!method.isAnnotationPresent(Key.class)) {
return;
}
Key annotation = method.getAnnotation(Key.class);
String key = annotation.value();
if (key.isEmpty()) {
throw new InvalidPropertyMethod(method, "Method has annotation @Key whose value is an empty string. Provide non empty key.");
}
}
}