001/* 002 * Copyright 2021 Global Biodiversity Information Facility (GBIF) 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.gbif.utils; 017 018import javax.annotation.Nullable; 019 020public final class PreconditionUtils { 021 022 private PreconditionUtils() { 023 } 024 025 /** 026 * Ensures the truth of an expression involving the state of the calling instance, but not 027 * involving any parameters to the calling method. 028 * From Guava. 029 * 030 * @param expression a boolean expression 031 * @throws IllegalStateException if {@code expression} is false 032 */ 033 public static void checkState(boolean expression) { 034 if (!expression) { 035 throw new IllegalStateException(); 036 } 037 } 038 039 /** 040 * Ensures the truth of an expression involving the state of the calling instance, but not 041 * involving any parameters to the calling method. 042 * From Guava. 043 * 044 * @param expression a boolean expression 045 * @param errorMessage the exception message to use if the check fails; will be converted to a 046 * string using {@link String#valueOf(Object)} 047 * @throws IllegalStateException if {@code expression} is false 048 */ 049 public static void checkState(boolean expression, @Nullable Object errorMessage) { 050 if (!expression) { 051 throw new IllegalStateException(String.valueOf(errorMessage)); 052 } 053 } 054 055 /** 056 * Ensures the truth of an expression involving one or more parameters to the calling method. 057 * From Guava. 058 * 059 * @param expression a boolean expression 060 * @throws IllegalArgumentException if {@code expression} is false 061 */ 062 public static void checkArgument(boolean expression) { 063 if (!expression) { 064 throw new IllegalArgumentException(); 065 } 066 } 067 068 /** 069 * Ensures the truth of an expression involving one or more parameters to the calling method. 070 * From Guava. 071 * 072 * @param expression a boolean expression 073 * @param errorMessage the exception message to use if the check fails; will be converted to a 074 * string using {@link String#valueOf(Object)} 075 * @throws IllegalArgumentException if {@code expression} is false 076 */ 077 public static void checkArgument(boolean expression, @Nullable Object errorMessage) { 078 if (!expression) { 079 throw new IllegalArgumentException(String.valueOf(errorMessage)); 080 } 081 } 082}