Objects.java

  1. /**
  2.  *
  3.  * Copyright 2015-2019 Florian Schmaus
  4.  *
  5.  * Licensed under the Apache License, Version 2.0 (the "License");
  6.  * you may not use this file except in compliance with the License.
  7.  * You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.jivesoftware.smack.util;

  18. import java.util.Collection;

  19. public class Objects {

  20.     /**
  21.      * Checks that the specified object reference is not <code>null</code> and throws a customized
  22.      * {@link IllegalArgumentException} if it is.
  23.      * <p>
  24.      * Note that unlike <code>java.util.Objects</code>, this method throws an {@link IllegalArgumentException} instead
  25.      * of an {@link NullPointerException}.
  26.      * </p>
  27.      *
  28.      * @param <T> the type of the reference.
  29.      * @param obj the object reference to check for nullity.
  30.      * @param message detail message to be used in the event that a {@link IllegalArgumentException} is thrown.
  31.      * @return <code>obj</code> if not null.
  32.      * @throws IllegalArgumentException in case <code>obj</code> is <code>null</code>.
  33.      */
  34.     public static <T> T requireNonNull(T obj, String message) throws IllegalArgumentException {
  35.         if (obj == null) {
  36.             if (message == null) {
  37.                 message = "Can not provide null argument";
  38.             }
  39.             throw new IllegalArgumentException(message);
  40.         }
  41.         return obj;
  42.     }

  43.     public static <T> T requireNonNull(T obj) {
  44.         return requireNonNull(obj, null);
  45.     }

  46.     /**
  47.      * Require a collection to be neither null, nor empty.
  48.      *
  49.      * @param collection collection
  50.      * @param message error message
  51.      * @param <T> Collection type
  52.      * @return collection TODO javadoc me please
  53.      */
  54.     public static <T extends Collection<?>> T requireNonNullNorEmpty(T collection, String message) {
  55.         if (requireNonNull(collection).isEmpty()) {
  56.             throw new IllegalArgumentException(message);
  57.         }
  58.         return collection;
  59.     }

  60.     public static boolean equals(Object a, Object b) {
  61.         return a == b || (a != null && a.equals(b));
  62.     }
  63. }