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      public static long checkContentLength(final EntityDetails entityDetails) {
58          // -1 is a special value,
59          // 0 is allowed as well,
60          // but never more than Integer.MAX_VALUE.
61          return checkRange(entityDetails.getContentLength(), -1, Integer.MAX_VALUE,
62                          "HTTP entity too large to be buffered in memory)");
63      }
64  
65      public static int checkRange(final int value, final int lowInclusive, final int highInclusive,
66                      final String message) {
67          if (value < lowInclusive || value > highInclusive) {
68              throw illegalArgumentException("%s: %d is out of range [%d, %d]", message, value,
69                      lowInclusive, highInclusive);
70          }
71          return value;
72      }
73  
74      public static long checkRange(final long value, final long lowInclusive, final long highInclusive,
75                      final String message) {
76          if (value < lowInclusive || value > highInclusive) {
77              throw illegalArgumentException("%s: %d is out of range [%d, %d]", message, value,
78                      lowInclusive, highInclusive);
79          }
80          return value;
81      }
82  
83      public static <T extends CharSequence> T containsNoBlanks(final T argument, final String name) {
84          notNull(argument, name);
85          if (isEmpty(argument)) {
86              throw illegalArgumentExceptionNotEmpty(name);
87          }
88          if (TextUtils.containsBlanks(argument)) {
89              throw new IllegalArgumentException(name + " must not contain blanks");
90          }
91          return argument;
92      }
93  
94      private static IllegalArgumentException illegalArgumentException(final String format, final Object... args) {
95          return new IllegalArgumentException(String.format(format, args));
96      }
97  
98      private static IllegalArgumentException illegalArgumentExceptionNotEmpty(final String name) {
99          return new IllegalArgumentException(name + " must not be empty");
100     }
101 
102     private static NullPointerException NullPointerException(final String name) {
103         return new NullPointerException(name + " must not be null");
104     }
105 
106     public static <T extends CharSequence> T notBlank(final T argument, final String name) {
107         notNull(argument, name);
108         if (TextUtils.isBlank(argument)) {
109             throw new IllegalArgumentException(name + " must not be blank");
110         }
111         return argument;
112     }
113 
114     public static <T extends CharSequence> T notEmpty(final T argument, final String name) {
115         notNull(argument, name);
116         if (isEmpty(argument)) {
117             throw illegalArgumentExceptionNotEmpty(name);
118         }
119         return argument;
120     }
121 
122     public static <E, T extends Collection<E>> T notEmpty(final T argument, final String name) {
123         notNull(argument, name);
124         if (isEmpty(argument)) {
125             throw illegalArgumentExceptionNotEmpty(name);
126         }
127         return argument;
128     }
129 
130     public static <T> T notEmpty(final T argument, final String name) {
131         notNull(argument, name);
132         if (isEmpty(argument)) {
133             throw illegalArgumentExceptionNotEmpty(name);
134         }
135         return argument;
136     }
137 
138     public static int notNegative(final int n, final String name) {
139         if (n < 0) {
140             throw illegalArgumentException("%s must not be negative: %d", name, n);
141         }
142         return n;
143     }
144 
145     public static long notNegative(final long n, final String name) {
146         if (n < 0) {
147             throw illegalArgumentException("%s must not be negative: %d", name, n);
148         }
149         return n;
150     }
151 
152     /**
153      * <p>Validate that the specified argument is not {@code null};
154      * otherwise throwing an exception with the specified message.
155      *
156      * <pre>Args.notNull(myObject, "The object must not be null");</pre>
157      *
158      * @param <T> the object type
159      * @param argument  the object to check
160      * @param name  the {@link String} exception message if invalid, not null
161      * @return the validated object (never {@code null} for method chaining)
162      * @throws NullPointerException if the object is {@code null}
163      */
164     public static <T> T notNull(final T argument, final String name) {
165         return Objects.requireNonNull(argument, name);
166     }
167 
168     /**
169      * <p>Checks if an Object is empty or null.</p>
170      *
171      * The following types are supported:
172      * <ul>
173      * <li>{@link CharSequence}: Considered empty if its length is zero.</li>
174      * <li>{@code Array}: Considered empty if its length is zero.</li>
175      * <li>{@link Collection}: Considered empty if it has zero elements.</li>
176      * <li>{@link Map}: Considered empty if it has zero key-value mappings.</li>
177      * </ul>
178      *
179      * <pre>
180      * Args.isEmpty(null)             = true
181      * Args.isEmpty("")               = true
182      * Args.isEmpty("ab")             = false
183      * Args.isEmpty(new int[]{})      = true
184      * Args.isEmpty(new int[]{1,2,3}) = false
185      * Args.isEmpty(1234)             = false
186      * </pre>
187      *
188      * @param object  the {@code Object} to test, may be {@code null}
189      * @return {@code true} if the object has a supported type and is empty or null,
190      * {@code false} otherwise
191      * @since 5.1
192      */
193     public static boolean isEmpty(final Object object) {
194         if (object == null) {
195             return true;
196         }
197         if (object instanceof CharSequence) {
198             return ((CharSequence) object).length() == 0;
199         }
200         if (object.getClass().isArray()) {
201             return Array.getLength(object) == 0;
202         }
203         if (object instanceof Collection<?>) {
204             return ((Collection<?>) object).isEmpty();
205         }
206         if (object instanceof Map<?, ?>) {
207             return ((Map<?, ?>) object).isEmpty();
208         }
209         return false;
210     }
211 
212     public static int positive(final int n, final String name) {
213         if (n <= 0) {
214             throw illegalArgumentException("%s must not be negative or zero: %d", name, n);
215         }
216         return n;
217     }
218 
219     public static long positive(final long n, final String name) {
220         if (n <= 0) {
221             throw illegalArgumentException("%s must not be negative or zero: %d", name, n);
222         }
223         return n;
224     }
225 
226     public static <T extends TimeValue> T positive(final T timeValue, final String name) {
227         positive(timeValue.getDuration(), name);
228         return timeValue;
229     }
230 
231     /**
232      * Private constructor so that no instances can be created. This class
233      * contains only static utility methods.
234      */
235     private Args() {
236     }
237 
238 }