View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.hc.core5.util;
29  
30  import java.lang.reflect.Array;
31  import java.util.Collection;
32  import java.util.Map;
33  import java.util.Objects;
34  
35  import org.apache.hc.core5.http.EntityDetails;
36  
37  public class Args {
38  
39      public static void check(final boolean expression, final String message) {
40          if (!expression) {
41              throw new IllegalArgumentException(message);
42          }
43      }
44  
45      public static void check(final boolean expression, final String message, final Object... args) {
46          if (!expression) {
47              throw new IllegalArgumentException(String.format(message, args));
48          }
49      }
50  
51      public static void check(final boolean expression, final String message, final Object arg) {
52          if (!expression) {
53              throw new IllegalArgumentException(String.format(message, arg));
54          }
55      }
56  
57      /**
58       * @deprecated Use {@link #checkRange(long, long, long, String)}.
59       */
60      @Deprecated
61      public static long checkContentLength(final EntityDetails entityDetails) {
62          // -1 is a special value,
63          // 0 is allowed as well,
64          // but never more than Integer.MAX_VALUE.
65          return checkRange(entityDetails.getContentLength(), -1, Integer.MAX_VALUE,
66                          "HTTP entity too large to be buffered in memory)");
67      }
68  
69      public static int checkRange(final int value, final int lowInclusive, final int highInclusive,
70                      final String message) {
71          if (value < lowInclusive || value > highInclusive) {
72              throw illegalArgumentException("%s: %d is out of range [%d, %d]", message, value,
73                      lowInclusive, highInclusive);
74          }
75          return value;
76      }
77  
78      public static long checkRange(final long value, final long lowInclusive, final long highInclusive,
79                      final String message) {
80          if (value < lowInclusive || value > highInclusive) {
81              throw illegalArgumentException("%s: %d is out of range [%d, %d]", message, value,
82                      lowInclusive, highInclusive);
83          }
84          return value;
85      }
86  
87      public static <T extends CharSequence> T containsNoBlanks(final T argument, final String name) {
88          notNull(argument, name);
89          if (isEmpty(argument)) {
90              throw illegalArgumentExceptionNotEmpty(name);
91          }
92          if (TextUtils.containsBlanks(argument)) {
93              throw new IllegalArgumentException(name + " must not contain blanks");
94          }
95          return argument;
96      }
97  
98      private static IllegalArgumentException illegalArgumentException(final String format, final Object... args) {
99          return new IllegalArgumentException(String.format(format, args));
100     }
101 
102     private static IllegalArgumentException illegalArgumentExceptionNotEmpty(final String name) {
103         return new IllegalArgumentException(name + " must not be empty");
104     }
105 
106     private static NullPointerException NullPointerException(final String name) {
107         return new NullPointerException(name + " must not be null");
108     }
109 
110     public static <T extends CharSequence> T notBlank(final T argument, final String name) {
111         notNull(argument, name);
112         if (TextUtils.isBlank(argument)) {
113             throw new IllegalArgumentException(name + " must not be blank");
114         }
115         return argument;
116     }
117 
118     public static <T extends CharSequence> T notEmpty(final T argument, final String name) {
119         notNull(argument, name);
120         if (isEmpty(argument)) {
121             throw illegalArgumentExceptionNotEmpty(name);
122         }
123         return argument;
124     }
125 
126     public static <E, T extends Collection<E>> T notEmpty(final T argument, final String name) {
127         notNull(argument, name);
128         if (isEmpty(argument)) {
129             throw illegalArgumentExceptionNotEmpty(name);
130         }
131         return argument;
132     }
133 
134     public static <T> T notEmpty(final T argument, final String name) {
135         notNull(argument, name);
136         if (isEmpty(argument)) {
137             throw illegalArgumentExceptionNotEmpty(name);
138         }
139         return argument;
140     }
141 
142     public static int notNegative(final int n, final String name) {
143         if (n < 0) {
144             throw illegalArgumentException("%s must not be negative: %d", name, n);
145         }
146         return n;
147     }
148 
149     public static long notNegative(final long n, final String name) {
150         if (n < 0) {
151             throw illegalArgumentException("%s must not be negative: %d", name, n);
152         }
153         return n;
154     }
155 
156     /**
157      * <p>Validate that the specified argument is not {@code null};
158      * otherwise throwing an exception with the specified message.
159      *
160      * <pre>Args.notNull(myObject, "The object must not be null");</pre>
161      *
162      * @param <T> the object type
163      * @param argument  the object to check
164      * @param name  the {@link String} exception message if invalid, not null
165      * @return the validated object (never {@code null} for method chaining)
166      * @throws NullPointerException if the object is {@code null}
167      */
168     public static <T> T notNull(final T argument, final String name) {
169         return Objects.requireNonNull(argument, name);
170     }
171 
172     /**
173      * <p>Checks if an Object is empty or null.</p>
174      *
175      * The following types are supported:
176      * <ul>
177      * <li>{@link CharSequence}: Considered empty if its length is zero.</li>
178      * <li>{@code Array}: Considered empty if its length is zero.</li>
179      * <li>{@link Collection}: Considered empty if it has zero elements.</li>
180      * <li>{@link Map}: Considered empty if it has zero key-value mappings.</li>
181      * </ul>
182      *
183      * <pre>
184      * Args.isEmpty(null)             = true
185      * Args.isEmpty("")               = true
186      * Args.isEmpty("ab")             = false
187      * Args.isEmpty(new int[]{})      = true
188      * Args.isEmpty(new int[]{1,2,3}) = false
189      * Args.isEmpty(1234)             = false
190      * </pre>
191      *
192      * @param object  the {@code Object} to test, may be {@code null}
193      * @return {@code true} if the object has a supported type and is empty or null,
194      * {@code false} otherwise
195      * @since 5.1
196      */
197     public static boolean isEmpty(final Object object) {
198         if (object == null) {
199             return true;
200         }
201         if (object instanceof CharSequence) {
202             return ((CharSequence) object).length() == 0;
203         }
204         if (object.getClass().isArray()) {
205             return Array.getLength(object) == 0;
206         }
207         if (object instanceof Collection<?>) {
208             return ((Collection<?>) object).isEmpty();
209         }
210         if (object instanceof Map<?, ?>) {
211             return ((Map<?, ?>) object).isEmpty();
212         }
213         return false;
214     }
215 
216     public static int positive(final int n, final String name) {
217         if (n <= 0) {
218             throw illegalArgumentException("%s must not be negative or zero: %d", name, n);
219         }
220         return n;
221     }
222 
223     public static long positive(final long n, final String name) {
224         if (n <= 0) {
225             throw illegalArgumentException("%s must not be negative or zero: %d", name, n);
226         }
227         return n;
228     }
229 
230     public static <T extends TimeValue> T positive(final T timeValue, final String name) {
231         positive(timeValue.getDuration(), name);
232         return timeValue;
233     }
234 
235     /**
236      * Private constructor so that no instances can be created. This class
237      * contains only static utility methods.
238      */
239     private Args() {
240     }
241 
242 }