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