X-Git-Url: https://juplo.de/gitweb/?p=facebook-errors;a=blobdiff_plain;f=src%2Fmain%2Fjava%2Fde%2Fjuplo%2Ffacebook%2Faspects%2FSanitizeAspect.java;fp=src%2Fmain%2Fjava%2Fde%2Fjuplo%2Ffacebook%2Faspects%2FSanitizeAspect.java;h=4bdf908ff01b924522ad88bd34806571c5695660;hp=0000000000000000000000000000000000000000;hb=2344baa082277120401d815461d5e13e831d510f;hpb=bc0989ddb7bb05e2d95ae4aad4438b4d4806f9dc diff --git a/src/main/java/de/juplo/facebook/aspects/SanitizeAspect.java b/src/main/java/de/juplo/facebook/aspects/SanitizeAspect.java new file mode 100644 index 0000000..4bdf908 --- /dev/null +++ b/src/main/java/de/juplo/facebook/aspects/SanitizeAspect.java @@ -0,0 +1,93 @@ +package de.juplo.facebook.aspects; + + +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + + +/** + * @author Kai Moritz + */ +@Aspect +public class SanitizeAspect +{ + private static final Logger log = + LoggerFactory.getLogger(SanitizeAspect.class); + + + /** + * This method sanitizes the given string in all means: + * + * + * This method ensures that the output String has only + * valid XML unicode characters as specified by the + * XML 1.0 standard. For reference, please see + * the + * standard. This method will return an empty + * String if the input is null or empty. + * + * @param jp The join-point captured by AspectJ. + * @param in The String whose non-valid characters we want to remove. + * @param sanitize The annotation, the field was marked with. + * @see Invalid XML Characters: when valid UTF8 does not mean valid XML + * @see Ungültige Zeichen in Eingabefeldern abfangen + */ + @Around("set(String *) && args(in) && @annotation(sanitize)") + public void sanitize( + ProceedingJoinPoint jp, + String in, + Sanitize sanitize + ) + throws Throwable + { + if (in == null) + { + jp.proceed(new Object[] { null }); + return; + } + + in = in.trim(); + if ("".equals(in)) + { + jp.proceed(new Object[] { null }); + return; + } + + StringBuilder out = new StringBuilder(); // Used to hold the output. + char current; // Used to reference the current character. + + for (int i = 0; i < in.length(); i++) + { + current = in.charAt(i); // NOTE: No IndexOutOfBoundsException caught here; it should not happen. + if ((current == 0x9) || + (current == 0xA) || + (current == 0xD) || + ((current >= 0x20) && (current <= 0xD7FF)) || + ((current >= 0xE000) && (current <= 0xFFFD)) || + ((current >= 0x10000) && (current <= 0x10FFFF))) + out.append(current); + } + if (out.length() > sanitize.length()) + { + log.error( + "Maximum length for attribute {} exceeded: should={}, was={}", + jp.getSignature().getName(), + sanitize.length(), + out.length() + ); + if (sanitize.fail()) + throw new RuntimeException("String is longer than " + sanitize.length()); + else + out.setLength(sanitize.length()); + } + jp.proceed(new Object[] { out.toString() }); + } +}