Skip to content

Tidy map.computeIfAbsent(), whitespace, format, javadoc #53

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,9 @@ void setFullName(String fullName) {
String fullName() {
if (fullName == null) {
final List<String> types = new ArrayList<>(allTypes);

for (final var adapter : annotationAdapters)
for (final var adapter : annotationAdapters) {
adapter.getQualifiedName().toString().transform(types::add);

}
String topPackage = TopPackage.of(types);
if (!topPackage.endsWith(".valid")) {
topPackage += ".valid";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,21 +42,17 @@ void read() {
/** Read the existing JsonAdapters from the MetaData annotation of the generated component. */
private void readMetaData(TypeElement moduleType) {
for (final AnnotationMirror annotationMirror : moduleType.getAnnotationMirrors()) {

final MetaDataPrism metaData = MetaDataPrism.getInstance(annotationMirror);
final FactoryPrism metaDataFactory = FactoryPrism.getInstance(annotationMirror);
final AnnotationFactoryPrism metaDataAnnotationFactory =
AnnotationFactoryPrism.getInstance(annotationMirror);
final AnnotationFactoryPrism metaDataAnnotationFactory = AnnotationFactoryPrism.getInstance(annotationMirror);

if (metaData != null) {

metaData.value().stream().map(TypeMirror::toString).forEach(componentMetaData::add);

} else if (metaDataFactory != null) {

metaDataFactory.value().stream().map(TypeMirror::toString).forEach(componentMetaData::add);
} else if (metaDataAnnotationFactory != null) {

} else if (metaDataAnnotationFactory != null) {
metaDataAnnotationFactory.value().stream()
.map(ProcessingContext::asElement)
.forEach(componentMetaData::addAnnotationAdapter);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@

final class Constants {

static final String META_INF_COMPONENT =
"META-INF/services/io.avaje.validation.Validator$GeneratedComponent";
static final String META_INF_COMPONENT = "META-INF/services/io.avaje.validation.Validator$GeneratedComponent";
public static final String VALID_SPI = "io.avaje.validation.spi.*";
public static final String VALIDATOR = "io.avaje.validation.Validator";
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ final class FieldReader {
this.element = element;
if (element instanceof final ExecutableElement executableElement) {
this.rawType = Util.trimAnnotations(executableElement.getReturnType().toString());

} else {
this.rawType = Util.trimAnnotations(element.asType().toString());
}
Expand Down Expand Up @@ -152,17 +151,14 @@ private void writeGetValue(Append writer, String suffix) {
}

void writeValidate(Append writer) {

writer.append(" var _$%s = ", fieldName);
writeGetValue(writer, ";");
writer.eol();
if (optionalValidation) {

writer.append(" if(_$%s != null) {", fieldName);
}
writer.append(" %s.validate(_$%s", adapterFieldName, fieldName);
writer.append(", request, \"%s\");", fieldName);

if (optionalValidation) {
writer.append(" }");
}
Expand All @@ -179,70 +175,46 @@ public GenericType type() {
}

public void writeConstructor(Append writer) {

writer.append(" this.%s = ", adapterFieldName).eol();

boolean first = true;
for (final var a : annotations.entrySet()) {

if (first) {
writer.append(
" ctx.<%s>adapter(%s.class, %s)",
PrimitiveUtil.wrap(genericType.shortType()), a.getKey().shortName(), a.getValue());
writer.append(" ctx.<%s>adapter(%s.class, %s)", PrimitiveUtil.wrap(genericType.shortType()), a.getKey().shortName(), a.getValue());
first = false;
continue;
}
writer
.eol()
.append(
" .andThen(ctx.adapter(%s.class,%s))",
a.getKey().shortName(), a.getValue());
writer.eol().append(" .andThen(ctx.adapter(%s.class,%s))", a.getKey().shortName(), a.getValue());
}
final var topType = genericType.topType();
if (isBasicType(topType)) {

writer.append(";").eol();
return;
}

if ("java.util.List".equals(genericType.topType())
|| "java.util.Set".equals(genericType.topType())) {
if ("java.util.List".equals(genericType.topType()) || "java.util.Set".equals(genericType.topType())) {
if (isBasicType(genericType.firstParamType())) {

writer.append(";").eol();
return;
}
writer.eol().append(" .list(ctx, %s.class)", Util.shortName(genericType.firstParamType()));

writer
.eol()
.append(" .list(ctx, %s.class)", Util.shortName(genericType.firstParamType()));
} else if ("java.util.Map".equals(genericType.topType())) {
if (isBasicType(genericType.secondParamType())) {

writer.append(";").eol();
return;
}
writer.eol().append(" .map(ctx, %s.class)", Util.shortName(genericType.secondParamType()));

writer
.eol()
.append(" .map(ctx, %s.class)", Util.shortName(genericType.secondParamType()));
} else if (genericType.topType().contains("[]")) {
if (isBasicType(topType)) {

writer.append(";").eol();
return;
}
writer.eol().append(" .array(ctx, %s.class)", Util.shortName(genericType.topType().replace("[]", "")));

writer
.eol()
.append(
" .array(ctx, %s.class)",
Util.shortName(genericType.topType().replace("[]", "")));
} else {
writer
.eol()
.append(
" .andThen(ctx.adapter(%s.class))", Util.shortName(genericType.topType()));
writer.eol().append(" .andThen(ctx.adapter(%s.class))", Util.shortName(genericType.topType()));
}
writer.append(";").eol();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ GenericType parse() {
final char ch = raw.charAt(i);
processChar(ch);
}

return stack.peek();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,7 @@ private void readModule() {
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment round) {
readModule();

registerCustomAdapters(
round.getElementsAnnotatedWith(element(AnnotationValidatorPrism.PRISM_TYPE)));

registerCustomAdapters(round.getElementsAnnotatedWith(element(AnnotationValidatorPrism.PRISM_TYPE)));
writeAdapters(round.getElementsAnnotatedWith(element(ValidPojoPrism.PRISM_TYPE)));

Optional.ofNullable(element(ValidPrism.PRISM_TYPE))
Expand All @@ -87,11 +85,8 @@ public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment
}

private void registerCustomAdapters(Set<? extends Element> elements) {

for (final var typeElement : ElementFilter.typesIn(elements)) {

AnnotationValidatorPrism.getInstanceOn(typeElement).value();

metaData.addAnnotationAdapter(typeElement);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,7 @@ private void writeConstructor() {
writer.append(" /**").eol();
writer.append(" * Construct using Object for generic type parameters.").eol();
writer.append(" */").eol();
writer
.append(" public %sValidationAdapter(ValidationContext ctx) {", adapterShortName)
.eol();
writer.append(" public %sValidationAdapter(ValidationContext ctx) {", adapterShortName).eol();
writer.append(" this(ctx");
for (int i = 0; i < genericParamsCount; i++) {
writer.append(", Object.class");
Expand All @@ -83,9 +81,7 @@ private void writeClassEnd() {

private void writeClassStart() {
writer.append("@Generated").eol();
writer.append(
"public final class %sValidationAdapter implements ValidationAdapter<%s> ",
adapterShortName, beanReader.shortName());
writer.append("public final class %sValidationAdapter implements ValidationAdapter<%s> ", adapterShortName, beanReader.shortName());
writer.append("{").eol().eol();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,12 @@ void read(TypeElement type) {
}

for (final FieldReader localField : localFields) {

allFields.add(localField);
allFieldMap.put(localField.fieldName(), localField);
}
}

private void readField(Element element, List<FieldReader> localFields) {

if (includeField(element)) {
localFields.add(new FieldReader(element, genericTypeParams));
}
Expand All @@ -86,7 +84,6 @@ private boolean includeField(Element element) {
}

private void readMethod(Element element, TypeElement type, List<FieldReader> localFields) {

final ExecutableElement methodElement = (ExecutableElement) element;
if (methodElement.getModifiers().contains(Modifier.PUBLIC)) {
final List<? extends VariableElement> parameters = methodElement.getParameters();
Expand Down Expand Up @@ -119,12 +116,7 @@ private void matchFieldToGetter(FieldReader field) {
&& !field.isPublicField()) {
nonAccessibleField = true;
if (hasJsonAnnotation) {
logError(
"Non accessible field "
+ baseType
+ " "
+ field.fieldName()
+ " with no matching getter?");
logError("Non accessible field " + baseType + " " + field.fieldName() + " with no matching getter?");
} else {
logDebug("Non accessible field " + baseType + " " + field.fieldName());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,21 @@ public class ConstraintViolation {
private final String propertyName;
private final String message;

/**
* Create the ConstraintViolation with the given path, property and message.
*/
public ConstraintViolation(String path, String propertyName, String message) {
this.path = path;
this.propertyName = propertyName;
this.message = message;
}

/** Return the path that this violation occurred for */
/** Return the path for this constraint violation */
public String path() {
return path;
}

/** Return the property name for this constraint violation */
public String propertyName() {
return propertyName;
}
Expand All @@ -32,7 +36,6 @@ public String message() {

@Override
public String toString() {

return message;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,19 @@

import java.util.Set;

/**
* Exception holding a set of constraint violations.
*/
public final class ConstraintViolationException extends RuntimeException {

private final Set<ConstraintViolation> violations;

/** Create with the given constraint violations */
public ConstraintViolationException(Set<ConstraintViolation> violations) {
this.violations = violations;
}

/** Return the constraint violations. */
public Set<ConstraintViolation> violations() {
return violations;
}
Expand Down
4 changes: 1 addition & 3 deletions validator/src/main/java/io/avaje/validation/Validator.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,13 @@ interface Builder {

/**
* Add ResourceBundle for error message interpolation
*
* @param bundleName the name of the bundleFiles
*/
Builder addResourceBundles(ResourceBundle... bundle);

/** Set Default Locale for this validator, if not set, will use Locale.getDefault() */
Builder setDefaultLocale(Locale defaultLocale);

/** Adds an additional Locales for this validator */
/** Adds additional Locales for this validator */
Builder addLocales(Locale... locales);

/** Add a AdapterBuilder which provides a ValidationAdapter to use for the given type. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ default boolean validate(T value, ValidationRequest req) {
return validate(value, req, null);
}

@SuppressWarnings("unchecked")
default ValidationAdapter<T> list(ValidationContext ctx, Class<?> clazz) {
final var after = ctx.<Object>adapter(clazz);
return (value, req, propertyName) -> {
Expand All @@ -24,6 +25,7 @@ default ValidationAdapter<T> list(ValidationContext ctx, Class<?> clazz) {
};
}

@SuppressWarnings("unchecked")
default ValidationAdapter<T> map(ValidationContext ctx, Class<?> clazz) {
final var after = ctx.<Object>adapter(clazz);
return (value, req, propertyName) -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
import java.lang.reflect.Type;
import java.util.Map;

import io.avaje.validation.adapter.ValidationContext.Message;

/**
* Context available when validation adapters are being created.
*/
public interface ValidationContext {

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,31 @@
package io.avaje.validation.adapter;

/**
* A validation request.
*/
public interface ValidationRequest {

void addViolation(ValidationContext.Message msg, String propertyName);
/**
* Add a constraint violation for the given property.
*
* @param message The message
* @param propertyName The property that failed the constraint
*/
void addViolation(ValidationContext.Message message, String propertyName);

/**
* Push the nested path.
*/
void pushPath(String path);

/**
* Pop the nested path.
*/
void popPath();

/**
* Throw ConstraintViolationException if there are violations for this request.
*/
void throwWithViolations();

}
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ final class BasicMessageInterpolator implements MessageInterpolator {

@Override
public String interpolate(String template, Map<String, Object> attributes) {

String result = template;

for (final Map.Entry<String, Object> entry : attributes.entrySet()) {
// needs work here to improve functionality, support local specific value formatting eg
// Duration Max
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,13 @@ <T> ValidationAdapter<T> build(Type type, Object cacheKey) {
return result;
}
}
throw new IllegalArgumentException(
"No ValidationAdapter for " + type + ". Perhaps needs @ValidPojo or @ValidPojo.Import?");
throw new IllegalArgumentException("No ValidationAdapter for " + type + ". Perhaps needs @ValidPojo or @ValidPojo.Import?");
}

/** Build given type and annotations. */
// TODO understand that lookup chain stuff
@SuppressWarnings("unchecked")
<T> ValidationAdapter<T> buildAnnotation(Class<? extends Annotation> cls, Map<String, Object> attributes) {

// Ask each factory to create the validation adapter.
for (final ValidationContext.AnnotationFactory factory : annotationFactories) {
final var result = (ValidationAdapter<T>) factory.create(cls, context, attributes);
Expand Down
Loading