123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635 |
- package cn.com.ty.lift.common.verify;
- import lombok.extern.slf4j.Slf4j;
- import javax.validation.constraints.*;
- import java.lang.annotation.Annotation;
- import java.lang.invoke.MethodHandle;
- import java.lang.invoke.MethodHandles;
- import java.lang.invoke.MethodType;
- import java.lang.reflect.Array;
- import java.lang.reflect.Field;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.math.BigDecimal;
- import java.math.BigInteger;
- import java.net.IDN;
- import java.security.AccessController;
- import java.security.PrivilegedAction;
- import java.time.*;
- import java.time.chrono.HijrahDate;
- import java.time.chrono.JapaneseDate;
- import java.time.chrono.MinguoDate;
- import java.time.chrono.ThaiBuddhistDate;
- import java.time.temporal.TemporalAccessor;
- import java.util.*;
- import java.util.concurrent.ConcurrentHashMap;
- import java.util.regex.Matcher;
- import java.util.regex.PatternSyntaxException;
- import java.util.stream.Collectors;
- import static java.util.regex.Pattern.CASE_INSENSITIVE;
- /**
- * the validation for parameter implements {@linkplain javax.validation.constraints},
- * reform from hibernate validator (v6.0.16.Final)
- *
- * @author wcz
- * @since 2020/2/15
- */
- @Slf4j
- public class VerifyProcessor {
- /**
- * the name of the verify method.
- */
- private static final String VerifyMethodName = "verify";
- /**
- * the list of validation annotation & method can be work in {@code javax.validation.constraints.*}
- */
- private static final Map<Class<?>, Method> ClassMethodCache = new ConcurrentHashMap<>();
- private static final Map<Class<?>, MethodHandle> ClassMethodHandleCache = new ConcurrentHashMap<>();
- private static final Map<Field, Annotation[]> FieldAnnotationCache = new ConcurrentHashMap<>();
- /**
- * the max length for a valid email address local part.
- */
- private static final int MAX_LOCAL_PART_LENGTH = 64;
- /**
- * the regular expression for local part of a valid email address.
- */
- private static final String LOCAL_PART_ATOM = "[a-z0-9!#$%&'*+/=?^_`{|}~\u0080-\uFFFF-]";
- /**
- * the regular expression for the local part of an email address.
- */
- private static final String LOCAL_PART_INSIDE_QUOTES_ATOM = "([a-z0-9!#$%&'*.(),<>\\[\\]:; @+/=?^_`{|}~\u0080-\uFFFF-]|\\\\\\\\|\\\\\\\")";
- /**
- * Regular expression for the local part of an email address (everything before '@')
- */
- private static final java.util.regex.Pattern LOCAL_PART_PATTERN = java.util.regex.Pattern.compile(
- "(" + LOCAL_PART_ATOM + "+|\"" + LOCAL_PART_INSIDE_QUOTES_ATOM + "+\")" +
- "(\\." + "(" + LOCAL_PART_ATOM + "+|\"" + LOCAL_PART_INSIDE_QUOTES_ATOM + "+\")" + ")*", CASE_INSENSITIVE
- );
- /**
- * This is the maximum length of a domain name. But be aware that each label (parts separated by a dot) of the
- * domain name must be at most 63 characters long. This is verified by {@link IDN#toASCII(String)}.
- */
- private static final int MAX_DOMAIN_PART_LENGTH = 255;
- private static final String DOMAIN_CHARS_WITHOUT_DASH = "[a-z\u0080-\uFFFF0-9!#$%&'*+/=?^_`{|}~]";
- private static final String DOMAIN_LABEL = "(" + DOMAIN_CHARS_WITHOUT_DASH + "-*)*" + DOMAIN_CHARS_WITHOUT_DASH + "+";
- /**
- * the regex for check domain
- */
- private static final String DOMAIN = DOMAIN_LABEL + "+(\\." + DOMAIN_LABEL + "+)*";
- /**
- * regex for check IP v4
- */
- private static final String IP_DOMAIN = "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}";
- /**
- * IP v6 regex taken from http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
- */
- private static final String IP_V6_DOMAIN = "(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))";
- /**
- * Regular expression for the domain part of an URL
- * A host string must be a domain string, an IPv4 address string, or "[", followed by an IPv6 address string, followed by "]".
- */
- private static final java.util.regex.Pattern DOMAIN_PATTERN = java.util.regex.Pattern.compile(DOMAIN + "|\\[" + IP_V6_DOMAIN + "\\]", CASE_INSENSITIVE);
- /**
- * Regular expression for the domain part of an email address (everything after '@')
- */
- private static final java.util.regex.Pattern EMAIL_DOMAIN_PATTERN = java.util.regex.Pattern.compile(
- DOMAIN + "|\\[" + IP_DOMAIN + "\\]|" + "\\[IPv6:" + IP_V6_DOMAIN + "\\]", CASE_INSENSITIVE
- );
- /**
- * the minimum value of compare two number for the infinity check when double or float.
- */
- private static final OptionalInt LESS_THAN = OptionalInt.of(-1);
- /**
- * the empty OptionalInt(value = 0) of compare two number for the infinity check when double or float.
- */
- private static final OptionalInt FINITE_VALUE = OptionalInt.empty();
- /**
- * the maximun value of compare two number for the infinity check when double or float.
- */
- private static final OptionalInt GREATER_THAN = OptionalInt.of(1);
- /**
- * short 0
- */
- private static final short SHORT_ZERO = (short) 0;
- /**
- * byte 0
- */
- private static final byte BYTE_ZERO = (byte) 0;
- /**
- * to private the constrctor.
- */
- private VerifyProcessor() {
- }
- /**
- * collect all vaild validation annotation from the methods.
- */
- static {
- collectValidAnnotationMethod();
- }
- private static void collectValidAnnotationMethod() {
- Method[] declaredMethods = VerifyAction.class.getDeclaredMethods();
- List<Method> verifyMethods = Arrays.stream(declaredMethods).filter(method -> VerifyMethodName.equals(method.getName())).collect(Collectors.toList());
- isTrue(verifyMethods.isEmpty(), "No any method named 'verify' in VerifyAction.");
- for (Method method : verifyMethods) {
- Optional<Class<?>> classOptional = Arrays.stream(method.getParameterTypes()).filter(Annotation.class::isAssignableFrom).findFirst();
- classOptional.ifPresent(verifyClass -> {
- if (!method.isAccessible()) {
- method.setAccessible(true);
- }
- ClassMethodCache.put(verifyClass, method);
- log.info("@interface: {}", verifyClass.getCanonicalName());
- });
- }
- isTrue(ClassMethodCache.isEmpty(), "No valid validation annotation was resolved in VerifyAction.");
- }
- /**
- * to do verify by using the singleton instance.
- *
- * @param logWrite {@code true} log information, otherwise no log to file.
- * @param object the target object to verify.
- * @param fields the list of fields to verify.
- */
- public static void perform(final boolean logWrite, final Object object, final String... fields) {
- new VerifyAction(logWrite, object, fields).action();
- }
- /**
- * to do verify by using the singleton instance.
- *
- * @param object the target object to verify.
- * @param fields the list of fields to verify.
- */
- public static void perform(final Object object, final String... fields) {
- new VerifyAction(object, fields).action();
- }
- /**
- * get the systemDefaultZone {@link Clock#systemDefaultZone()}. for the date compare.
- */
- private static Clock systemDefaultClock() {
- return Clock.offset(Clock.systemDefaultZone(), Duration.ZERO.abs().negated());
- }
- private static <T> boolean isEmpty(T[] array) {
- return array == null || array.length == 0;
- }
- private static boolean notBlank(String value) {
- return null != value && !value.trim().isEmpty();
- }
- /**
- * verify the value is instance of the Number.
- *
- * @param value any value.
- * @return if return {@code true}, the value is Number, otherwise no
- */
- private static boolean isNumber(Object value) {
- return (value instanceof Number);
- }
- /**
- * verify the value is instance of the CharSequence.
- *
- * @param value any value.
- * @return if return {@code true}, the value is CharSequence, otherwise no
- */
- private static boolean isCharSequence(Object value) {
- return (value instanceof CharSequence);
- }
- /**
- * verify the value is instance of the BigDecimal.
- *
- * @param value any value.
- * @return if return {@code true}, the value is BigDecimal, otherwise no
- */
- private static boolean isBigDecimal(Object value) {
- return (value instanceof BigDecimal);
- }
- /**
- * verify the value is instance of the BigInteger.
- *
- * @param value any value.
- * @return if return {@code true}, the value is BigInteger, otherwise no
- */
- private static boolean isBigInteger(Object value) {
- return (value instanceof BigInteger);
- }
- /**
- * verify the value is instance of the Long.
- *
- * @param value any value.
- * @return if return {@code true}, the value is Long, otherwise no
- */
- private static boolean isLong(Object value) {
- return (value instanceof Long);
- }
- /**
- * verify the value is instance of the Double.
- *
- * @param value any value.
- * @return if return {@code true}, the value is Double, otherwise no
- */
- private static boolean isDouble(Object value) {
- return (value instanceof Double);
- }
- /**
- * verify the value is instance of the Float.
- *
- * @param value any value.
- * @return if return {@code true}, the value is Float, otherwise no
- */
- private static boolean isFloat(Object value) {
- return (value instanceof Float);
- }
- /**
- * verify the value is instance of the TemporalAccessor(java 8).
- *
- * @param value any value.
- * @return if return {@code true}, the value is TemporalAccessor, otherwise no
- */
- private static boolean isTemporalAccessor(Object value) {
- return (value instanceof TemporalAccessor);
- }
- /**
- * verify the value is instance of the java.util.Date.
- *
- * @param value any value.
- * @return if return {@code true}, the value is Date, otherwise no
- */
- private static boolean isDate(Object value) {
- return (value instanceof Date);
- }
- /**
- * verify the value is instance of the java.util.Calendar.
- *
- * @param value any value.
- * @return if return true, the value is Calendar, otherwise no
- */
- private static boolean isCalendar(Object value) {
- return (value instanceof Calendar);
- }
- /**
- * verify whether a double value is infinity with less or greater.
- *
- * @param number any double value.
- * @param treatNanAs when the value isn't a number, return this value.
- * @return a OptionalInt value with the result of compare to infinity.
- * -1 for equal {@link Double#NEGATIVE_INFINITY}
- * 1 for equal {@link Double#POSITIVE_INFINITY}
- */
- private static OptionalInt infinityCheck(Double number, OptionalInt treatNanAs) {
- if (number == Double.NEGATIVE_INFINITY) {
- return LESS_THAN;
- } else if (number.isNaN()) {
- return treatNanAs;
- } else if (number == Double.POSITIVE_INFINITY) {
- return GREATER_THAN;
- } else {
- return FINITE_VALUE;
- }
- }
- /**
- * verify whether a float vlaue is infinity with less or greater.
- *
- * @param number any float value.
- * @param treatNanAs when the value isn't a number, return this value.
- * @return a OptionalInt value with the result of compare to infinity.
- * -1 for equal {@link Float#NEGATIVE_INFINITY}
- * 1 for equal {@link Float#POSITIVE_INFINITY}
- */
- private static OptionalInt infinityCheck(Float number, OptionalInt treatNanAs) {
- if (number == Float.NEGATIVE_INFINITY) {
- return LESS_THAN;
- } else if (number.isNaN()) {
- return treatNanAs;
- } else if (number == Float.POSITIVE_INFINITY) {
- return GREATER_THAN;
- } else {
- return FINITE_VALUE;
- }
- }
- /**
- * compare two bigdecimal value
- *
- * @param value any object value
- * @param val the bigdecimal value transform from the object value
- * @param bounds the boundary of the maximum or minimum
- * @param treatNanAs return for the value isn't number when check for infinity
- * @return return {@code -1} for the val is less than boundary, {@code 0} for equal,{@code 1} for greater than boundary.
- */
- private static int decimalComparator(Object value, BigDecimal val, BigDecimal bounds, OptionalInt treatNanAs) {
- if (isLong(value) || isBigInteger(value) || isBigDecimal(value)) {
- return val.compareTo(bounds);
- }
- if (isDouble(value)) {
- Double v = (Double) value;
- OptionalInt infinity = infinityCheck(v, treatNanAs);
- if (infinity.isPresent()) {
- return infinity.getAsInt();
- } else {
- return val.compareTo(bounds);
- }
- }
- if (isFloat(value)) {
- Float v = (Float) value;
- OptionalInt infinity = infinityCheck(v, treatNanAs);
- if (infinity.isPresent()) {
- return infinity.getAsInt();
- } else {
- return val.compareTo(bounds);
- }
- }
- return val.compareTo(bounds);
- }
- /**
- * get the length or size of the value.
- *
- * @param value any object value
- * @return the length or size of the value when it's working, but return zero when the value is null.
- */
- private static int length(Object value) {
- if (Objects.isNull(value)) {
- return 0;
- }
- if (isCharSequence(value)) {
- return ((CharSequence) value).length();
- }
- if (value instanceof Collection) {
- return ((Collection<?>) value).size();
- }
- if (value instanceof Map) {
- return ((Map<?, ?>) value).size();
- }
- if (value.getClass().isArray()) {
- return Array.getLength(value);
- }
- int count;
- if (value instanceof Iterator) {
- Iterator<?> iter = (Iterator<?>) value;
- count = 0;
- while (iter.hasNext()) {
- count++;
- iter.next();
- }
- return count;
- }
- if (value instanceof Enumeration) {
- Enumeration<?> enumeration = (Enumeration<?>) value;
- count = 0;
- while (enumeration.hasMoreElements()) {
- count++;
- enumeration.nextElement();
- }
- return count;
- }
- return -1;
- }
- /**
- * compare two number value with less than or greater than.
- *
- * @param value any number value
- * @param bounds the other value
- * @param treatNanAs return when the value is {@code NaN}.
- * @return {@code -1} value less than limit, {@code 0} value equal limit, {@code 1} value greater than limit.
- */
- private static int numberComparator(Number value, long bounds, OptionalInt treatNanAs) {
- if (isLong(value)) {
- return ((Long) value).compareTo(bounds);
- }
- if (isDouble(value)) {
- Double val = (Double) value;
- OptionalInt infinity = infinityCheck(val, treatNanAs);
- if (infinity.isPresent()) {
- return infinity.getAsInt();
- } else {
- return Double.compare(val, bounds);
- }
- }
- if (isFloat(value)) {
- Float val = (Float) value;
- OptionalInt infinity = infinityCheck(val, treatNanAs);
- if (infinity.isPresent()) {
- return infinity.getAsInt();
- } else {
- return Float.compare(val, bounds);
- }
- }
- if (isBigDecimal(value)) {
- return ((BigDecimal) value).compareTo(BigDecimal.valueOf(bounds));
- }
- if (isBigInteger(value)) {
- return ((BigInteger) value).compareTo(BigInteger.valueOf(bounds));
- }
- return Long.compare(value.longValue(), bounds);
- }
- /**
- * get the sign number of the value.
- *
- * @param value any number value
- * @param treatNanAs return when the value equal infinity.
- * @return {@code -1} the value less than zero, {@code 0} the value equal zero, {@code 1} the value greater than zero.
- */
- private static int signum(Number value, OptionalInt treatNanAs) {
- if (isLong(value)) {
- return Long.signum((Long) value);
- }
- if (value instanceof Integer) {
- return Integer.signum((Integer) value);
- }
- if (isBigDecimal(value)) {
- return ((BigDecimal) value).signum();
- }
- if (isBigInteger(value)) {
- return ((BigInteger) value).signum();
- }
- if (isDouble(value)) {
- Double val = (Double) value;
- OptionalInt infinity = infinityCheck(val, treatNanAs);
- if (infinity.isPresent()) {
- return infinity.getAsInt();
- } else {
- return val.compareTo(0D);
- }
- }
- if (isFloat(value)) {
- Float val = (Float) value;
- OptionalInt infinity = infinityCheck(val, treatNanAs);
- if (infinity.isPresent()) {
- return infinity.getAsInt();
- } else {
- return val.compareTo(0F);
- }
- }
- if (value instanceof Byte) {
- return ((Byte) value).compareTo(BYTE_ZERO);
- }
- if (value instanceof Short) {
- return ((Short) value).compareTo(SHORT_ZERO);
- }
- return Double.compare(value.doubleValue(), 0D);
- }
- /**
- * the implements verify method for validation annotation in {@linkplain javax.validation.constraints}
- */
- private static class VerifyAction {
- private String message;
- private int code;
- private boolean logWrite = true;
- private Object object;
- private String[] fields;
- private VerifyAction(boolean logWrite, Object object, String... fields) {
- this.logWrite = logWrite;
- this.object = object;
- this.fields = fields;
- }
- private VerifyAction(Object object, String... fields) {
- this.object = object;
- this.fields = fields;
- }
- /**
- * new a BigDecimal object with a CharSequence value.
- *
- * @param value any CharSequence value
- * @return a new {@link BigDecimal} object or null when occur any exception.
- */
- private BigDecimal newBigDecimal(CharSequence value) {
- try {
- BigDecimal bd;
- if (value instanceof String) {
- bd = new BigDecimal((String) value);
- } else {
- bd = new BigDecimal(value.toString());
- }
- return bd;
- } catch (Exception e) {
- setIllegalArgMessage("Failed to convert '%s' to a valid BigDecimal. Exception: %s", value, e.getMessage());
- return null;
- }
- }
- /**
- * new a BigDecimal object with a Number value, base on the Specific type of the value.
- *
- * @param value any Number value
- * @return a new {@link BigDecimal} object or null when occur any exception.
- */
- private BigDecimal newBigDecimal(Number value) {
- try {
- BigDecimal bd;
- if (isLong(value)) {
- bd = BigDecimal.valueOf((Long) value);
- } else if (isBigDecimal(value)) {
- bd = ((BigDecimal) value);
- } else if (isBigInteger(value)) {
- bd = new BigDecimal((BigInteger) value);
- } else if (isDouble(value)) {
- bd = BigDecimal.valueOf((Double) value);
- } else if (isFloat(value)) {
- bd = BigDecimal.valueOf((Float) value);
- } else {
- bd = BigDecimal.valueOf(value.doubleValue());
- }
- return bd;
- } catch (Exception e) {
- setIllegalArgMessage("Failed to convert '%s' to a valid BigDecimal. Exception: %s", value, e.getMessage());
- return null;
- }
- }
- /**
- * set the verify message in the ThreadLocal.(code : 1)
- */
- private void setVerifyMessage(String message, Object... values) {
- this.code = 1;
- this.message = format(message, values);
- }
- /**
- * set the illegal argument message in the ThreadLocal.(code : 2)
- */
- private void setIllegalArgMessage(String message, Object... values) {
- this.code = 2;
- this.message = format(message, values);
- }
- /**
- * verify whether the value isn't {@code null}.
- *
- * @param value any object value.
- * @param annotation the {@link NotNull} annotation get from the field.
- * @return if return {@code true} that the value isn't null, otherwise no.
- */
- private boolean verify(Object value, NotNull annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- setVerifyMessage(annotation.message());
- return null != value;
- }
- /**
- * verify whether the value is {@code null}.
- *
- * @param value any object value.
- * @param annotation the {@link Null} annotation get from the field.
- * @return if return {@code true} that the value is null, otherwise no.
- */
- private boolean verify(Object value, Null annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- setVerifyMessage(annotation.message());
- return Objects.isNull(value);
- }
- /**
- * verify whether the value is {@code true}.
- *
- * @param value any object value, but only work for {@link Boolean}
- * @param annotation the {@link AssertTrue} annotation get from the field.
- * @return if return {@code true} that the value is true, otherwise no.
- */
- private boolean verify(Object value, AssertTrue annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- setVerifyMessage(annotation.message());
- if (Objects.isNull(value)) {
- return false;
- }
- if (value instanceof Boolean) {
- return ((Boolean) value);
- } else {
- setIllegalArgMessage("The @AssertTrue only supports Boolean.");
- return false;
- }
- }
- /**
- * verify whether the value is {@code false}.
- *
- * @param value any object value, but only work for {@link Boolean}
- * @param annotation the {@link AssertFalse} annotation get from the field.
- * @return if return {@code true} that the value is false, otherwise no.
- */
- private boolean verify(Object value, AssertFalse annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- setVerifyMessage(annotation.message());
- if (Objects.isNull(value)) {
- return false;
- }
- if (value instanceof Boolean) {
- return !((Boolean) value);
- } else {
- setIllegalArgMessage("The @AssertFalse only supports Boolean.");
- return false;
- }
- }
- /**
- * verify whether the value is less than the bigdecimal maximum value.
- *
- * @param value any object value, but only work for {@link Number} and {@link CharSequence}
- * @param annotation the {@link DecimalMax} annotation get from the field.
- * @return if return {@code true} that the value is less than the bigdecimal maximum, otherwise no.
- */
- private boolean verify(Object value, DecimalMax annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- setVerifyMessage(annotation.message());
- if (Objects.isNull(value)) {
- return false;
- }
- final boolean isNumber = isNumber(value);
- final boolean isCharSequence = isCharSequence(value);
- if (!isNumber && !isCharSequence) {
- setIllegalArgMessage("The @DecimalMax only supports Number & CharSequence.");
- return false;
- }
- final String maxValue = annotation.value();
- if (Objects.isNull(maxValue)) {
- setIllegalArgMessage("The value of @DecimalMax is null, a invalid BigDecimal format.");
- return false;
- }
- final BigDecimal max = newBigDecimal(maxValue);
- if (Objects.isNull(max)) {
- return false;
- }
- final BigDecimal val;
- if (isNumber) {
- val = newBigDecimal((Number) value);
- } else {
- val = newBigDecimal((CharSequence) value);
- }
- if (Objects.isNull(val)) {
- return false;
- }
- final int compare = decimalComparator(value, val, max, GREATER_THAN);
- final boolean inclusive = annotation.inclusive();
- //inclusive ? comparisonResult <= 0 : comparisonResult < 0;
- if (inclusive) {
- return compare <= 0;
- } else {
- return compare < 0;
- }
- }
- /**
- * verify whether the value is greater than the bigdecimal minimum value.
- *
- * @param value any object value, but only work for {@link Number} and {@link CharSequence}
- * @param annotation the {@link DecimalMin} annotation get from the field.
- * @return if return {@code true} that the value is greater than the bigdecimal minimum, otherwise no.
- */
- private boolean verify(Object value, DecimalMin annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- setVerifyMessage(annotation.message());
- if (Objects.isNull(value)) {
- return false;
- }
- final boolean isNumber = isNumber(value);
- final boolean isCharSequence = isCharSequence(value);
- if (!isNumber && !isCharSequence) {
- setIllegalArgMessage("The @DecimalMin only supports Number & CharSequence.");
- return false;
- }
- final String minValue = annotation.value();
- if (Objects.isNull(minValue)) {
- setIllegalArgMessage("The value of @DecimalMin is null, a invalid BigDecimal format.");
- return false;
- }
- final BigDecimal min = newBigDecimal(minValue);
- if (Objects.isNull(min)) {
- return false;
- }
- final BigDecimal val;
- if (isNumber) {
- val = newBigDecimal((Number) value);
- } else {
- val = newBigDecimal((CharSequence) value);
- }
- if (Objects.isNull(val)) {
- return false;
- }
- final int compare = decimalComparator(value, val, min, LESS_THAN);
- final boolean inclusive = annotation.inclusive();
- //inclusive ? comparisonResult >= 0 : comparisonResult > 0;
- if (inclusive) {
- return compare >= 0;
- } else {
- return compare > 0;
- }
- }
- /**
- * verify whether the value isn't null and not empty.
- *
- * @param value any object value,but only work for {@link CharSequence},{@link Collection},{@link Map},{@link Array},{@link Iterator}and {@link Enumeration}
- * @param annotation the {@link NotEmpty} annotation get from the field.
- * @return if return {@code true} that the value isn't empty(with some length or size), otherwise no.
- */
- private boolean verify(Object value, NotEmpty annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- setVerifyMessage(annotation.message());
- if (Objects.isNull(value)) {
- return false;
- }
- final int length = length(value);
- if (-1 == length) {
- setIllegalArgMessage("The @NotEmpty only supports CharSequence & Collection & Map & Array & Iterator & Enumeration.");
- return false;
- }
- // length > 0
- return length > 0;
- }
- /**
- * verify whether the value satisfy the size with maximum and minimun.
- *
- * @param value any object value, but only work for {@link CharSequence},{@link Collection},{@link Map},{@link Array},{@link Iterator}and {@link Enumeration}
- * @param annotation the {@link Size} annotation get from the field.
- * @return if return {@code true} that the value satisfy the size, otherwise no.
- */
- private boolean verify(Object value, Size annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- final int min = annotation.min();
- final int max = annotation.max();
- String message = annotation.message();
- if (notBlank(message)) {
- if (message.contains("{min}")) {
- message = message.replace("{min}", String.valueOf(min));
- }
- if (message.contains("{max}")) {
- message = message.replace("{max}", String.valueOf(max));
- }
- }
- setVerifyMessage(message);
- if (Objects.isNull(value)) {
- return false;
- }
- if (min < 0) {
- setIllegalArgMessage("The min (%s) parameter of @Size cannot be negative.", min);
- return false;
- }
- if (max < 0) {
- setIllegalArgMessage("The max (%s) parameter of @Size cannot be negative.", max);
- return false;
- }
- if (min > max) {
- setIllegalArgMessage("The min (%s) must be less or equals max (%s) of @Size.", min, max);
- return false;
- }
- final int length = length(value);
- if (-1 == length) {
- setIllegalArgMessage("The @Size only supports CharSequence & Collection & Map & Array & Iterator & Enumeration.");
- return false;
- }
- //size >= min && size <= max
- return length >= min && length <= max;
- }
- /**
- * verify that the {@code Number} being validated matches the pattern
- *
- * @param value any object value, but only work for {@link CharSequence} and {@link Number}
- * @param annotation the {@link Digits} annotation get from the field.
- * @return if return {@code true} that the value is matches pattern, otherwise no.
- */
- private boolean verify(Object value, Digits annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- final int maxInteger = annotation.integer();
- final int maxFraction = annotation.fraction();
- String message = annotation.message();
- if (notBlank(message)) {
- if (message.contains("{integer}")) {
- message = message.replace("{integer}", String.valueOf(maxInteger));
- }
- if (message.contains("{fraction}")) {
- message = message.replace("{fraction}", String.valueOf(maxFraction));
- }
- }
- setVerifyMessage(message);
- if (Objects.isNull(value)) {
- return false;
- }
- final boolean isNumber = isNumber(value);
- final boolean isCharSequence = isCharSequence(value);
- if (!isNumber && !isCharSequence) {
- setIllegalArgMessage("The @Digits only supports Number & CharSequence.");
- return false;
- }
- if (maxInteger < 0) {
- setIllegalArgMessage("The length of the integer '%s' part of @Digits cannot be negative.", maxInteger);
- return false;
- }
- if (maxFraction < 0) {
- setIllegalArgMessage("The length of the fraction '%s' part of @Digits cannot be negative.", maxFraction);
- return false;
- }
- BigDecimal val;
- if (isNumber) {
- if (isBigDecimal(value)) {
- val = (BigDecimal) value;
- } else {
- val = newBigDecimal(value.toString());
- if (Objects.isNull(val)) {
- return false;
- }
- val = val.stripTrailingZeros();
- }
- } else {
- val = newBigDecimal((CharSequence) value);
- }
- if (Objects.isNull(val)) {
- return false;
- }
- int integerPart = val.precision() - val.scale();
- int fractionPart = val.scale() < 0 ? 0 : val.scale();
- //maxInteger >= integerPart && maxFraction >= fractionPart
- return maxInteger >= integerPart && maxFraction >= fractionPart;
- }
- /**
- * verify that a character sequence is not {@code null} nor empty after removing any leading or trailing whitespace.
- *
- * @param value any object value, but only work for {@link CharSequence}
- * @param annotation the {@link NotBlank} annotation get from the field.
- * @return if return {@code true} that the value isn't blank, otherwise no.
- */
- private boolean verify(Object value, NotBlank annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- setVerifyMessage(annotation.message());
- if (Objects.isNull(value)) {
- return false;
- }
- if (!isCharSequence(value)) {
- setIllegalArgMessage("The @NotBlank only supports CharSequence.");
- return false;
- }
- return ((CharSequence) value).toString().trim().length() > 0;
- }
- /**
- * verify whether the value is a valid email address.
- *
- * @param value any object value, but only work for {@link CharSequence}
- * @param annotation the {@link Email} annotation get from the field.
- * @return if return {@code true} that the value is a valid email address, otherwise no.
- */
- private boolean verify(Object value, Email annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- setVerifyMessage(annotation.message());
- if (Objects.isNull(value)) {
- return false;
- }
- if (!isCharSequence(value)) {
- setIllegalArgMessage("The @Email only supports CharSequence.");
- return false;
- }
- //@Email need trim
- final String val = ((CharSequence) value).toString().trim();
- if (val.isEmpty()) {
- return false;
- }
- // cannot split email string at @ as it can be a part of quoted local part of email.
- // so we need to split at a position of last @ present in the string:
- int splitPosition = val.lastIndexOf('@');
- if (splitPosition < 0) {
- return false;
- }
- String localPart = val.substring(0, splitPosition);
- String domainPart = val.substring(splitPosition + 1);
- // verify the local part
- if (localPart.length() > MAX_LOCAL_PART_LENGTH) {
- return false;
- }
- if (!LOCAL_PART_PATTERN.matcher(localPart).matches()) {
- return false;
- }
- // verify the domain part
- // if we have a trailing dot the domain part we have an invalid email address.
- // the regular expression match would take care of this, but IDN.toASCII drops the trailing '.'
- if (domainPart.endsWith(".")) {
- return false;
- }
- Matcher matcher = EMAIL_DOMAIN_PATTERN.matcher(domainPart);
- if (!matcher.matches()) {
- return false;
- }
- String ascii;
- try {
- ascii = IDN.toASCII(domainPart);
- } catch (IllegalArgumentException e) {
- setIllegalArgMessage("Failed to convert domain string to ASCII code. Exception: %s", e.getMessage());
- return false;
- }
- if (MAX_DOMAIN_PART_LENGTH < ascii.length()) {
- return false;
- }
- final Pattern.Flag[] flags = annotation.flags();
- final String regexp = annotation.regexp();
- int intFlag = 0;
- for (Pattern.Flag flag : flags) {
- intFlag = intFlag | flag.getValue();
- }
- java.util.regex.Pattern pattern = null;
- // we only apply the regexp if there is one to apply
- if (!".*".equals(regexp) || flags.length > 0) {
- try {
- pattern = java.util.regex.Pattern.compile(regexp, intFlag);
- } catch (PatternSyntaxException e) {
- setIllegalArgMessage("Failed to Compile the regexp and flag for @Email. Exception: %s", e.getMessage());
- return false;
- }
- }
- if (Objects.isNull(pattern)) {
- setIllegalArgMessage("The regexp for @Email is Invalid regular expression.");
- return false;
- }
- return pattern.matcher(val).matches();
- }
- /**
- * verify whether the value is matches the pattern.
- *
- * @param value any object value, but only work for {@link CharSequence}
- * @param annotation the {@link Pattern} annotation get from the field.
- * @return if return {@code true} that the value is mathches the pattern, otherwise no.
- */
- private boolean verify(Object value, Pattern annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- setVerifyMessage(annotation.message());
- if (Objects.isNull(value)) {
- return false;
- }
- if (!isCharSequence(value)) {
- setIllegalArgMessage("The @Pattern only supports CharSequence.");
- return false;
- }
- //@Pattern no trim
- final String val = ((CharSequence) value).toString();
- if (val.isEmpty()) {
- return false;
- }
- final Pattern.Flag[] flags = annotation.flags();
- final String regexp = annotation.regexp();
- int intFlag = 0;
- for (Pattern.Flag flag : flags) {
- intFlag = intFlag | flag.getValue();
- }
- java.util.regex.Pattern pattern;
- try {
- pattern = java.util.regex.Pattern.compile(regexp, intFlag);
- } catch (PatternSyntaxException e) {
- setIllegalArgMessage("Failed to Compile the regexp and flag for @Pattern. Exception: %s", e.getMessage());
- return false;
- }
- if (Objects.isNull(pattern)) {
- setIllegalArgMessage("The regexp for @Pattern is Invalid regular expression.");
- return false;
- }
- return pattern.matcher(val).matches();
- }
- /**
- * verify whether the value less then or equal the maximum value.
- *
- * @param value any object value, but only work for {@link CharSequence} and {@link Number}
- * @param annotation the {@link Max} annotation get from the field.
- * @return if return {@code ture} that the value is less than or equal the maximum, otherwise no.
- */
- private boolean verify(Object value, Max annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- setVerifyMessage(annotation.message());
- if (Objects.isNull(value)) {
- return false;
- }
- final boolean isNumber = isNumber(value);
- final boolean isCharSequence = isCharSequence(value);
- if (!isCharSequence && !isNumber) {
- setIllegalArgMessage("The @Max only supports Number & CharSequence.");
- return false;
- }
- final long max = annotation.value();
- final int compare;
- if (isNumber) {
- compare = numberComparator((Number) value, max, GREATER_THAN);
- } else {
- String v = ((CharSequence) value).toString().trim();
- if (v.isEmpty()) {
- return false;
- }
- BigDecimal val = newBigDecimal(v);
- if (Objects.isNull(val)) {
- return false;
- }
- compare = val.compareTo(BigDecimal.valueOf(max));
- }
- //compare <= 0
- return compare <= 0;
- }
- /**
- * verify whether the value greater then or equal the minimum value.
- *
- * @param value any object value, but only work for {@link CharSequence} and {@link Number}
- * @param annotation the {@link Max} annotation get from the field.
- * @return if return {@code ture} that the value is less than or equal the minimum, otherwise no.
- */
- private boolean verify(Object value, Min annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- setVerifyMessage(annotation.message());
- if (Objects.isNull(value)) {
- return false;
- }
- final boolean isNumber = isNumber(value);
- final boolean isCharSequence = isCharSequence(value);
- if (!isCharSequence && !isNumber) {
- setIllegalArgMessage("The @Min only supports Number & CharSequence.");
- return false;
- }
- final long min = annotation.value();
- final int compare;
- if (isNumber) {
- compare = numberComparator((Number) value, min, LESS_THAN);
- } else {
- String v = ((CharSequence) value).toString().trim();
- if (v.isEmpty()) {
- return false;
- }
- BigDecimal val = newBigDecimal(v);
- if (Objects.isNull(val)) {
- return false;
- }
- compare = val.compareTo(BigDecimal.valueOf(min));
- }
- //compare >= 0
- return compare >= 0;
- }
- /**
- * verify whether the value
- *
- * @param value any object value, but only work for {@link Number}
- * @param annotation the {@link Negative} annotation get from the field.
- * @return
- */
- private boolean verify(Object value, Negative annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- setVerifyMessage(annotation.message());
- if (Objects.isNull(value)) {
- return false;
- }
- if (!isNumber(value)) {
- setIllegalArgMessage("The @Negative only supports Number.");
- return false;
- }
- return signum((Number) value, GREATER_THAN) < 0;
- }
- /**
- * @param value any object value, but only work for {@link Number}
- * @param annotation the {@link NegativeOrZero} annotation get from the field.
- * @return
- */
- private boolean verify(Object value, NegativeOrZero annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- setVerifyMessage(annotation.message());
- if (Objects.isNull(value)) {
- return false;
- }
- if (!isNumber(value)) {
- setIllegalArgMessage("The @NegativeOrZero only supports Number.");
- return false;
- }
- return signum((Number) value, GREATER_THAN) <= 0;
- }
- /**
- * @param value any object value, but only work for {@link Number}
- * @param annotation the {@link Positive} annotation get from the field.
- * @return
- */
- private boolean verify(Object value, Positive annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- setVerifyMessage(annotation.message());
- if (Objects.isNull(value)) {
- return false;
- }
- if (!isNumber(value)) {
- setIllegalArgMessage("The @Positive only supports Number.");
- return false;
- }
- return signum((Number) value, LESS_THAN) > 0;
- }
- /**
- * @param value any object value, but only work for {@link Number}
- * @param annotation the {@link PositiveOrZero} annotation get from the field.
- * @return
- */
- private boolean verify(Object value, PositiveOrZero annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- setVerifyMessage(annotation.message());
- if (Objects.isNull(value)) {
- return false;
- }
- if (!isNumber(value)) {
- setIllegalArgMessage("The @PositiveOrZero only supports Number.");
- return false;
- }
- return signum((Number) value, LESS_THAN) >= 0;
- }
- /**
- * compare the TemporalAccessor value with now , verify whether the value is before or after now.
- *
- * @param value any object value, but only work for {@link TemporalAccessor}, {@link Date} and {@link Calendar}
- * @param isTemporalAccessor whether the value is instance of {@link TemporalAccessor}
- * @param isDate whether the value is instance of {@link Date}
- * @return {@code -1} the value is before now, {@code 0} is now, {@code 1} after now. otherwise {@code -2} not support the type.
- */
- private int dateComparator(Object value, boolean isTemporalAccessor, boolean isDate) {
- Clock clock = systemDefaultClock();
- int compare;
- if (isTemporalAccessor) {
- if (value instanceof Instant) {
- compare = ((Instant) value).compareTo(Instant.now(clock));
- } else if (value instanceof LocalDateTime) {
- compare = ((LocalDateTime) value).compareTo(LocalDateTime.now(clock));
- } else if (value instanceof LocalDate) {
- compare = ((LocalDate) value).compareTo(LocalDate.now(clock));
- } else if (value instanceof LocalTime) {
- compare = ((LocalTime) value).compareTo(LocalTime.now(clock));
- } else if (value instanceof MonthDay) {
- compare = ((MonthDay) value).compareTo(MonthDay.now(clock));
- } else if (value instanceof HijrahDate) {
- compare = ((HijrahDate) value).compareTo(HijrahDate.now(clock));
- } else if (value instanceof JapaneseDate) {
- compare = ((JapaneseDate) value).compareTo(JapaneseDate.now(clock));
- } else if (value instanceof MinguoDate) {
- compare = ((MinguoDate) value).compareTo(MinguoDate.now(clock));
- } else if (value instanceof OffsetDateTime) {
- compare = ((OffsetDateTime) value).compareTo(OffsetDateTime.now(clock));
- } else if (value instanceof OffsetTime) {
- compare = ((OffsetTime) value).compareTo(OffsetTime.now(clock));
- } else if (value instanceof ThaiBuddhistDate) {
- compare = ((ThaiBuddhistDate) value).compareTo(ThaiBuddhistDate.now(clock));
- } else if (value instanceof Year) {
- compare = ((Year) value).compareTo(Year.now(clock));
- } else if (value instanceof YearMonth) {
- compare = ((YearMonth) value).compareTo(YearMonth.now(clock));
- } else if (value instanceof ZonedDateTime) {
- compare = ((ZonedDateTime) value).compareTo(ZonedDateTime.now(clock));
- } else {
- setIllegalArgMessage("The '%s' is not a supported TemporalAccessor class temporarily.", value.getClass().getCanonicalName());
- compare = Integer.MAX_VALUE;
- }
- } else if (isDate) {
- Date val = (Date) value;
- compare = val.toInstant().compareTo(Instant.now(clock));
- } else {
- Calendar val = (Calendar) value;
- compare = val.toInstant().compareTo(Instant.now(clock));
- }
- return compare;
- }
- /**
- * verify whether the value is a future time.
- *
- * @param value any object value, but only work for {@link TemporalAccessor}, {@link Date} and {@link Calendar}
- * @param annotation the {@link Future} annotation get from the field.
- * @return if return {@code true} that the value is a future time, otherwise no.
- */
- private boolean verify(Object value, Future annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- setVerifyMessage(annotation.message());
- if (Objects.isNull(value)) {
- return false;
- }
- final boolean isTemporalAccessor = isTemporalAccessor(value);
- final boolean isDate = isDate(value);
- final boolean isCalendar = isCalendar(value);
- if (!isTemporalAccessor && !isDate && !isCalendar) {
- setIllegalArgMessage("The @Future only supports TemporalAccessor & Calendar & Date.");
- return false;
- }
- final int compare = dateComparator(value, isTemporalAccessor, isDate);
- if (Integer.MAX_VALUE == compare) {
- return false;
- }
- //compare > 0
- return compare > 0;
- }
- /**
- * verify whether the value is a future time or present.
- *
- * @param value any object value, but only work for {@link TemporalAccessor}, {@link Date} and {@link Calendar}
- * @param annotation the {@link FutureOrPresent} annotation get from the field.
- * @return if return {@code true} that the value is a future time or present, otherwise no.
- */
- private boolean verify(Object value, FutureOrPresent annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- setVerifyMessage(annotation.message());
- if (Objects.isNull(value)) {
- return false;
- }
- final boolean isTemporalAccessor = isTemporalAccessor(value);
- final boolean isDate = isDate(value);
- final boolean isCalendar = isCalendar(value);
- if (!isTemporalAccessor && !isDate && !isCalendar) {
- setIllegalArgMessage("The @FutureOrPresent only supports TemporalAccessor & Calendar & Date.");
- return false;
- }
- final int compare = dateComparator(value, isTemporalAccessor, isDate);
- if (Integer.MAX_VALUE == compare) {
- return false;
- }
- //compare >= 0
- return compare >= 0;
- }
- /**
- * verify whether the value is a past time.
- *
- * @param value any object value, but only work for {@link TemporalAccessor}, {@link Date} and {@link Calendar}
- * @param annotation the {@link Past} annotation get from the field.
- * @return if return {@code true} that the value is a past time, otherwise no.
- */
- private boolean verify(Object value, Past annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- setVerifyMessage(annotation.message());
- if (Objects.isNull(value)) {
- return false;
- }
- final boolean isTemporalAccessor = isTemporalAccessor(value);
- final boolean isDate = isDate(value);
- final boolean isCalendar = isCalendar(value);
- if (!isTemporalAccessor && !isDate && !isCalendar) {
- setIllegalArgMessage("The @Past only supports TemporalAccessor & Calendar & Date.");
- return false;
- }
- final int compare = dateComparator(value, isTemporalAccessor, isDate);
- if (Integer.MAX_VALUE == compare) {
- return false;
- }
- //compare < 0
- return compare < 0;
- }
- /**
- * verify whether the value is a future time or present.
- *
- * @param value any object value, but only work for {@link TemporalAccessor}, {@link Date} and {@link Calendar}
- * @param annotation the {@link Future} annotation get from the field.
- * @return if return {@code true} that the value is a past time or present, otherwise no.
- */
- private boolean verify(Object value, PastOrPresent annotation) {
- if (Objects.isNull(annotation)) {
- return true;
- }
- setVerifyMessage(annotation.message());
- if (Objects.isNull(value)) {
- return false;
- }
- final boolean isTemporalAccessor = isTemporalAccessor(value);
- final boolean isDate = isDate(value);
- final boolean isCalendar = isCalendar(value);
- if (!isTemporalAccessor && !isDate && !isCalendar) {
- setIllegalArgMessage("The @PastOrPresent only supports TemporalAccessor & Calendar & Date.");
- return false;
- }
- final int compare = dateComparator(value, isTemporalAccessor, isDate);
- if (Integer.MAX_VALUE == compare) {
- return false;
- }
- //compare <= 0
- return compare <= 0;
- }
- /**
- * verify the fields of the object base on the annotation present on it.
- * if it is not valid that will throw a {@link VerifyException}.
- * or a {@link IllegalArgumentException} when argument is illegal.
- * <p>
- * {@code object} any object value. with some validation annotation in {@code javax.validation.constraints.*}
- * {@code fields} the list of fields to verify. if no, that will verify all fields in the object.
- */
- private void action() {
- isNull(object, "The object to verify must not be null.");
- Field[] verifyFields = filterFields(object, fields);
- for (Field verifyField : verifyFields) {
- //filter the validation annotation
- Annotation[] verifyAnnos = filterAnnotations(verifyField);
- if (isEmpty(verifyAnnos)) continue;
- //get value.
- Object value = obtainFieldValue(object, verifyField);
- for (Annotation verifyAnno : verifyAnnos) {
- //get method
- Method method = lookupMethod(this.getClass(), VerifyMethodName, verifyAnno.annotationType());
- // result.
- boolean invoke = invokeMethod(this, method, value, verifyAnno);
- if (invoke) continue;
- if (logWrite) {
- info(verifyField, value, method, verifyAnno);
- }
- if (1 == code) {
- throw newVerifyException(message);
- } else {
- throw newIllegalArgException(message);
- }
- }
- }
- }
- }
- /**
- * get field by the names
- *
- * @param object the target object
- * @param fields the names of field
- * @return list of field
- */
- private static Field[] filterFields(final Object object, final String... fields) {
- Class<?> objectClass = object.getClass();
- // get fields, if has specify fields, otherwise get all fields on the object.
- if (isEmpty(fields)) {
- return objectClass.getDeclaredFields();
- }
- List<Field> verifyFields = new ArrayList<>();
- for (String field : fields) {
- Field verifyField;
- try {
- verifyField = objectClass.getDeclaredField(field);
- } catch (NoSuchFieldException e) {
- throw newIllegalArgException("No such field '%s' in : %s.", field, objectClass.getCanonicalName());
- }
- verifyFields.add(verifyField);
- }
- //if vaild fields is empty
- if (verifyFields.isEmpty()) {
- throw newIllegalArgException("The specified field names did not resolve any available fields to verify.");
- }
- return verifyFields.toArray(new Field[verifyFields.size()]);
- }
- /**
- * get all validation annotation on the field
- *
- * @param field the target field
- * @return list of validation annotation
- */
- private static Annotation[] filterAnnotations(final Field field) {
- if (!field.isAccessible()) {
- field.setAccessible(true);
- }
- if (FieldAnnotationCache.keySet().contains(field)) {
- return FieldAnnotationCache.get(field);
- }
- //get all annotation of the field
- Annotation[] annotations = field.getDeclaredAnnotations();
- //filter the validation annotation
- if (annotations != null && annotations.length > 0) {
- List<Annotation> verifyAnnos = Arrays.stream(annotations).filter(anno -> ClassMethodCache.keySet().contains(anno.annotationType())).collect(Collectors.toList());
- annotations = verifyAnnos.toArray(new Annotation[verifyAnnos.size()]);
- }
- FieldAnnotationCache.put(field, annotations);
- log.info("Get Declared annotation on field '{}', cache size: {}", field.getName(), FieldAnnotationCache.size());
- return annotations;
- }
- /**
- * get value of the field on the object
- *
- * @param object the target object
- * @param field the field
- * @return the value
- */
- private static Object obtainFieldValue(final Object object, final Field field) {
- final Object value;
- try {
- value = field.get(object);
- } catch (IllegalAccessException e) {
- throw newIllegalArgException("Illegal Access '%s' in %s.", field.getName(), object.getClass().getCanonicalName());
- }
- return value;
- }
- private static Method lookupMethod(final Class<?> target, final String methodName, final Class<?> annotationType) {
- if (ClassMethodCache.keySet().contains(annotationType)) {
- return ClassMethodCache.get(annotationType);
- }
- final Method method;
- try {
- method = target.getDeclaredMethod(methodName, Object.class, annotationType);
- } catch (NoSuchMethodException e) {
- throw newIllegalArgException("No such method [%s(Object,%s)] in %s.", methodName, annotationType, target.getName());
- }
- if (!method.isAccessible()) {
- method.setAccessible(true);
- }
- ClassMethodCache.put(annotationType, method);
- return method;
- }
- /**
- * look up the {@link MethodHandle} for the target verify.
- *
- * @param lookup {@link MethodHandles#lookup()}
- * @param methodName the name of method
- * @param annotationType the return type and args type
- * @return MethodHandle
- */
- private static MethodHandle lookupMethod(final MethodHandles.Lookup lookup, final String methodName, final Class<?> annotationType) {
- if (ClassMethodHandleCache.keySet().contains(annotationType)) {
- return ClassMethodHandleCache.get(annotationType);
- }
- final Class<?> lookupClass = lookup.lookupClass();
- final MethodHandle methodHandle;
- final MethodType methodType = MethodType.methodType(boolean.class, Object.class, annotationType);
- try {
- methodHandle = lookup.findVirtual(lookupClass, methodName, methodType);
- } catch (NoSuchMethodException | IllegalAccessException e) {
- throw newIllegalArgException("No such method [%s(%s)] in %s.", methodName, methodType, lookupClass.getName());
- }
- ClassMethodHandleCache.put(annotationType, methodHandle);
- return methodHandle;
- }
- /**
- * invoke the target methodHandle to verify
- *
- * @param target the target object
- * @param methodHandle the verify methodHandle
- * @param args the list of args
- * @return boolean
- */
- private static boolean invokeMethod(final Object target, final MethodHandle methodHandle, final Object... args) {
- final boolean invoke;
- try {
- invoke = (boolean) methodHandle.bindTo(target).invokeWithArguments(args);
- } catch (Throwable throwable) {
- throw newIllegalArgException("Invoke the target method [%s] failed.", methodHandle);
- }
- return invoke;
- }
- /**
- * invoke the target method to verify.
- *
- * @param target the target object
- * @param method the target method
- * @param value the value
- * @param annotation the annotation
- * @return boolean
- */
- private static boolean invokeMethod(final Object target, final Method method, final Object value, final Annotation annotation) {
- final boolean invoke;
- try {
- invoke = (boolean) method.invoke(target, value, annotation);
- } catch (IllegalAccessException | InvocationTargetException e) {
- throw newIllegalArgException("Invoke the target method [%s(Object,%s)] failed.", method.getName(), annotation.annotationType().getName());
- }
- return invoke;
- }
- /**
- * the format of the {@code info} level log.
- *
- * @param verifyField the field to valid.
- * @param value the value of the field.
- * @param method the method to action
- * @param verifyAnno the validation annotation of the field.
- */
- private static void info(Field verifyField, Object value, Method method, Annotation verifyAnno) {
- log.info("###| FIELD : {}", verifyField);
- log.info("###| FIELD_VALUE : {}", value);
- log.info("###| METHOD : (false) {}(Object,{})", method.getName(), verifyAnno.annotationType().getName());
- }
- /**
- * create a {@link IllegalArgumentException} with the message.
- *
- * @param message the message of exception.
- * @return a {@link IllegalArgumentException}
- */
- private static IllegalArgumentException newIllegalArgException(String message, Object... values) {
- return new IllegalArgumentException(format(message, values));
- }
- /**
- * create a {@link VerifyException} with the message.
- *
- * @param message the message of exception.
- * @return a {@link VerifyException}
- */
- private static VerifyException newVerifyException(String message, Object... values) {
- return new VerifyException(format(message, values));
- }
- /**
- * format the message with some values
- *
- * @param message the message string.
- * @param values some values.
- * @return the message has format if necessary
- */
- private static String format(String message, Object... values) {
- if(message.contains("%s") && null != values && values.length > 0) {
- return String.format(message, values);
- }
- return message;
- }
- /**
- * verify whether the expression is {@code true}.
- *
- * @param object any object.
- * @param message if {@code true} that throw a {@link IllegalArgumentException} with message.
- */
- private static void isNull(Object object, String message) {
- if (null == object) {
- throw newIllegalArgException(message);
- }
- }
- private static void isTrue(boolean expression, String message) {
- if (expression) {
- throw newIllegalArgException(message);
- }
- }
- /**
- * to support {@link SecurityManager}
- *
- * @param action {@link PrivilegedAction}
- * @param <T> the type of return.
- * @return return the result.
- */
- private <T> T run(PrivilegedAction<T> action) {
- return System.getSecurityManager() != null ? AccessController.doPrivileged(action) : action.run();
- }
- }
|