001package org.kuali.common.util.base;
002
003import static com.google.common.base.Preconditions.checkArgument;
004import static org.apache.commons.lang3.StringUtils.isBlank;
005
006import com.google.common.base.Optional;
007
008/**
009 * Strongly mimic's Guava's {@Preconditions} with a sensible default error message for common situations
010 * 
011 * <pre>
012 * Guava:
013 * String foo = checkArgument(!StringUtils.isBlank(foo), &quot;'%s' cannot be blank&quot;);
014 * 
015 * Kuali:
016 * String foo = checkNotBlank(foo, &quot;foo&quot;);
017 * </pre>
018 */
019public class Precondition {
020
021        private static final String NOT_BLANK_MSG = "'%s' cannot be blank";
022        private static final String MIN_MSG = "%s not allowed. '%s' must be greater than or equal to %s";
023
024        /**
025         * Check that a String is not whitespace, empty ("") or null.
026         */
027        public static String checkNotBlank(String arg, String argName) {
028                checkArgument(!isBlank(arg), NOT_BLANK_MSG, argName);
029                return arg;
030        }
031
032        /**
033         * If arg.isPresent(), check that the string it contains is not whitespace, empty ("") or null.
034         */
035        public static Optional<String> checkNotBlank(Optional<String> arg, String argName) {
036                if (arg.isPresent()) {
037                        checkArgument(!isBlank(arg.get()), argName);
038                }
039                return arg;
040        }
041
042        /**
043         * If arg.isPresent(), check that the Integer it contains is greater than or equal to min
044         */
045        public static Optional<Integer> checkMin(Optional<Integer> arg, int min, String argName) {
046                if (arg.isPresent()) {
047                        checkMin(arg.get(), min, argName);
048                }
049                return arg;
050        }
051
052        /**
053         * If arg.isPresent(), check that the Long it contains is greater than or equal to min
054         */
055        public static Optional<Long> checkMin(Optional<Long> arg, long min, String argName) {
056                if (arg.isPresent()) {
057                        checkMin(arg.get(), min, argName);
058                }
059                return arg;
060        }
061
062        /**
063         * Check that arg is greater than or equal to min.
064         */
065        public static int checkMin(int arg, int min, String argName) {
066                checkArgument(arg >= min, MIN_MSG, arg, min, argName);
067                return arg;
068        }
069
070        /**
071         * Check that arg is greater than or equal to min.
072         */
073        public static long checkMin(long arg, long min, String argName) {
074                checkArgument(arg >= min, MIN_MSG, arg, min, argName);
075                return arg;
076        }
077
078}