001/*
002 * #%L
003 * HAPI FHIR - Core Library
004 * %%
005 * Copyright (C) 2014 - 2024 Smile CDR, Inc.
006 * %%
007 * Licensed under the Apache License, Version 2.0 (the "License");
008 * you may not use this file except in compliance with the License.
009 * You may obtain a copy of the License at
010 *
011 *      http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 * #L%
019 */
020package ca.uhn.fhir.util;
021
022import ca.uhn.fhir.i18n.Msg;
023import org.apache.commons.lang3.StringUtils;
024
025import java.util.Objects;
026import java.util.Optional;
027
028public class ObjectUtil {
029
030        // hide
031        private ObjectUtil() {}
032
033        /**
034         * @deprecated Just use Objects.equals() instead;
035         */
036        @Deprecated(since = "6.2")
037        public static boolean equals(Object object1, Object object2) {
038                return Objects.equals(object1, object2);
039        }
040
041        public static <T> T requireNonNull(T obj, String message) {
042                if (obj == null) throw new NullPointerException(Msg.code(1776) + message);
043                return obj;
044        }
045
046        public static void requireNotEmpty(String str, String message) {
047                if (StringUtils.isBlank(str)) {
048                        throw new IllegalArgumentException(Msg.code(1777) + message);
049                }
050        }
051
052        /**
053         * Cast the object to the type using Optional.
054         * Useful for streaming with flatMap.
055         * @param theObject any object
056         * @param theClass the class to check instanceof
057         * @return Optional present if theObject is of type theClass
058         */
059        @SuppressWarnings("unchecked")
060        public static <T> Optional<T> castIfInstanceof(Object theObject, Class<T> theClass) {
061                if (theClass.isInstance(theObject)) {
062                        return Optional.of((T) theObject);
063                } else {
064                        return Optional.empty();
065                }
066        }
067}