diff --git a/README.md b/README.md index 0f2abf3..63df5ff 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,8 @@ ```java public class User { - @ConcurrentSpace - private String name; + @ConcurrentSpace + private String name; } ``` @@ -21,6 +21,30 @@ sanitizer.sanitize(); ``` +### Recursive sanitation ### + +To traverse into embedded objects, collections, and arrays of non-primitive +types, enable recursion before calling `sanitize()`: + +```java +new Sanitizer(object).recursive().sanitize(); +``` + +Recursion follows non-`java.*` package types and `Collection` elements, +skipping primitives, enums, and `null` entries. + +### Supported value types ### + +Every annotation below is applied to `String` values directly. When the +annotated field is one of the following, every element is cleansed in place: + +- `String` +- `Collection` (e.g. `List`, `Set`) +- `String[]` + +If the annotated `Collection` is unmodifiable, the cleansed values cannot be +written back and the field is left untouched. + ## Accent ## Strip accents from characters @@ -29,9 +53,6 @@ @Accent ``` -Data types supported -- String - ## Concurrent Space ## Replaces all concurrent spaces with single space @@ -54,9 +75,6 @@ John Doe ``` -Data types supported -- String - ## Lowercase ## Lowercase all characters @@ -65,22 +83,18 @@ @Lowercase ``` -Data types supported -- String - ## Remove ## -Removes all instances of given string +Removes all literal occurrences of the given string. The argument is **not** +treated as a regular expression, so characters such as `.`, `*`, and `(` are +matched literally. ```java @Remove("-") ``` Required -- toRemove - [String] - -Data types supported -- String +- value - [String] ## Trim ## @@ -90,9 +104,6 @@ @Trim ``` -Data types supported -- String - ## Trim to Null ## Remove leading and trailing spaces and return null if empty @@ -101,9 +112,6 @@ @TrimToNull ``` -Data types supported -- String - ## Uppercase ## Uppercase all characters @@ -112,9 +120,6 @@ @Uppercase ``` -Data types supported -- String - ## Custom ## Sanitizes against a custom class @@ -124,10 +129,24 @@ ``` Required -- value - Class that implements Cleanser +- value - Class that implements `Cleanser` -**Note:** Custom validation class must implement the Cleanser interface +**Note:** The class supplied to `@CustomSanitizer` must implement the +`Cleanser` interface and expose a public no-argument constructor. If the +class does not implement `Cleanser`, the field is silently skipped. If the +class cannot be instantiated reflectively, an `IllegalStateException` is +thrown. -## TODO ## +## Error handling ## -Handle exception from CustomSanitizer \ No newline at end of file +Reflective failures while reading or writing fields are surfaced as +`IllegalStateException` with the originating exception attached as the cause. +This replaces the previous behavior of writing stack traces to standard error. + +## Building ## + +```bash +mvn clean test +``` + +The project targets Java 8 and uses JUnit 4 for tests. diff --git a/src/main/java/io/ljunggren/sanitizer/Item.java b/src/main/java/io/ljunggren/sanitizer/Item.java index 822dd5e..45fb0c1 100644 --- a/src/main/java/io/ljunggren/sanitizer/Item.java +++ b/src/main/java/io/ljunggren/sanitizer/Item.java @@ -7,8 +7,8 @@ @Getter public class Item { - private Object object; - private Field field; + private final Object object; + private final Field field; private Object value; public Item(Object object, Field field, Object value) { @@ -16,14 +16,16 @@ this.field = field; this.value = value; } - + public void setValue(Object value) { try { this.value = value; + field.setAccessible(true); field.set(object, value); } catch (IllegalArgumentException | IllegalAccessException e) { - e.printStackTrace(); + throw new IllegalStateException( + "Failed to set value on field " + field.getName(), e); } } - + } diff --git a/src/main/java/io/ljunggren/sanitizer/Sanitizer.java b/src/main/java/io/ljunggren/sanitizer/Sanitizer.java index f5b3132..d942774 100644 --- a/src/main/java/io/ljunggren/sanitizer/Sanitizer.java +++ b/src/main/java/io/ljunggren/sanitizer/Sanitizer.java @@ -3,7 +3,6 @@ import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.List; @@ -16,34 +15,54 @@ import io.ljunggren.sanitizer.sanitation.CustomSanitation; import io.ljunggren.sanitizer.sanitation.LowercaseSanitation; import io.ljunggren.sanitizer.sanitation.RemoveSanitation; +import io.ljunggren.sanitizer.sanitation.SanitationChain; import io.ljunggren.sanitizer.sanitation.TrimSanitation; import io.ljunggren.sanitizer.sanitation.TrimToNullSanitation; import io.ljunggren.sanitizer.sanitation.UppercaseSanitation; import lombok.Getter; +/** + * Entry point for sanitizing the annotated fields of an object. + * + *

Construct with the target object, optionally enable {@link #recursive()} + * traversal, then call {@link #sanitize()} to apply all annotation-driven + * cleansing in place.

+ */ @Getter public class Sanitizer { - private Object object; + private final Object object; private boolean recursive; public Sanitizer(Object object) { this.object = object; } - + + /** + * Enables recursive descent into embedded objects, collections, and arrays + * of non-primitive types. + * + * @return this {@code Sanitizer} for chaining + */ public Sanitizer recursive() { this.recursive = true; return this; } - + + /** + * Walks the configured object and applies sanitation to every annotated + * field. + * + * @return this {@code Sanitizer} for chaining + */ public Sanitizer sanitize() { List items = findItems(object); sanitizeItems(items); return this; } - + private List findItems(Object object) { - List items = new ArrayList(); + List items = new ArrayList<>(); findItems(object, items); return items; } @@ -57,31 +76,31 @@ items.add(new Item(object, field, value)); } if (checkEmbedded(field.getType())) { - if (ReflectionUtils.isCollection(field.getType())) { - @SuppressWarnings("unchecked") - Collection embeddeds = (Collection) field.get(object); - if (embeddeds == null) { - continue; - } - for (Object embedded: embeddeds) { - if (checkEmbedded(object.getClass())) { - findItems(embedded, items); - } + if (ReflectionUtils.isCollection(field.getType())) { + @SuppressWarnings("unchecked") + Collection embeddeds = (Collection) value; + if (embeddeds == null) { + continue; } - continue; - } - Object embedded = field.get(object); - if (embedded != null) { - findItems(embedded, items); + for (Object embedded : embeddeds) { + if (embedded != null && checkEmbedded(embedded.getClass())) { + findItems(embedded, items); + } + } + continue; + } + if (value != null) { + findItems(value, items); } } } catch (IllegalAccessException e) { - e.printStackTrace(); + throw new IllegalStateException( + "Failed to read field " + field.getName(), e); } } return items; } - + private boolean checkEmbedded(Class type) { if (!recursive) { return false; @@ -96,30 +115,33 @@ return false; } if (ReflectionUtils.isCollection(type)) { - return true; + return true; } return !type.getPackage().getName().startsWith("java"); } - + private List findObjectFields(Object object) { if (object != null) { Class clazz = object.getClass(); return FieldUtils.getAllFieldsList(clazz); } - return new ArrayList(); + return new ArrayList<>(); } - + private void sanitizeItems(List items) { - items.stream().forEach(item -> sanitizeItem(item)); + SanitationChain chain = buildChain(); + items.forEach(item -> sanitizeItem(item, chain)); } - - private void sanitizeItem(Item item) { + + private void sanitizeItem(Item item, SanitationChain chain) { Annotation[] annotations = item.getField().getAnnotations(); - Arrays.asList(annotations).forEach(annotation -> sanitationChain(annotation, item)); + for (Annotation annotation : annotations) { + chain.sanitize(annotation, item); + } } - - private void sanitationChain(Annotation annotation, Item item) { - new ConcurrentSpaceSanitation() + + private SanitationChain buildChain() { + return new ConcurrentSpaceSanitation() .nextChain(new LowercaseSanitation() .nextChain(new RemoveSanitation() .nextChain(new TrimSanitation() @@ -128,7 +150,7 @@ .nextChain(new CustomSanitation() .nextChain(new AccentSanitation() .nextChain(new CatchAllSanitation() - )))))))).sanitize(annotation, item); + )))))))); } } diff --git a/src/main/java/io/ljunggren/sanitizer/cleanser/AccentCleanser.java b/src/main/java/io/ljunggren/sanitizer/cleanser/AccentCleanser.java index 00c3f33..07a8e34 100644 --- a/src/main/java/io/ljunggren/sanitizer/cleanser/AccentCleanser.java +++ b/src/main/java/io/ljunggren/sanitizer/cleanser/AccentCleanser.java @@ -6,7 +6,7 @@ @Override public String cleanse(String value) { - return value == null ? value : StringUtils.stripAccents(value); + return value == null ? null : StringUtils.stripAccents(value); } @Override diff --git a/src/main/java/io/ljunggren/sanitizer/cleanser/Cleanser.java b/src/main/java/io/ljunggren/sanitizer/cleanser/Cleanser.java index c70fa43..3e7c555 100644 --- a/src/main/java/io/ljunggren/sanitizer/cleanser/Cleanser.java +++ b/src/main/java/io/ljunggren/sanitizer/cleanser/Cleanser.java @@ -1,8 +1,23 @@ package io.ljunggren.sanitizer.cleanser; +/** + * Strategy interface for cleansing a value of type {@code T}. + * + * @param the type of value the cleanser operates on + */ public interface Cleanser { + /** + * Apply the cleansing rule to the given value. + * + * @param value input value (implementations should accept {@code null}) + * @return the cleansed value + */ String cleanse(T value); + + /** + * @return human-readable description of what this cleanser does + */ String description(); - + } diff --git a/src/main/java/io/ljunggren/sanitizer/cleanser/LowercaseCleanser.java b/src/main/java/io/ljunggren/sanitizer/cleanser/LowercaseCleanser.java index 9753dea..c3bb1ba 100644 --- a/src/main/java/io/ljunggren/sanitizer/cleanser/LowercaseCleanser.java +++ b/src/main/java/io/ljunggren/sanitizer/cleanser/LowercaseCleanser.java @@ -2,10 +2,12 @@ public class LowercaseCleanser implements Cleanser { + @Override public String cleanse(String value) { - return value == null ? value : value.toLowerCase(); + return value == null ? null : value.toLowerCase(); } + @Override public String description() { return "Lowercase all characters"; } diff --git a/src/main/java/io/ljunggren/sanitizer/cleanser/RemoveCleanser.java b/src/main/java/io/ljunggren/sanitizer/cleanser/RemoveCleanser.java index 7997f45..57e9f63 100644 --- a/src/main/java/io/ljunggren/sanitizer/cleanser/RemoveCleanser.java +++ b/src/main/java/io/ljunggren/sanitizer/cleanser/RemoveCleanser.java @@ -2,19 +2,21 @@ public class RemoveCleanser implements Cleanser { - private String toRemove; - + private final String toRemove; + public RemoveCleanser(String toRemove) { this.toRemove = toRemove; } + @Override public String cleanse(String value) { - if (value == null || toRemove == null) { + if (value == null || toRemove == null || toRemove.isEmpty()) { return value; } - return value.replaceAll(toRemove, ""); + return value.replace(toRemove, ""); } + @Override public String description() { return String.format("Remove all %s", toRemove); } diff --git a/src/main/java/io/ljunggren/sanitizer/cleanser/ReplaceCleanser.java b/src/main/java/io/ljunggren/sanitizer/cleanser/ReplaceCleanser.java index 03b7bb2..252999f 100644 --- a/src/main/java/io/ljunggren/sanitizer/cleanser/ReplaceCleanser.java +++ b/src/main/java/io/ljunggren/sanitizer/cleanser/ReplaceCleanser.java @@ -2,8 +2,8 @@ public class ReplaceCleanser implements Cleanser { - private String replacer; - private String replacement; + private final String replacer; + private final String replacement; public ReplaceCleanser(String replacer, String replacement) { this.replacer = replacer; @@ -12,17 +12,21 @@ @Override public String cleanse(String value) { - if (value == null || replacer == null || replacement == null) { + if (value == null || replacer == null || replacement == null || replacer.isEmpty()) { return value; } - return replace(value); - } - - private String replace(String value) { - if (value.contains(replacer)) { - return replace(value.replace(replacer, replacement)); + String current = value; + // Keep replacing only while the result strictly shrinks. This preserves + // the "collapse repeated runs" behavior (e.g. "||||" -> "|") while + // preventing infinite expansion when the replacement contains the + // replacer (e.g. "a" -> "aa"). + while (true) { + String next = current.replace(replacer, replacement); + if (next.length() >= current.length()) { + return next; + } + current = next; } - return value; } @Override diff --git a/src/main/java/io/ljunggren/sanitizer/cleanser/TrimCleanser.java b/src/main/java/io/ljunggren/sanitizer/cleanser/TrimCleanser.java index 947278c..edf0bec 100644 --- a/src/main/java/io/ljunggren/sanitizer/cleanser/TrimCleanser.java +++ b/src/main/java/io/ljunggren/sanitizer/cleanser/TrimCleanser.java @@ -2,10 +2,12 @@ public class TrimCleanser implements Cleanser { + @Override public String cleanse(String value) { - return value == null ? value : value.trim(); + return value == null ? null : value.trim(); } + @Override public String description() { return "Remove leading and trailing spaces"; } diff --git a/src/main/java/io/ljunggren/sanitizer/cleanser/TrimToNullCleanser.java b/src/main/java/io/ljunggren/sanitizer/cleanser/TrimToNullCleanser.java index 7ad6863..faa0891 100644 --- a/src/main/java/io/ljunggren/sanitizer/cleanser/TrimToNullCleanser.java +++ b/src/main/java/io/ljunggren/sanitizer/cleanser/TrimToNullCleanser.java @@ -2,14 +2,16 @@ public class TrimToNullCleanser implements Cleanser { + @Override public String cleanse(String value) { - if (value == null) { - return null; - } - value = value.trim(); - return value.isEmpty() ? null : value; + if (value == null) { + return null; + } + String trimmed = value.trim(); + return trimmed.isEmpty() ? null : trimmed; } + @Override public String description() { return "Remove leading and trailing spaces and returns null if empty"; } diff --git a/src/main/java/io/ljunggren/sanitizer/cleanser/UppercaseCleanser.java b/src/main/java/io/ljunggren/sanitizer/cleanser/UppercaseCleanser.java index c391c66..b0ed60f 100644 --- a/src/main/java/io/ljunggren/sanitizer/cleanser/UppercaseCleanser.java +++ b/src/main/java/io/ljunggren/sanitizer/cleanser/UppercaseCleanser.java @@ -2,10 +2,12 @@ public class UppercaseCleanser implements Cleanser { + @Override public String cleanse(String value) { - return value == null? value : value.toUpperCase(); + return value == null ? null : value.toUpperCase(); } + @Override public String description() { return "Uppercase all characters"; } diff --git a/src/main/java/io/ljunggren/sanitizer/sanitation/AccentSanitation.java b/src/main/java/io/ljunggren/sanitizer/sanitation/AccentSanitation.java index fd1cbeb..6dfca00 100644 --- a/src/main/java/io/ljunggren/sanitizer/sanitation/AccentSanitation.java +++ b/src/main/java/io/ljunggren/sanitizer/sanitation/AccentSanitation.java @@ -9,13 +9,13 @@ public class AccentSanitation extends SanitationChain { - private Class annotationClass = Accent.class; - private Cleanser cleanser = new AccentCleanser(); + private static final Class ANNOTATION_CLASS = Accent.class; + private static final Cleanser CLEANSER = new AccentCleanser(); @Override public void sanitize(Annotation annotation, Item item) { - if (annotation.annotationType() == annotationClass) { - sanitizeStringType(item, cleanser); + if (annotation.annotationType() == ANNOTATION_CLASS) { + sanitizeStringType(item, CLEANSER); return; } nextChain.sanitize(annotation, item); diff --git a/src/main/java/io/ljunggren/sanitizer/sanitation/CatchAllSanitation.java b/src/main/java/io/ljunggren/sanitizer/sanitation/CatchAllSanitation.java index 11c5278..aec7d0a 100644 --- a/src/main/java/io/ljunggren/sanitizer/sanitation/CatchAllSanitation.java +++ b/src/main/java/io/ljunggren/sanitizer/sanitation/CatchAllSanitation.java @@ -1,14 +1,14 @@ -package io.ljunggren.sanitizer.sanitation; - -import java.lang.annotation.Annotation; - -import io.ljunggren.sanitizer.Item; - -public class CatchAllSanitation extends SanitationChain { - - @Override - public void sanitize(Annotation annotation, Item item) { - return; - } - -} +package io.ljunggren.sanitizer.sanitation; + +import java.lang.annotation.Annotation; + +import io.ljunggren.sanitizer.Item; + +public class CatchAllSanitation extends SanitationChain { + + @Override + public void sanitize(Annotation annotation, Item item) { + // Terminal handler: unrecognized annotations are silently ignored. + } + +} diff --git a/src/main/java/io/ljunggren/sanitizer/sanitation/ConcurrentSpaceSanitation.java b/src/main/java/io/ljunggren/sanitizer/sanitation/ConcurrentSpaceSanitation.java index 5d698df..569f1d4 100644 --- a/src/main/java/io/ljunggren/sanitizer/sanitation/ConcurrentSpaceSanitation.java +++ b/src/main/java/io/ljunggren/sanitizer/sanitation/ConcurrentSpaceSanitation.java @@ -1,24 +1,24 @@ -package io.ljunggren.sanitizer.sanitation; - -import java.lang.annotation.Annotation; - -import io.ljunggren.sanitizer.Item; -import io.ljunggren.sanitizer.annotation.ConcurrentSpace; -import io.ljunggren.sanitizer.cleanser.Cleanser; -import io.ljunggren.sanitizer.cleanser.ReplaceCleanser; - -public class ConcurrentSpaceSanitation extends SanitationChain { - - private final String SPACE = " "; - private Class annotationClass = ConcurrentSpace.class; - private Cleanser cleanser = new ReplaceCleanser(SPACE + SPACE, SPACE); - - @Override - public void sanitize(Annotation annotation, Item item) { - if (annotation.annotationType() == annotationClass) { - sanitizeStringType(item, cleanser); - return; - } - nextChain.sanitize(annotation, item); - } -} +package io.ljunggren.sanitizer.sanitation; + +import java.lang.annotation.Annotation; + +import io.ljunggren.sanitizer.Item; +import io.ljunggren.sanitizer.annotation.ConcurrentSpace; +import io.ljunggren.sanitizer.cleanser.Cleanser; +import io.ljunggren.sanitizer.cleanser.ReplaceCleanser; + +public class ConcurrentSpaceSanitation extends SanitationChain { + + private static final String SPACE = " "; + private static final Class ANNOTATION_CLASS = ConcurrentSpace.class; + private static final Cleanser CLEANSER = new ReplaceCleanser(SPACE + SPACE, SPACE); + + @Override + public void sanitize(Annotation annotation, Item item) { + if (annotation.annotationType() == ANNOTATION_CLASS) { + sanitizeStringType(item, CLEANSER); + return; + } + nextChain.sanitize(annotation, item); + } +} diff --git a/src/main/java/io/ljunggren/sanitizer/sanitation/CustomSanitation.java b/src/main/java/io/ljunggren/sanitizer/sanitation/CustomSanitation.java index d093f9d..18a0dd4 100644 --- a/src/main/java/io/ljunggren/sanitizer/sanitation/CustomSanitation.java +++ b/src/main/java/io/ljunggren/sanitizer/sanitation/CustomSanitation.java @@ -1,38 +1,39 @@ -package io.ljunggren.sanitizer.sanitation; - -import java.lang.annotation.Annotation; - -import io.ljunggren.sanitizer.Item; -import io.ljunggren.sanitizer.annotation.CustomSanitizer; -import io.ljunggren.sanitizer.cleanser.Cleanser; - -public class CustomSanitation extends SanitationChain { - - @Override - public void sanitize(Annotation annotation, Item item) { - if (annotation.annotationType() == CustomSanitizer.class) { - Class clazz = ((CustomSanitizer) annotation).value(); - try { - Cleanser cleanser = instantiateCleanser(clazz); - item.setValue(cleanser.cleanse(item.getValue())); - } catch (Exception e) { - // do something with exception - } - return; - } - nextChain.sanitize(annotation, item); - } - - @SuppressWarnings("unchecked") - private Cleanser instantiateCleanser(Class clazz) throws Exception { - try { - if (Cleanser.class.isAssignableFrom(clazz)) { - return (Cleanser) clazz.getDeclaredConstructor().newInstance(); - } - throw new Exception(String.format("CustomSanitizer(%s) does not implement Cleanser", clazz.getSimpleName())); - } catch (ClassNotFoundException e) { - throw new Exception("CustomSanitizer class not found " + e.getMessage()); - } - } - -} +package io.ljunggren.sanitizer.sanitation; + +import java.lang.annotation.Annotation; +import java.lang.reflect.InvocationTargetException; + +import io.ljunggren.sanitizer.Item; +import io.ljunggren.sanitizer.annotation.CustomSanitizer; +import io.ljunggren.sanitizer.cleanser.Cleanser; + +public class CustomSanitation extends SanitationChain { + + @Override + public void sanitize(Annotation annotation, Item item) { + if (annotation.annotationType() == CustomSanitizer.class) { + Class clazz = ((CustomSanitizer) annotation).value(); + if (!Cleanser.class.isAssignableFrom(clazz)) { + // The configured class does not implement Cleanser; skip rather than fail. + return; + } + try { + Cleanser cleanser = instantiateCleanser(clazz); + item.setValue(cleanser.cleanse(item.getValue())); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException( + "Failed to instantiate CustomSanitizer " + clazz.getName(), e); + } + return; + } + nextChain.sanitize(annotation, item); + } + + @SuppressWarnings("unchecked") + private Cleanser instantiateCleanser(Class clazz) + throws InstantiationException, IllegalAccessException, + InvocationTargetException, NoSuchMethodException { + return (Cleanser) clazz.getDeclaredConstructor().newInstance(); + } + +} diff --git a/src/main/java/io/ljunggren/sanitizer/sanitation/LowercaseSanitation.java b/src/main/java/io/ljunggren/sanitizer/sanitation/LowercaseSanitation.java index 97be428..5b7555c 100644 --- a/src/main/java/io/ljunggren/sanitizer/sanitation/LowercaseSanitation.java +++ b/src/main/java/io/ljunggren/sanitizer/sanitation/LowercaseSanitation.java @@ -1,23 +1,23 @@ -package io.ljunggren.sanitizer.sanitation; - -import java.lang.annotation.Annotation; - -import io.ljunggren.sanitizer.Item; -import io.ljunggren.sanitizer.annotation.Lowercase; -import io.ljunggren.sanitizer.cleanser.Cleanser; -import io.ljunggren.sanitizer.cleanser.LowercaseCleanser; - -public class LowercaseSanitation extends SanitationChain { - - private Class annotationClass = Lowercase.class; - private Cleanser cleanser = new LowercaseCleanser(); - - @Override - public void sanitize(Annotation annotation, Item item) { - if (annotation.annotationType() == annotationClass) { - sanitizeStringType(item, cleanser); - return; - } - nextChain.sanitize(annotation, item); - } -} +package io.ljunggren.sanitizer.sanitation; + +import java.lang.annotation.Annotation; + +import io.ljunggren.sanitizer.Item; +import io.ljunggren.sanitizer.annotation.Lowercase; +import io.ljunggren.sanitizer.cleanser.Cleanser; +import io.ljunggren.sanitizer.cleanser.LowercaseCleanser; + +public class LowercaseSanitation extends SanitationChain { + + private static final Class ANNOTATION_CLASS = Lowercase.class; + private static final Cleanser CLEANSER = new LowercaseCleanser(); + + @Override + public void sanitize(Annotation annotation, Item item) { + if (annotation.annotationType() == ANNOTATION_CLASS) { + sanitizeStringType(item, CLEANSER); + return; + } + nextChain.sanitize(annotation, item); + } +} diff --git a/src/main/java/io/ljunggren/sanitizer/sanitation/RemoveSanitation.java b/src/main/java/io/ljunggren/sanitizer/sanitation/RemoveSanitation.java index a95287b..aa3c0df 100644 --- a/src/main/java/io/ljunggren/sanitizer/sanitation/RemoveSanitation.java +++ b/src/main/java/io/ljunggren/sanitizer/sanitation/RemoveSanitation.java @@ -1,29 +1,25 @@ -package io.ljunggren.sanitizer.sanitation; - -import java.lang.annotation.Annotation; - -import io.ljunggren.sanitizer.Item; -import io.ljunggren.sanitizer.annotation.Remove; -import io.ljunggren.sanitizer.cleanser.Cleanser; -import io.ljunggren.sanitizer.cleanser.RemoveCleanser; - -public class RemoveSanitation extends SanitationChain { - - private Class annotationClass = Remove.class; - - @Override - public void sanitize(Annotation annotation, Item item) { - if (annotation.annotationType() == annotationClass) { - String toRemove = ((Remove) annotation).value(); - sanitize(item, toRemove); - return; - } - nextChain.sanitize(annotation, item); - } - - private void sanitize(Item item, String toRemove) { - Cleanser cleanser = new RemoveCleanser(toRemove); - sanitizeStringType(item, cleanser); - } - -} +package io.ljunggren.sanitizer.sanitation; + +import java.lang.annotation.Annotation; + +import io.ljunggren.sanitizer.Item; +import io.ljunggren.sanitizer.annotation.Remove; +import io.ljunggren.sanitizer.cleanser.Cleanser; +import io.ljunggren.sanitizer.cleanser.RemoveCleanser; + +public class RemoveSanitation extends SanitationChain { + + private static final Class ANNOTATION_CLASS = Remove.class; + + @Override + public void sanitize(Annotation annotation, Item item) { + if (annotation.annotationType() == ANNOTATION_CLASS) { + String toRemove = ((Remove) annotation).value(); + Cleanser cleanser = new RemoveCleanser(toRemove); + sanitizeStringType(item, cleanser); + return; + } + nextChain.sanitize(annotation, item); + } + +} diff --git a/src/main/java/io/ljunggren/sanitizer/sanitation/SanitationChain.java b/src/main/java/io/ljunggren/sanitizer/sanitation/SanitationChain.java index df9d587..890e242 100644 --- a/src/main/java/io/ljunggren/sanitizer/sanitation/SanitationChain.java +++ b/src/main/java/io/ljunggren/sanitizer/sanitation/SanitationChain.java @@ -1,76 +1,93 @@ -package io.ljunggren.sanitizer.sanitation; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -import io.ljunggren.reflectionUtils.ReflectionUtils; -import io.ljunggren.sanitizer.Item; -import io.ljunggren.sanitizer.cleanser.Cleanser; - -public abstract class SanitationChain { - - protected SanitationChain nextChain; - - public SanitationChain nextChain(SanitationChain nextChain) { - this.nextChain = nextChain; - return this; - } - - public abstract void sanitize(Annotation annotation, Item item); - - protected boolean isString(Item item) { - return item.getValue() instanceof String; - } - - protected boolean isCollectionOfStrings(Item item) { - if (ReflectionUtils.isCollection(item.getValue())) { - Type type = ReflectionUtils.getParameterizedType(item.getField().getGenericType()); - return ReflectionUtils.isString(type); - } - return false; - } - - protected boolean isArrayOfStrings(Item item) { - if (ReflectionUtils.isArray(item.getValue())) { - Type type = ReflectionUtils.getArrayComponentType(item.getField().getGenericType()); - return ReflectionUtils.isString(type); - } - return false; - } - - @SuppressWarnings("unchecked") - protected void sanitizeCollectionOfStrings(Item item, Cleanser cleanser) { - Collection collection = (Collection) item.getValue(); - List sanitized = collection.stream().map(element -> cleanser.cleanse((String) element)).toList(); - collection.clear(); - collection.addAll(sanitized); - } - - protected void sanitizeArrayOfString(Item item, Cleanser cleanser) { - String[] array = (String[]) item.getValue(); - String[] sanitized = Arrays.stream(array).map(element -> cleanser.cleanse((String) element)).toArray(String[]::new); - item.setValue(sanitized); - } - - protected void sanitizeStringType(Item item, Cleanser cleanser) { - if (item == null) { - return; - } - if (isString(item)) { - item.setValue(cleanser.cleanse(item.getValue().toString())); - return; - } - if (isCollectionOfStrings(item)) { - sanitizeCollectionOfStrings(item, cleanser); - return; - } - if (isArrayOfStrings(item)) { - sanitizeArrayOfString(item, cleanser); - return; - } - } - -} +package io.ljunggren.sanitizer.sanitation; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; + +import io.ljunggren.reflectionUtils.ReflectionUtils; +import io.ljunggren.sanitizer.Item; +import io.ljunggren.sanitizer.cleanser.Cleanser; + +/** + * Base class for the sanitation chain-of-responsibility. + * + *

Each concrete subclass handles a specific annotation; if the annotation + * does not match it forwards the call to {@link #nextChain}. Helper methods + * are provided for the common case of cleansing {@link String} values, as + * well as collections and arrays of strings.

+ */ +public abstract class SanitationChain { + + protected SanitationChain nextChain; + + public SanitationChain nextChain(SanitationChain nextChain) { + this.nextChain = nextChain; + return this; + } + + public abstract void sanitize(Annotation annotation, Item item); + + protected boolean isString(Item item) { + return item.getValue() instanceof String; + } + + protected boolean isCollectionOfStrings(Item item) { + if (ReflectionUtils.isCollection(item.getValue())) { + Type type = ReflectionUtils.getParameterizedType(item.getField().getGenericType()); + return ReflectionUtils.isString(type); + } + return false; + } + + protected boolean isArrayOfStrings(Item item) { + if (ReflectionUtils.isArray(item.getValue())) { + Type type = ReflectionUtils.getArrayComponentType(item.getField().getGenericType()); + return ReflectionUtils.isString(type); + } + return false; + } + + @SuppressWarnings("unchecked") + protected void sanitizeCollectionOfStrings(Item item, Cleanser cleanser) { + Collection collection = (Collection) item.getValue(); + List sanitized = collection.stream() + .map(cleanser::cleanse) + .collect(Collectors.toCollection(ArrayList::new)); + try { + collection.clear(); + collection.addAll(sanitized); + } catch (UnsupportedOperationException e) { + // Collection was unmodifiable; nothing more we can do safely. + } + } + + protected void sanitizeArrayOfStrings(Item item, Cleanser cleanser) { + String[] array = (String[]) item.getValue(); + String[] sanitized = Arrays.stream(array) + .map(cleanser::cleanse) + .toArray(String[]::new); + item.setValue(sanitized); + } + + protected void sanitizeStringType(Item item, Cleanser cleanser) { + if (item == null) { + return; + } + if (isString(item)) { + item.setValue(cleanser.cleanse((String) item.getValue())); + return; + } + if (isCollectionOfStrings(item)) { + sanitizeCollectionOfStrings(item, cleanser); + return; + } + if (isArrayOfStrings(item)) { + sanitizeArrayOfStrings(item, cleanser); + } + } + +} diff --git a/src/main/java/io/ljunggren/sanitizer/sanitation/TrimSanitation.java b/src/main/java/io/ljunggren/sanitizer/sanitation/TrimSanitation.java index 35b0ffe..ab6ed11 100644 --- a/src/main/java/io/ljunggren/sanitizer/sanitation/TrimSanitation.java +++ b/src/main/java/io/ljunggren/sanitizer/sanitation/TrimSanitation.java @@ -1,23 +1,23 @@ -package io.ljunggren.sanitizer.sanitation; - -import java.lang.annotation.Annotation; - -import io.ljunggren.sanitizer.Item; -import io.ljunggren.sanitizer.annotation.Trim; -import io.ljunggren.sanitizer.cleanser.Cleanser; -import io.ljunggren.sanitizer.cleanser.TrimCleanser; - -public class TrimSanitation extends SanitationChain { - - private Class annotationClass = Trim.class; - private Cleanser cleanser = new TrimCleanser(); - - @Override - public void sanitize(Annotation annotation, Item item) { - if (annotation.annotationType() == annotationClass) { - sanitizeStringType(item, cleanser); - return; - } - nextChain.sanitize(annotation, item); - } -} +package io.ljunggren.sanitizer.sanitation; + +import java.lang.annotation.Annotation; + +import io.ljunggren.sanitizer.Item; +import io.ljunggren.sanitizer.annotation.Trim; +import io.ljunggren.sanitizer.cleanser.Cleanser; +import io.ljunggren.sanitizer.cleanser.TrimCleanser; + +public class TrimSanitation extends SanitationChain { + + private static final Class ANNOTATION_CLASS = Trim.class; + private static final Cleanser CLEANSER = new TrimCleanser(); + + @Override + public void sanitize(Annotation annotation, Item item) { + if (annotation.annotationType() == ANNOTATION_CLASS) { + sanitizeStringType(item, CLEANSER); + return; + } + nextChain.sanitize(annotation, item); + } +} diff --git a/src/main/java/io/ljunggren/sanitizer/sanitation/TrimToNullSanitation.java b/src/main/java/io/ljunggren/sanitizer/sanitation/TrimToNullSanitation.java index e63c74d..4290d09 100644 --- a/src/main/java/io/ljunggren/sanitizer/sanitation/TrimToNullSanitation.java +++ b/src/main/java/io/ljunggren/sanitizer/sanitation/TrimToNullSanitation.java @@ -8,14 +8,14 @@ import io.ljunggren.sanitizer.cleanser.TrimToNullCleanser; public class TrimToNullSanitation extends SanitationChain { - - private Class annotationClass = TrimToNull.class; - private Cleanser cleanser = new TrimToNullCleanser(); + + private static final Class ANNOTATION_CLASS = TrimToNull.class; + private static final Cleanser CLEANSER = new TrimToNullCleanser(); @Override public void sanitize(Annotation annotation, Item item) { - if (annotation.annotationType() == annotationClass) { - sanitizeStringType(item, cleanser); + if (annotation.annotationType() == ANNOTATION_CLASS) { + sanitizeStringType(item, CLEANSER); return; } nextChain.sanitize(annotation, item); diff --git a/src/main/java/io/ljunggren/sanitizer/sanitation/UppercaseSanitation.java b/src/main/java/io/ljunggren/sanitizer/sanitation/UppercaseSanitation.java index 52d8261..3428456 100644 --- a/src/main/java/io/ljunggren/sanitizer/sanitation/UppercaseSanitation.java +++ b/src/main/java/io/ljunggren/sanitizer/sanitation/UppercaseSanitation.java @@ -1,23 +1,23 @@ -package io.ljunggren.sanitizer.sanitation; - -import java.lang.annotation.Annotation; - -import io.ljunggren.sanitizer.Item; -import io.ljunggren.sanitizer.annotation.Uppercase; -import io.ljunggren.sanitizer.cleanser.Cleanser; -import io.ljunggren.sanitizer.cleanser.UppercaseCleanser; - -public class UppercaseSanitation extends SanitationChain { - - private Class annotationClass = Uppercase.class; - private Cleanser cleanser = new UppercaseCleanser(); - - @Override - public void sanitize(Annotation annotation, Item item) { - if (annotation.annotationType() == annotationClass) { - sanitizeStringType(item, cleanser); - return; - } - nextChain.sanitize(annotation, item); - } -} +package io.ljunggren.sanitizer.sanitation; + +import java.lang.annotation.Annotation; + +import io.ljunggren.sanitizer.Item; +import io.ljunggren.sanitizer.annotation.Uppercase; +import io.ljunggren.sanitizer.cleanser.Cleanser; +import io.ljunggren.sanitizer.cleanser.UppercaseCleanser; + +public class UppercaseSanitation extends SanitationChain { + + private static final Class ANNOTATION_CLASS = Uppercase.class; + private static final Cleanser CLEANSER = new UppercaseCleanser(); + + @Override + public void sanitize(Annotation annotation, Item item) { + if (annotation.annotationType() == ANNOTATION_CLASS) { + sanitizeStringType(item, CLEANSER); + return; + } + nextChain.sanitize(annotation, item); + } +} diff --git a/src/test/java/io/ljunggren/sanitizer/ItemTest.java b/src/test/java/io/ljunggren/sanitizer/ItemTest.java new file mode 100755 index 0000000..7fc4c83 --- /dev/null +++ b/src/test/java/io/ljunggren/sanitizer/ItemTest.java @@ -0,0 +1,64 @@ +package io.ljunggren.sanitizer; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; + +import java.lang.reflect.Field; + +import org.junit.Test; + +public class ItemTest { + + private static class Holder { + @SuppressWarnings("unused") + private String name = "initial"; + } + + @Test + public void constructorAndGettersTest() throws NoSuchFieldException { + Holder holder = new Holder(); + Field field = Holder.class.getDeclaredField("name"); + Item item = new Item(holder, field, "value"); + assertSame(holder, item.getObject()); + assertSame(field, item.getField()); + assertEquals("value", item.getValue()); + } + + @Test + public void setValueUpdatesItemAndFieldTest() throws NoSuchFieldException, IllegalAccessException { + Holder holder = new Holder(); + Field field = Holder.class.getDeclaredField("name"); + field.setAccessible(true); + Item item = new Item(holder, field, field.get(holder)); + item.setValue("updated"); + assertEquals("updated", item.getValue()); + assertEquals("updated", field.get(holder)); + } + + @Test + public void setValueAcceptsNullTest() throws NoSuchFieldException, IllegalAccessException { + Holder holder = new Holder(); + Field field = Holder.class.getDeclaredField("name"); + field.setAccessible(true); + Item item = new Item(holder, field, "value"); + item.setValue(null); + assertNull(item.getValue()); + assertNull(field.get(holder)); + } + + @Test + public void setValueWrongTypeThrowsTest() throws NoSuchFieldException { + Holder holder = new Holder(); + Field field = Holder.class.getDeclaredField("name"); + Item item = new Item(holder, field, "value"); + try { + item.setValue(Integer.valueOf(1)); + fail("Expected IllegalStateException for type mismatch"); + } catch (IllegalStateException expected) { + assertNotNull(expected.getCause()); + } + } +} diff --git a/src/test/java/io/ljunggren/sanitizer/SanitizerExtraTest.java b/src/test/java/io/ljunggren/sanitizer/SanitizerExtraTest.java new file mode 100755 index 0000000..dff5dfc --- /dev/null +++ b/src/test/java/io/ljunggren/sanitizer/SanitizerExtraTest.java @@ -0,0 +1,107 @@ +package io.ljunggren.sanitizer; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +import io.ljunggren.sanitizer.annotation.Lowercase; +import io.ljunggren.sanitizer.annotation.Uppercase; +import lombok.AllArgsConstructor; +import lombok.Getter; + +public class SanitizerExtraTest { + + @AllArgsConstructor + @Getter + private static class TopLevelArrayPojo { + @Uppercase + private String[] names; + } + + @AllArgsConstructor + @Getter + private static class Inner { + @Lowercase + private String name; + } + + @AllArgsConstructor + @Getter + private static class CollectionOfInner { + private List inners; + } + + @AllArgsConstructor + @Getter + private static class CollectionWithNullEntries { + private List inners; + } + + @Test + public void gettersTest() { + Object target = new Object(); + Sanitizer sanitizer = new Sanitizer(target); + assertSame(target, sanitizer.getObject()); + assertFalse(sanitizer.isRecursive()); + assertSame(sanitizer, sanitizer.recursive()); + assertTrue(sanitizer.isRecursive()); + } + + @Test + public void sanitizeNullObjectTest() { + Sanitizer sanitizer = new Sanitizer(null); + Sanitizer returned = sanitizer.sanitize(); + assertSame(sanitizer, returned); + assertNull(sanitizer.getObject()); + } + + @Test + public void topLevelArraySanitizesTest() { + TopLevelArrayPojo pojo = new TopLevelArrayPojo(new String[] {"a", "b"}); + new Sanitizer(pojo).sanitize(); + assertEquals("A", pojo.getNames()[0]); + assertEquals("B", pojo.getNames()[1]); + } + + @Test + public void recursiveCollectionOfPojosTest() { + List inners = new ArrayList<>(Arrays.asList(new Inner("Alex"), new Inner("Gage"))); + CollectionOfInner pojo = new CollectionOfInner(inners); + new Sanitizer(pojo).recursive().sanitize(); + assertEquals("alex", pojo.getInners().get(0).getName()); + assertEquals("gage", pojo.getInners().get(1).getName()); + } + + @Test + public void recursiveCollectionWithNullEntriesTest() { + List inners = new ArrayList<>(Arrays.asList(new Inner("Alex"), null, new Inner("Gage"))); + CollectionWithNullEntries pojo = new CollectionWithNullEntries(inners); + new Sanitizer(pojo).recursive().sanitize(); + assertEquals("alex", pojo.getInners().get(0).getName()); + assertNull(pojo.getInners().get(1)); + assertEquals("gage", pojo.getInners().get(2).getName()); + } + + @Test + public void recursiveNullCollectionTest() { + CollectionOfInner pojo = new CollectionOfInner(null); + new Sanitizer(pojo).recursive().sanitize(); + assertNull(pojo.getInners()); + } + + @Test + public void nonRecursiveDoesNotDescendTest() { + List inners = new ArrayList<>(Arrays.asList(new Inner("Alex"))); + CollectionOfInner pojo = new CollectionOfInner(inners); + new Sanitizer(pojo).sanitize(); + assertEquals("Alex", pojo.getInners().get(0).getName()); + } +} diff --git a/src/test/java/io/ljunggren/sanitizer/cleanser/RemoveCleanserExtraTest.java b/src/test/java/io/ljunggren/sanitizer/cleanser/RemoveCleanserExtraTest.java new file mode 100755 index 0000000..dc92ae0 --- /dev/null +++ b/src/test/java/io/ljunggren/sanitizer/cleanser/RemoveCleanserExtraTest.java @@ -0,0 +1,27 @@ +package io.ljunggren.sanitizer.cleanser; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class RemoveCleanserExtraTest { + + @Test + public void emptyToRemoveLeavesValueUnchangedTest() { + assertEquals("Programming", new RemoveCleanser("").cleanse("Programming")); + } + + @Test + public void regexMetacharactersAreLiteralTest() { + // Prior implementation used replaceAll which would treat '.' as 'any character' + // and strip every character. The literal replace must only remove '.'. + assertEquals("abc", new RemoveCleanser(".").cleanse("a.b.c.")); + assertEquals("xy", new RemoveCleanser("(a)").cleanse("x(a)y")); + assertEquals("ab", new RemoveCleanser("\\d").cleanse("a\\db")); + } + + @Test + public void descriptionWithSpecialCharsTest() { + assertEquals("Remove all .", new RemoveCleanser(".").description()); + } +} diff --git a/src/test/java/io/ljunggren/sanitizer/cleanser/ReplaceCleanserExtraTest.java b/src/test/java/io/ljunggren/sanitizer/cleanser/ReplaceCleanserExtraTest.java new file mode 100755 index 0000000..9385ee2 --- /dev/null +++ b/src/test/java/io/ljunggren/sanitizer/cleanser/ReplaceCleanserExtraTest.java @@ -0,0 +1,25 @@ +package io.ljunggren.sanitizer.cleanser; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class ReplaceCleanserExtraTest { + + @Test + public void emptyReplacerLeavesValueUnchangedTest() { + assertEquals("hello", new ReplaceCleanser("", "X").cleanse("hello")); + } + + @Test + public void replacementContainingReplacerDoesNotLoopTest() { + // Replacing 'a' with 'aa' would loop forever in a naive recursive impl. + // Verify the cleanser terminates and produces 'aa'. + assertEquals("aa", new ReplaceCleanser("a", "aa").cleanse("a")); + } + + @Test + public void noOccurrenceLeavesValueUnchangedTest() { + assertEquals("xyz", new ReplaceCleanser("a", "b").cleanse("xyz")); + } +} diff --git a/src/test/java/io/ljunggren/sanitizer/cleanser/TrimToNullCleanserTest.java b/src/test/java/io/ljunggren/sanitizer/cleanser/TrimToNullCleanserTest.java new file mode 100755 index 0000000..2db111c --- /dev/null +++ b/src/test/java/io/ljunggren/sanitizer/cleanser/TrimToNullCleanserTest.java @@ -0,0 +1,32 @@ +package io.ljunggren.sanitizer.cleanser; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +public class TrimToNullCleanserTest { + + @Test + public void cleanseTest() { + assertEquals("Alex", new TrimToNullCleanser().cleanse(" Alex ")); + assertEquals("Alex", new TrimToNullCleanser().cleanse("Alex")); + } + + @Test + public void cleanseEmptyOrWhitespaceReturnsNullTest() { + assertNull(new TrimToNullCleanser().cleanse("")); + assertNull(new TrimToNullCleanser().cleanse(" ")); + } + + @Test + public void cleanseNullTest() { + assertNull(new TrimToNullCleanser().cleanse(null)); + } + + @Test + public void descriptionTest() { + assertEquals("Remove leading and trailing spaces and returns null if empty", + new TrimToNullCleanser().description()); + } +} diff --git a/src/test/java/io/ljunggren/sanitizer/sanitation/CustomSanitationExtraTest.java b/src/test/java/io/ljunggren/sanitizer/sanitation/CustomSanitationExtraTest.java new file mode 100755 index 0000000..45f4bee --- /dev/null +++ b/src/test/java/io/ljunggren/sanitizer/sanitation/CustomSanitationExtraTest.java @@ -0,0 +1,77 @@ +package io.ljunggren.sanitizer.sanitation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.Test; + +import io.ljunggren.sanitizer.Sanitizer; +import io.ljunggren.sanitizer.annotation.CustomSanitizer; +import io.ljunggren.sanitizer.cleanser.Cleanser; +import lombok.AllArgsConstructor; +import lombok.Getter; + +public class CustomSanitationExtraTest { + + /** A Cleanser implementation with no accessible no-arg constructor. */ + public static class NoNoArgCleanser implements Cleanser { + public NoNoArgCleanser(String required) { + // requires an argument + if (required == null) { + throw new IllegalArgumentException("required"); + } + } + @Override + public String cleanse(Object value) { + return value == null ? null : value.toString(); + } + @Override + public String description() { + return "no-arg-missing"; + } + } + + /** A trivial Cleanser that pads its input. */ + public static class BangCleanser implements Cleanser { + @Override + public String cleanse(Object value) { + return value == null ? null : value + "!"; + } + @Override + public String description() { + return "append bang"; + } + } + + @AllArgsConstructor + @Getter + private static class BadPojo { + @CustomSanitizer(NoNoArgCleanser.class) + private String name; + } + + @AllArgsConstructor + @Getter + private static class GoodPojo { + @CustomSanitizer(BangCleanser.class) + private String name; + } + + @Test + public void instantiationFailureThrowsIllegalStateTest() { + BadPojo pojo = new BadPojo("alex"); + try { + new Sanitizer(pojo).sanitize(); + fail("Expected IllegalStateException because Cleanser has no no-arg constructor"); + } catch (IllegalStateException expected) { + // expected + } + } + + @Test + public void appliesCustomCleanserTest() { + GoodPojo pojo = new GoodPojo("alex"); + new Sanitizer(pojo).sanitize(); + assertEquals("alex!", pojo.getName()); + } +}