
org.killbill.commons.utils.Preconditions Maven / Gradle / Ivy
/*
* Copyright 2020-2022 Equinix, Inc
* Copyright 2014-2022 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.commons.utils;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Verbatim copy to guava's Joiner (v.31.0.1). See https://github.com/killbill/killbill/issues/1615
*/
public final class Preconditions {
private static final Logger logger = LoggerFactory.getLogger(Preconditions.class);
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will be converted to a
* string using {@link String#valueOf(Object)}
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(final boolean expression, @CheckForNull final Object errorMessage) {
if (!expression) {
throw new IllegalStateException(String.valueOf(errorMessage));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the check fail. The
* message is formed by replacing each {@code %s} placeholder in the template with an
* argument. These are matched by position - the first {@code %s} gets {@code
* errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in
* square braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message template. Arguments
* are converted to strings using {@link String#valueOf(Object)}.
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(final boolean expression, final String errorMessageTemplate, final Object... errorMessageArgs) {
if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, errorMessageArgs));
}
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @param errorMessageTemplate a template for the exception message should the check fail. The
* message is formed by replacing each {@code %s} placeholder in the template with an
* argument. These are matched by position - the first {@code %s} gets {@code
* errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in
* square braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message template. Arguments
* are converted to strings using {@link String#valueOf(Object)}.
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static T checkNotNull(@CheckForNull final T reference,
final String errorMessageTemplate,
@CheckForNull @Nullable final Object... errorMessageArgs) {
if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, errorMessageArgs));
}
return reference;
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* See {@link #checkState(boolean, String, Object...)} for details.
*/
public static void checkState(final boolean b, final String errorMessageTemplate, @CheckForNull final Object p1) {
if (!b) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1));
}
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static T checkNotNull(final T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @param errorMessage the exception message to use if the check fails; will be converted to a
* string using {@link String#valueOf(Object)}
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static T checkNotNull(@CheckForNull final T reference, @CheckForNull final Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* See {@link #checkNotNull(Object, String, Object...)} for details.
*/
public static T checkNotNull(@CheckForNull final T obj, final String errorMessageTemplate, @CheckForNull final Object p1) {
if (obj == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1));
}
return obj;
}
private static String lenientFormat(@CheckForNull String template, @CheckForNull Object... args) {
template = String.valueOf(template); // null -> "null"
if (args == null) {
args = new Object[] {"(Object[])null"};
} else {
for (int i = 0; i < args.length; i++) {
args[i] = lenientToString(args[i]);
}
}
// start substituting the arguments into the '%s' placeholders
final StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
final int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template, templateStart, placeholderStart);
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template, templateStart, template.length());
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append(']');
}
return builder.toString();
}
private static String lenientToString(@CheckForNull final Object o) {
if (o == null) {
return "null";
}
try {
return o.toString();
} catch (final Exception e) {
final String objectToString = o.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(o));
logger.warn("Exception during lenientFormat for {}, {}", objectToString, e);
return "<" + objectToString + " threw " + e.getClass().getName() + ">";
}
}
/**
* This method is DEPRECATED, to encourage user put message in precondition. See
* this discussion.
*
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* @param expression a boolean expression
* @throws IllegalStateException if {@code expression} is false
*/
@Deprecated
public static void checkState(final boolean expression) {
if (!expression) {
throw new IllegalStateException();
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(final boolean b, final String errorMessageTemplate, final Object p1, final int p2) {
if (!b) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
*
See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(final boolean b, final String errorMessageTemplate,
final Object p1, final Object p2, final Object p3) {
if (!b) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2, p3));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the check fail. The
* message is formed by replacing each {@code %s} placeholder in the template with an
* argument. These are matched by position - the first {@code %s} gets {@code
* errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in
* square braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message template. Arguments
* are converted to strings using {@link String#valueOf(Object)}.
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(final boolean expression, final String errorMessageTemplate, final Object... errorMessageArgs) {
if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, errorMessageArgs));
}
}
}