mirror of
https://github.com/Eaglercraft-Archive/Eaglercraftx-1.8.8-src.git
synced 2025-06-28 02:48:14 -05:00
Update #0 - First Release
This commit is contained in:
377
sources/main/java/org/apache/commons/lang3/AnnotationUtils.java
Normal file
377
sources/main/java/org/apache/commons/lang3/AnnotationUtils.java
Normal file
@ -0,0 +1,377 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||
import org.apache.commons.lang3.builder.ToStringStyle;
|
||||
|
||||
import net.lax1dude.eaglercraft.v1_8.HString;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Helper methods for working with {@link Annotation} instances.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This class contains various utility methods that make working with
|
||||
* annotations simpler.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* {@link Annotation} instances are always proxy objects; unfortunately dynamic
|
||||
* proxies cannot be depended upon to know how to implement certain methods in
|
||||
* the same manner as would be done by "natural" {@link Annotation}s. The
|
||||
* methods presented in this class can be used to avoid that possibility. It is
|
||||
* of course also possible for dynamic proxies to actually delegate their e.g.
|
||||
* {@link Annotation#equals(Object)}/{@link Annotation#hashCode()}/
|
||||
* {@link Annotation#toString()} implementations to {@link AnnotationUtils}.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* #ThreadSafe#
|
||||
* </p>
|
||||
*
|
||||
* @since 3.0
|
||||
*/
|
||||
public class AnnotationUtils {
|
||||
|
||||
/**
|
||||
* A style that prints annotations as recommended.
|
||||
*/
|
||||
private static final ToStringStyle TO_STRING_STYLE = new ToStringStyle() {
|
||||
/** Serialization version */
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
{
|
||||
setDefaultFullDetail(true);
|
||||
setArrayContentDetail(true);
|
||||
setUseClassName(true);
|
||||
setUseShortClassName(true);
|
||||
setUseIdentityHashCode(false);
|
||||
setContentStart("(");
|
||||
setContentEnd(")");
|
||||
setFieldSeparator(", ");
|
||||
setArrayStart("[");
|
||||
setArrayEnd("]");
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
protected String getShortClassName(final Class<?> cls) {
|
||||
return cls.getSimpleName();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
protected void appendDetail(final StringBuffer buffer, final String fieldName, Object value) {
|
||||
if (value instanceof Annotation) {
|
||||
value = AnnotationUtils.toString((Annotation) value);
|
||||
}
|
||||
super.appendDetail(buffer, fieldName, value);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* {@code AnnotationUtils} instances should NOT be constructed in standard
|
||||
* programming. Instead, the class should be used statically.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This constructor is public to permit tools that require a JavaBean instance
|
||||
* to operate.
|
||||
* </p>
|
||||
*/
|
||||
public AnnotationUtils() {
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Checks if two annotations are equal using the criteria for equality presented
|
||||
* in the {@link Annotation#equals(Object)} API docs.
|
||||
* </p>
|
||||
*
|
||||
* @param a1 the first Annotation to compare, {@code null} returns {@code false}
|
||||
* unless both are {@code null}
|
||||
* @param a2 the second Annotation to compare, {@code null} returns
|
||||
* {@code false} unless both are {@code null}
|
||||
* @return {@code true} if the two annotations are {@code equal} or both
|
||||
* {@code null}
|
||||
*/
|
||||
public static boolean equals(final Annotation a1, final Annotation a2) {
|
||||
if (a1 == a2) {
|
||||
return true;
|
||||
}
|
||||
if (a1 == null || a2 == null) {
|
||||
return false;
|
||||
}
|
||||
final Class<? extends Annotation> type1 = a1.annotationType();
|
||||
final Class<? extends Annotation> type2 = a2.annotationType();
|
||||
Validate.notNull(type1, "Annotation %s with null annotationType()", a1);
|
||||
Validate.notNull(type2, "Annotation %s with null annotationType()", a2);
|
||||
if (!type1.equals(type2)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
for (final Method m : type1.getDeclaredMethods()) {
|
||||
if (m.getParameterTypes().length == 0 && isValidAnnotationMemberType(m.getReturnType())) {
|
||||
final Object v1 = m.invoke(a1);
|
||||
final Object v2 = m.invoke(a2);
|
||||
if (!memberEquals(m.getReturnType(), v1, v2)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (final IllegalAccessException | InvocationTargetException ex) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Generate a hash code for the given annotation using the algorithm presented
|
||||
* in the {@link Annotation#hashCode()} API docs.
|
||||
* </p>
|
||||
*
|
||||
* @param a the Annotation for a hash code calculation is desired, not
|
||||
* {@code null}
|
||||
* @return the calculated hash code
|
||||
* @throws RuntimeException if an {@code Exception} is encountered during
|
||||
* annotation member access
|
||||
* @throws IllegalStateException if an annotation method invocation returns
|
||||
* {@code null}
|
||||
*/
|
||||
public static int hashCode(final Annotation a) {
|
||||
int result = 0;
|
||||
final Class<? extends Annotation> type = a.annotationType();
|
||||
for (final Method m : type.getDeclaredMethods()) {
|
||||
try {
|
||||
final Object value = m.invoke(a);
|
||||
if (value == null) {
|
||||
throw new IllegalStateException(HString.format("Annotation method %s returned null", m));
|
||||
}
|
||||
result += hashMember(m.getName(), value);
|
||||
} catch (final RuntimeException ex) {
|
||||
throw ex;
|
||||
} catch (final Exception ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Generate a string representation of an Annotation, as suggested by
|
||||
* {@link Annotation#toString()}.
|
||||
* </p>
|
||||
*
|
||||
* @param a the annotation of which a string representation is desired
|
||||
* @return the standard string representation of an annotation, not {@code null}
|
||||
*/
|
||||
public static String toString(final Annotation a) {
|
||||
final ToStringBuilder builder = new ToStringBuilder(a, TO_STRING_STYLE);
|
||||
for (final Method m : a.annotationType().getDeclaredMethods()) {
|
||||
if (m.getParameterTypes().length > 0) {
|
||||
continue; // wtf?
|
||||
}
|
||||
try {
|
||||
builder.append(m.getName(), m.invoke(a));
|
||||
} catch (final RuntimeException ex) {
|
||||
throw ex;
|
||||
} catch (final Exception ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Checks if the specified type is permitted as an annotation member.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The Java language specification only permits certain types to be used in
|
||||
* annotations. These include {@link String}, {@link Class}, primitive types,
|
||||
* {@link Annotation}, {@link Enum}, and single-dimensional arrays of these
|
||||
* types.
|
||||
* </p>
|
||||
*
|
||||
* @param type the type to check, {@code null}
|
||||
* @return {@code true} if the type is a valid type to use in an annotation
|
||||
*/
|
||||
public static boolean isValidAnnotationMemberType(Class<?> type) {
|
||||
if (type == null) {
|
||||
return false;
|
||||
}
|
||||
if (type.isArray()) {
|
||||
type = type.getComponentType();
|
||||
}
|
||||
return type.isPrimitive() || type.isEnum() || type.isAnnotation() || String.class.equals(type)
|
||||
|| Class.class.equals(type);
|
||||
}
|
||||
|
||||
// besides modularity, this has the advantage of autoboxing primitives:
|
||||
/**
|
||||
* Helper method for generating a hash code for a member of an annotation.
|
||||
*
|
||||
* @param name the name of the member
|
||||
* @param value the value of the member
|
||||
* @return a hash code for this member
|
||||
*/
|
||||
private static int hashMember(final String name, final Object value) {
|
||||
final int part1 = name.hashCode() * 127;
|
||||
if (value.getClass().isArray()) {
|
||||
return part1 ^ arrayMemberHash(value.getClass().getComponentType(), value);
|
||||
}
|
||||
if (value instanceof Annotation) {
|
||||
return part1 ^ hashCode((Annotation) value);
|
||||
}
|
||||
return part1 ^ value.hashCode();
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method for checking whether two objects of the given type are equal.
|
||||
* This method is used to compare the parameters of two annotation instances.
|
||||
*
|
||||
* @param type the type of the objects to be compared
|
||||
* @param o1 the first object
|
||||
* @param o2 the second object
|
||||
* @return a flag whether these objects are equal
|
||||
*/
|
||||
private static boolean memberEquals(final Class<?> type, final Object o1, final Object o2) {
|
||||
if (o1 == o2) {
|
||||
return true;
|
||||
}
|
||||
if (o1 == null || o2 == null) {
|
||||
return false;
|
||||
}
|
||||
if (type.isArray()) {
|
||||
return arrayMemberEquals(type.getComponentType(), o1, o2);
|
||||
}
|
||||
if (type.isAnnotation()) {
|
||||
return equals((Annotation) o1, (Annotation) o2);
|
||||
}
|
||||
return o1.equals(o2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method for comparing two objects of an array type.
|
||||
*
|
||||
* @param componentType the component type of the array
|
||||
* @param o1 the first object
|
||||
* @param o2 the second object
|
||||
* @return a flag whether these objects are equal
|
||||
*/
|
||||
private static boolean arrayMemberEquals(final Class<?> componentType, final Object o1, final Object o2) {
|
||||
if (componentType.isAnnotation()) {
|
||||
return annotationArrayMemberEquals((Annotation[]) o1, (Annotation[]) o2);
|
||||
}
|
||||
if (componentType.equals(Byte.TYPE)) {
|
||||
return Arrays.equals((byte[]) o1, (byte[]) o2);
|
||||
}
|
||||
if (componentType.equals(Short.TYPE)) {
|
||||
return Arrays.equals((short[]) o1, (short[]) o2);
|
||||
}
|
||||
if (componentType.equals(Integer.TYPE)) {
|
||||
return Arrays.equals((int[]) o1, (int[]) o2);
|
||||
}
|
||||
if (componentType.equals(Character.TYPE)) {
|
||||
return Arrays.equals((char[]) o1, (char[]) o2);
|
||||
}
|
||||
if (componentType.equals(Long.TYPE)) {
|
||||
return Arrays.equals((long[]) o1, (long[]) o2);
|
||||
}
|
||||
if (componentType.equals(Float.TYPE)) {
|
||||
return Arrays.equals((float[]) o1, (float[]) o2);
|
||||
}
|
||||
if (componentType.equals(Double.TYPE)) {
|
||||
return Arrays.equals((double[]) o1, (double[]) o2);
|
||||
}
|
||||
if (componentType.equals(Boolean.TYPE)) {
|
||||
return Arrays.equals((boolean[]) o1, (boolean[]) o2);
|
||||
}
|
||||
return Arrays.equals((Object[]) o1, (Object[]) o2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method for comparing two arrays of annotations.
|
||||
*
|
||||
* @param a1 the first array
|
||||
* @param a2 the second array
|
||||
* @return a flag whether these arrays are equal
|
||||
*/
|
||||
private static boolean annotationArrayMemberEquals(final Annotation[] a1, final Annotation[] a2) {
|
||||
if (a1.length != a2.length) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < a1.length; i++) {
|
||||
if (!equals(a1[i], a2[i])) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method for generating a hash code for an array.
|
||||
*
|
||||
* @param componentType the component type of the array
|
||||
* @param o the array
|
||||
* @return a hash code for the specified array
|
||||
*/
|
||||
private static int arrayMemberHash(final Class<?> componentType, final Object o) {
|
||||
if (componentType.equals(Byte.TYPE)) {
|
||||
return Arrays.hashCode((byte[]) o);
|
||||
}
|
||||
if (componentType.equals(Short.TYPE)) {
|
||||
return Arrays.hashCode((short[]) o);
|
||||
}
|
||||
if (componentType.equals(Integer.TYPE)) {
|
||||
return Arrays.hashCode((int[]) o);
|
||||
}
|
||||
if (componentType.equals(Character.TYPE)) {
|
||||
return Arrays.hashCode((char[]) o);
|
||||
}
|
||||
if (componentType.equals(Long.TYPE)) {
|
||||
return Arrays.hashCode((long[]) o);
|
||||
}
|
||||
if (componentType.equals(Float.TYPE)) {
|
||||
return Arrays.hashCode((float[]) o);
|
||||
}
|
||||
if (componentType.equals(Double.TYPE)) {
|
||||
return Arrays.hashCode((double[]) o);
|
||||
}
|
||||
if (componentType.equals(Boolean.TYPE)) {
|
||||
return Arrays.hashCode((boolean[]) o);
|
||||
}
|
||||
return Arrays.hashCode((Object[]) o);
|
||||
}
|
||||
}
|
135
sources/main/java/org/apache/commons/lang3/ArchUtils.java
Normal file
135
sources/main/java/org/apache/commons/lang3/ArchUtils.java
Normal file
@ -0,0 +1,135 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.apache.commons.lang3.arch.Processor;
|
||||
|
||||
/**
|
||||
* An utility class for the os.arch System Property. The class defines methods
|
||||
* for identifying the architecture of the current JVM.
|
||||
* <p>
|
||||
* Important: The os.arch System Property returns the architecture used by the
|
||||
* JVM not of the operating system.
|
||||
* </p>
|
||||
*
|
||||
* @since 3.6
|
||||
*/
|
||||
public class ArchUtils {
|
||||
|
||||
private static final Map<String, Processor> ARCH_TO_PROCESSOR;
|
||||
|
||||
static {
|
||||
ARCH_TO_PROCESSOR = new HashMap<>();
|
||||
init();
|
||||
}
|
||||
|
||||
private static void init() {
|
||||
init_X86_32Bit();
|
||||
init_X86_64Bit();
|
||||
init_IA64_32Bit();
|
||||
init_IA64_64Bit();
|
||||
init_PPC_32Bit();
|
||||
init_PPC_64Bit();
|
||||
}
|
||||
|
||||
private static void init_X86_32Bit() {
|
||||
final Processor processor = new Processor(Processor.Arch.BIT_32, Processor.Type.X86);
|
||||
addProcessors(processor, "x86", "i386", "i486", "i586", "i686", "pentium");
|
||||
}
|
||||
|
||||
private static void init_X86_64Bit() {
|
||||
final Processor processor = new Processor(Processor.Arch.BIT_64, Processor.Type.X86);
|
||||
addProcessors(processor, "x86_64", "amd64", "em64t", "universal");
|
||||
}
|
||||
|
||||
private static void init_IA64_32Bit() {
|
||||
final Processor processor = new Processor(Processor.Arch.BIT_32, Processor.Type.IA_64);
|
||||
addProcessors(processor, "ia64_32", "ia64n");
|
||||
}
|
||||
|
||||
private static void init_IA64_64Bit() {
|
||||
final Processor processor = new Processor(Processor.Arch.BIT_64, Processor.Type.IA_64);
|
||||
addProcessors(processor, "ia64", "ia64w");
|
||||
}
|
||||
|
||||
private static void init_PPC_32Bit() {
|
||||
final Processor processor = new Processor(Processor.Arch.BIT_32, Processor.Type.PPC);
|
||||
addProcessors(processor, "ppc", "power", "powerpc", "power_pc", "power_rs");
|
||||
}
|
||||
|
||||
private static void init_PPC_64Bit() {
|
||||
final Processor processor = new Processor(Processor.Arch.BIT_64, Processor.Type.PPC);
|
||||
addProcessors(processor, "ppc64", "power64", "powerpc64", "power_pc64", "power_rs64");
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the given {@link Processor} with the given key {@link String} to the
|
||||
* map.
|
||||
*
|
||||
* @param key The key as {@link String}.
|
||||
* @param processor The {@link Processor} to add.
|
||||
* @throws IllegalStateException If the key already exists.
|
||||
*/
|
||||
private static void addProcessor(final String key, final Processor processor) {
|
||||
if (ARCH_TO_PROCESSOR.containsKey(key)) {
|
||||
throw new IllegalStateException("Key " + key + " already exists in processor map");
|
||||
}
|
||||
ARCH_TO_PROCESSOR.put(key, processor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the given {@link Processor} with the given keys to the map.
|
||||
*
|
||||
* @param keys The keys.
|
||||
* @param processor The {@link Processor} to add.
|
||||
* @throws IllegalStateException If the key already exists.
|
||||
*/
|
||||
private static void addProcessors(final Processor processor, final String... keys) {
|
||||
Stream.of(keys).forEach(e -> addProcessor(e, processor));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a {@link Processor} object of the current JVM.
|
||||
*
|
||||
* <p>
|
||||
* Important: The os.arch System Property returns the architecture used by the
|
||||
* JVM not of the operating system.
|
||||
* </p>
|
||||
*
|
||||
* @return A {@link Processor} when supported, else {@code null}.
|
||||
*/
|
||||
public static Processor getProcessor() {
|
||||
return getProcessor(SystemUtils.OS_ARCH);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a {@link Processor} object the given value {@link String}. The
|
||||
* {@link String} must be like a value returned by the os.arch System Property.
|
||||
*
|
||||
* @param value A {@link String} like a value returned by the os.arch System
|
||||
* Property.
|
||||
* @return A {@link Processor} when it exists, else {@code null}.
|
||||
*/
|
||||
public static Processor getProcessor(final String value) {
|
||||
return ARCH_TO_PROCESSOR.get(value);
|
||||
}
|
||||
|
||||
}
|
142
sources/main/java/org/apache/commons/lang3/ArraySorter.java
Normal file
142
sources/main/java/org/apache/commons/lang3/ArraySorter.java
Normal file
@ -0,0 +1,142 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
|
||||
/**
|
||||
* Sorts and returns arrays in the fluent style.
|
||||
*
|
||||
* @since 3.12.0
|
||||
*/
|
||||
public class ArraySorter {
|
||||
|
||||
/**
|
||||
* Sorts and returns the given array.
|
||||
*
|
||||
* @param array the array to sort.
|
||||
* @return the given array.
|
||||
* @see Arrays#sort(byte[])
|
||||
*/
|
||||
public static byte[] sort(final byte[] array) {
|
||||
Arrays.sort(array);
|
||||
return array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts and returns the given array.
|
||||
*
|
||||
* @param array the array to sort.
|
||||
* @return the given array.
|
||||
* @see Arrays#sort(char[])
|
||||
*/
|
||||
public static char[] sort(final char[] array) {
|
||||
Arrays.sort(array);
|
||||
return array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts and returns the given array.
|
||||
*
|
||||
* @param array the array to sort.
|
||||
* @return the given array.
|
||||
* @see Arrays#sort(double[])
|
||||
*/
|
||||
public static double[] sort(final double[] array) {
|
||||
Arrays.sort(array);
|
||||
return array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts and returns the given array.
|
||||
*
|
||||
* @param array the array to sort.
|
||||
* @return the given array.
|
||||
* @see Arrays#sort(float[])
|
||||
*/
|
||||
public static float[] sort(final float[] array) {
|
||||
Arrays.sort(array);
|
||||
return array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts and returns the given array.
|
||||
*
|
||||
* @param array the array to sort.
|
||||
* @return the given array.
|
||||
* @see Arrays#sort(int[])
|
||||
*/
|
||||
public static int[] sort(final int[] array) {
|
||||
Arrays.sort(array);
|
||||
return array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts and returns the given array.
|
||||
*
|
||||
* @param array the array to sort.
|
||||
* @return the given array.
|
||||
* @see Arrays#sort(long[])
|
||||
*/
|
||||
public static long[] sort(final long[] array) {
|
||||
Arrays.sort(array);
|
||||
return array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts and returns the given array.
|
||||
*
|
||||
* @param array the array to sort.
|
||||
* @return the given array.
|
||||
* @see Arrays#sort(short[])
|
||||
*/
|
||||
public static short[] sort(final short[] array) {
|
||||
Arrays.sort(array);
|
||||
return array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts and returns the given array.
|
||||
*
|
||||
* @param <T> the array type.
|
||||
* @param array the array to sort.
|
||||
* @return the given array.
|
||||
* @see Arrays#sort(Object[])
|
||||
*/
|
||||
public static <T> T[] sort(final T[] array) {
|
||||
Arrays.sort(array);
|
||||
return array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts and returns the given array.
|
||||
*
|
||||
* @param <T> the array type.
|
||||
* @param array the array to sort.
|
||||
* @param comparator the comparator to determine the order of the array. A
|
||||
* {@code null} value uses the elements' {@link Comparable
|
||||
* natural ordering}.
|
||||
* @return the given array.
|
||||
* @see Arrays#sort(Object[])
|
||||
*/
|
||||
public static <T> T[] sort(final T[] array, final Comparator<? super T> comparator) {
|
||||
Arrays.sort(array, comparator);
|
||||
return array;
|
||||
}
|
||||
|
||||
}
|
344
sources/main/java/org/apache/commons/lang3/BitField.java
Normal file
344
sources/main/java/org/apache/commons/lang3/BitField.java
Normal file
@ -0,0 +1,344 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Supports operations on bit-mapped fields. Instances of this class can be used
|
||||
* to store a flag or data within an {@code int}, {@code short} or {@code byte}.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Each {@code BitField} is constructed with a mask value, which indicates the
|
||||
* bits that will be used to store and retrieve the data for that field. For
|
||||
* instance, the mask {@code 0xFF} indicates the least-significant byte should
|
||||
* be used to store the data.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* As an example, consider a car painting machine that accepts paint
|
||||
* instructions as integers. Bit fields can be used to encode this:
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* // blue, green and red are 1 byte values (0-255) stored in the three least
|
||||
* // significant bytes
|
||||
* BitField blue = new BitField(0xFF);
|
||||
* BitField green = new BitField(0xFF00);
|
||||
* BitField red = new BitField(0xFF0000);
|
||||
*
|
||||
* // anyColor is a flag triggered if any color is used
|
||||
* BitField anyColor = new BitField(0xFFFFFF);
|
||||
*
|
||||
* // isMetallic is a single bit flag
|
||||
* BitField isMetallic = new BitField(0x1000000);
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* Using these {@code BitField} instances, a paint instruction can be encoded
|
||||
* into an integer:
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* int paintInstruction = 0;
|
||||
* paintInstruction = red.setValue(paintInstruction, 35);
|
||||
* paintInstruction = green.setValue(paintInstruction, 100);
|
||||
* paintInstruction = blue.setValue(paintInstruction, 255);
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* Flags and data can be retrieved from the integer:
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* // Prints true if red, green or blue is non-zero
|
||||
* System.out.println(anyColor.isSet(paintInstruction)); // prints true
|
||||
*
|
||||
* // Prints value of red, green and blue
|
||||
* System.out.println(red.getValue(paintInstruction)); // prints 35
|
||||
* System.out.println(green.getValue(paintInstruction)); // prints 100
|
||||
* System.out.println(blue.getValue(paintInstruction)); // prints 255
|
||||
*
|
||||
* // Prints true if isMetallic was set
|
||||
* System.out.println(isMetallic.isSet(paintInstruction)); // prints false
|
||||
* </pre>
|
||||
*
|
||||
* @since 2.0
|
||||
*/
|
||||
public class BitField {
|
||||
|
||||
private final int _mask;
|
||||
private final int _shift_count;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a BitField instance.
|
||||
* </p>
|
||||
*
|
||||
* @param mask the mask specifying which bits apply to this BitField. Bits that
|
||||
* are set in this mask are the bits that this BitField operates on
|
||||
*/
|
||||
public BitField(final int mask) {
|
||||
_mask = mask;
|
||||
_shift_count = mask == 0 ? 0 : Integer.numberOfTrailingZeros(mask);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Obtains the value for the specified BitField, appropriately shifted right.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Many users of a BitField will want to treat the specified bits as an int
|
||||
* value, and will not want to be aware that the value is stored as a BitField
|
||||
* (and so shifted left so many bits).
|
||||
* </p>
|
||||
*
|
||||
* @see #setValue(int,int)
|
||||
* @param holder the int data containing the bits we're interested in
|
||||
* @return the selected bits, shifted right appropriately
|
||||
*/
|
||||
public int getValue(final int holder) {
|
||||
return getRawValue(holder) >> _shift_count;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Obtains the value for the specified BitField, appropriately shifted right, as
|
||||
* a short.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Many users of a BitField will want to treat the specified bits as an int
|
||||
* value, and will not want to be aware that the value is stored as a BitField
|
||||
* (and so shifted left so many bits).
|
||||
* </p>
|
||||
*
|
||||
* @see #setShortValue(short,short)
|
||||
* @param holder the short data containing the bits we're interested in
|
||||
* @return the selected bits, shifted right appropriately
|
||||
*/
|
||||
public short getShortValue(final short holder) {
|
||||
return (short) getValue(holder);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Obtains the value for the specified BitField, unshifted.
|
||||
* </p>
|
||||
*
|
||||
* @param holder the int data containing the bits we're interested in
|
||||
* @return the selected bits
|
||||
*/
|
||||
public int getRawValue(final int holder) {
|
||||
return holder & _mask;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Obtains the value for the specified BitField, unshifted.
|
||||
* </p>
|
||||
*
|
||||
* @param holder the short data containing the bits we're interested in
|
||||
* @return the selected bits
|
||||
*/
|
||||
public short getShortRawValue(final short holder) {
|
||||
return (short) getRawValue(holder);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Returns whether the field is set or not.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This is most commonly used for a single-bit field, which is often used to
|
||||
* represent a boolean value; the results of using it for a multi-bit field is
|
||||
* to determine whether *any* of its bits are set.
|
||||
* </p>
|
||||
*
|
||||
* @param holder the int data containing the bits we're interested in
|
||||
* @return {@code true} if any of the bits are set, else {@code false}
|
||||
*/
|
||||
public boolean isSet(final int holder) {
|
||||
return (holder & _mask) != 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Returns whether all of the bits are set or not.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This is a stricter test than {@link #isSet(int)}, in that all of the bits in
|
||||
* a multi-bit set must be set for this method to return {@code true}.
|
||||
* </p>
|
||||
*
|
||||
* @param holder the int data containing the bits we're interested in
|
||||
* @return {@code true} if all of the bits are set, else {@code false}
|
||||
*/
|
||||
public boolean isAllSet(final int holder) {
|
||||
return (holder & _mask) == _mask;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Replaces the bits with new values.
|
||||
* </p>
|
||||
*
|
||||
* @see #getValue(int)
|
||||
* @param holder the int data containing the bits we're interested in
|
||||
* @param value the new value for the specified bits
|
||||
* @return the value of holder with the bits from the value parameter replacing
|
||||
* the old bits
|
||||
*/
|
||||
public int setValue(final int holder, final int value) {
|
||||
return (holder & ~_mask) | ((value << _shift_count) & _mask);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Replaces the bits with new values.
|
||||
* </p>
|
||||
*
|
||||
* @see #getShortValue(short)
|
||||
* @param holder the short data containing the bits we're interested in
|
||||
* @param value the new value for the specified bits
|
||||
* @return the value of holder with the bits from the value parameter replacing
|
||||
* the old bits
|
||||
*/
|
||||
public short setShortValue(final short holder, final short value) {
|
||||
return (short) setValue(holder, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Clears the bits.
|
||||
* </p>
|
||||
*
|
||||
* @param holder the int data containing the bits we're interested in
|
||||
* @return the value of holder with the specified bits cleared (set to
|
||||
* {@code 0})
|
||||
*/
|
||||
public int clear(final int holder) {
|
||||
return holder & ~_mask;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Clears the bits.
|
||||
* </p>
|
||||
*
|
||||
* @param holder the short data containing the bits we're interested in
|
||||
* @return the value of holder with the specified bits cleared (set to
|
||||
* {@code 0})
|
||||
*/
|
||||
public short clearShort(final short holder) {
|
||||
return (short) clear(holder);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Clears the bits.
|
||||
* </p>
|
||||
*
|
||||
* @param holder the byte data containing the bits we're interested in
|
||||
*
|
||||
* @return the value of holder with the specified bits cleared (set to
|
||||
* {@code 0})
|
||||
*/
|
||||
public byte clearByte(final byte holder) {
|
||||
return (byte) clear(holder);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Sets the bits.
|
||||
* </p>
|
||||
*
|
||||
* @param holder the int data containing the bits we're interested in
|
||||
* @return the value of holder with the specified bits set to {@code 1}
|
||||
*/
|
||||
public int set(final int holder) {
|
||||
return holder | _mask;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Sets the bits.
|
||||
* </p>
|
||||
*
|
||||
* @param holder the short data containing the bits we're interested in
|
||||
* @return the value of holder with the specified bits set to {@code 1}
|
||||
*/
|
||||
public short setShort(final short holder) {
|
||||
return (short) set(holder);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Sets the bits.
|
||||
* </p>
|
||||
*
|
||||
* @param holder the byte data containing the bits we're interested in
|
||||
*
|
||||
* @return the value of holder with the specified bits set to {@code 1}
|
||||
*/
|
||||
public byte setByte(final byte holder) {
|
||||
return (byte) set(holder);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Sets a boolean BitField.
|
||||
* </p>
|
||||
*
|
||||
* @param holder the int data containing the bits we're interested in
|
||||
* @param flag indicating whether to set or clear the bits
|
||||
* @return the value of holder with the specified bits set or cleared
|
||||
*/
|
||||
public int setBoolean(final int holder, final boolean flag) {
|
||||
return flag ? set(holder) : clear(holder);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Sets a boolean BitField.
|
||||
* </p>
|
||||
*
|
||||
* @param holder the short data containing the bits we're interested in
|
||||
* @param flag indicating whether to set or clear the bits
|
||||
* @return the value of holder with the specified bits set or cleared
|
||||
*/
|
||||
public short setShortBoolean(final short holder, final boolean flag) {
|
||||
return flag ? setShort(holder) : clearShort(holder);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Sets a boolean BitField.
|
||||
* </p>
|
||||
*
|
||||
* @param holder the byte data containing the bits we're interested in
|
||||
* @param flag indicating whether to set or clear the bits
|
||||
* @return the value of holder with the specified bits set or cleared
|
||||
*/
|
||||
public byte setByteBoolean(final byte holder, final boolean flag) {
|
||||
return flag ? setByte(holder) : clearByte(holder);
|
||||
}
|
||||
|
||||
}
|
1167
sources/main/java/org/apache/commons/lang3/BooleanUtils.java
Normal file
1167
sources/main/java/org/apache/commons/lang3/BooleanUtils.java
Normal file
File diff suppressed because it is too large
Load Diff
159
sources/main/java/org/apache/commons/lang3/CharEncoding.java
Normal file
159
sources/main/java/org/apache/commons/lang3/CharEncoding.java
Normal file
@ -0,0 +1,159 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.IllegalCharsetNameException;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Character encoding names required of every implementation of the Java
|
||||
* platform.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* According to <a href=
|
||||
* "http://docs.oracle.com/javase/1.3/docs/api/java/lang/package-summary.html#charenc">JRE
|
||||
* character encoding names</a>:
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* <cite>Every implementation of the Java platform is required to support the
|
||||
* following character encodings. Consult the release documentation for your
|
||||
* implementation to see if any other encodings are supported. </cite>
|
||||
* </p>
|
||||
*
|
||||
* @see <a href=
|
||||
* "http://docs.oracle.com/javase/6/docs/technotes/guides/intl/encoding.doc.html">JRE
|
||||
* character encoding names</a>
|
||||
* @since 2.1
|
||||
* @deprecated Java 7 introduced {@link java.nio.charset.StandardCharsets},
|
||||
* which defines these constants as {@link Charset} objects. Use
|
||||
* {@link Charset#name()} to get the string values provided in this
|
||||
* class. This class will be removed in a future release.
|
||||
*/
|
||||
@Deprecated
|
||||
public class CharEncoding {
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* ISO Latin Alphabet #1, also known as ISO-LATIN-1.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Every implementation of the Java platform is required to support this
|
||||
* character encoding.
|
||||
* </p>
|
||||
*/
|
||||
public static final String ISO_8859_1 = "ISO-8859-1";
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Seven-bit ASCII, also known as ISO646-US, also known as the Basic Latin block
|
||||
* of the Unicode character set.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Every implementation of the Java platform is required to support this
|
||||
* character encoding.
|
||||
* </p>
|
||||
*/
|
||||
public static final String US_ASCII = "US-ASCII";
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Sixteen-bit Unicode Transformation Format, byte order specified by a
|
||||
* mandatory initial byte-order mark (either order accepted on input, big-endian
|
||||
* used on output).
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Every implementation of the Java platform is required to support this
|
||||
* character encoding.
|
||||
* </p>
|
||||
*/
|
||||
public static final String UTF_16 = "UTF-16";
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Sixteen-bit Unicode Transformation Format, big-endian byte order.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Every implementation of the Java platform is required to support this
|
||||
* character encoding.
|
||||
* </p>
|
||||
*/
|
||||
public static final String UTF_16BE = "UTF-16BE";
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Sixteen-bit Unicode Transformation Format, little-endian byte order.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Every implementation of the Java platform is required to support this
|
||||
* character encoding.
|
||||
* </p>
|
||||
*/
|
||||
public static final String UTF_16LE = "UTF-16LE";
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Eight-bit Unicode Transformation Format.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Every implementation of the Java platform is required to support this
|
||||
* character encoding.
|
||||
* </p>
|
||||
*/
|
||||
public static final String UTF_8 = "UTF-8";
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Returns whether the named charset is supported.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This is similar to <a href=
|
||||
* "http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html#isSupported%28java.lang.String%29">
|
||||
* java.nio.charset.Charset.isSupported(String)</a> but handles more formats
|
||||
* </p>
|
||||
*
|
||||
* @param name the name of the requested charset; may be either a canonical name
|
||||
* or an alias, null returns false
|
||||
* @return {@code true} if the charset is available in the current Java virtual
|
||||
* machine
|
||||
* @deprecated Please use {@link Charset#isSupported(String)} instead, although
|
||||
* be aware that {@code null} values are not accepted by that method
|
||||
* and an {@link IllegalCharsetNameException} may be thrown.
|
||||
*/
|
||||
@Deprecated
|
||||
public static boolean isSupported(final String name) {
|
||||
if (name == null) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return Charset.isSupported(name);
|
||||
} catch (final IllegalCharsetNameException ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
421
sources/main/java/org/apache/commons/lang3/CharRange.java
Normal file
421
sources/main/java/org/apache/commons/lang3/CharRange.java
Normal file
@ -0,0 +1,421 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Iterator;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* A contiguous range of characters, optionally negated.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Instances are immutable.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* #ThreadSafe#
|
||||
* </p>
|
||||
*
|
||||
* @since 1.0
|
||||
*/
|
||||
// TODO: This is no longer public and will be removed later as CharSet is moved
|
||||
// to depend on Range.
|
||||
final class CharRange implements Iterable<Character>, Serializable {
|
||||
|
||||
/**
|
||||
* Required for serialization support. Lang version 2.0.
|
||||
*
|
||||
* @see java.io.Serializable
|
||||
*/
|
||||
private static final long serialVersionUID = 8270183163158333422L;
|
||||
|
||||
/** The first character, inclusive, in the range. */
|
||||
private final char start;
|
||||
/** The last character, inclusive, in the range. */
|
||||
private final char end;
|
||||
/** True if the range is everything except the characters specified. */
|
||||
private final boolean negated;
|
||||
|
||||
/** Cached toString. */
|
||||
private transient String iToString;
|
||||
|
||||
/** Empty array. */
|
||||
static final CharRange[] EMPTY_ARRAY = new CharRange[0];
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Constructs a {@code CharRange} over a set of characters, optionally negating
|
||||
* the range.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* A negated range includes everything except that defined by the start and end
|
||||
* characters.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* If start and end are in the wrong order, they are reversed. Thus {@code a-e}
|
||||
* is the same as {@code e-a}.
|
||||
* </p>
|
||||
*
|
||||
* @param start first character, inclusive, in this range
|
||||
* @param end last character, inclusive, in this range
|
||||
* @param negated true to express everything except the range
|
||||
*/
|
||||
private CharRange(char start, char end, final boolean negated) {
|
||||
if (start > end) {
|
||||
final char temp = start;
|
||||
start = end;
|
||||
end = temp;
|
||||
}
|
||||
|
||||
this.start = start;
|
||||
this.end = end;
|
||||
this.negated = negated;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Constructs a {@code CharRange} over a single character.
|
||||
* </p>
|
||||
*
|
||||
* @param ch only character in this range
|
||||
* @return the new CharRange object
|
||||
* @since 2.5
|
||||
*/
|
||||
public static CharRange is(final char ch) {
|
||||
return new CharRange(ch, ch, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Constructs a negated {@code CharRange} over a single character.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* A negated range includes everything except that defined by the single
|
||||
* character.
|
||||
* </p>
|
||||
*
|
||||
* @param ch only character in this range
|
||||
* @return the new CharRange object
|
||||
* @since 2.5
|
||||
*/
|
||||
public static CharRange isNot(final char ch) {
|
||||
return new CharRange(ch, ch, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Constructs a {@code CharRange} over a set of characters.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* If start and end are in the wrong order, they are reversed. Thus {@code a-e}
|
||||
* is the same as {@code e-a}.
|
||||
* </p>
|
||||
*
|
||||
* @param start first character, inclusive, in this range
|
||||
* @param end last character, inclusive, in this range
|
||||
* @return the new CharRange object
|
||||
* @since 2.5
|
||||
*/
|
||||
public static CharRange isIn(final char start, final char end) {
|
||||
return new CharRange(start, end, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Constructs a negated {@code CharRange} over a set of characters.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* A negated range includes everything except that defined by the start and end
|
||||
* characters.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* If start and end are in the wrong order, they are reversed. Thus {@code a-e}
|
||||
* is the same as {@code e-a}.
|
||||
* </p>
|
||||
*
|
||||
* @param start first character, inclusive, in this range
|
||||
* @param end last character, inclusive, in this range
|
||||
* @return the new CharRange object
|
||||
* @since 2.5
|
||||
*/
|
||||
public static CharRange isNotIn(final char start, final char end) {
|
||||
return new CharRange(start, end, true);
|
||||
}
|
||||
|
||||
// Accessors
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Gets the start character for this character range.
|
||||
* </p>
|
||||
*
|
||||
* @return the start char (inclusive)
|
||||
*/
|
||||
public char getStart() {
|
||||
return this.start;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets the end character for this character range.
|
||||
* </p>
|
||||
*
|
||||
* @return the end char (inclusive)
|
||||
*/
|
||||
public char getEnd() {
|
||||
return this.end;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Is this {@code CharRange} negated.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* A negated range includes everything except that defined by the start and end
|
||||
* characters.
|
||||
* </p>
|
||||
*
|
||||
* @return {@code true} if negated
|
||||
*/
|
||||
public boolean isNegated() {
|
||||
return negated;
|
||||
}
|
||||
|
||||
// Contains
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Is the character specified contained in this range.
|
||||
* </p>
|
||||
*
|
||||
* @param ch the character to check
|
||||
* @return {@code true} if this range contains the input character
|
||||
*/
|
||||
public boolean contains(final char ch) {
|
||||
return (ch >= start && ch <= end) != negated;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Are all the characters of the passed in range contained in this range.
|
||||
* </p>
|
||||
*
|
||||
* @param range the range to check against
|
||||
* @return {@code true} if this range entirely contains the input range
|
||||
* @throws IllegalArgumentException if {@code null} input
|
||||
*/
|
||||
public boolean contains(final CharRange range) {
|
||||
Validate.notNull(range, "range");
|
||||
if (negated) {
|
||||
if (range.negated) {
|
||||
return start >= range.start && end <= range.end;
|
||||
}
|
||||
return range.end < start || range.start > end;
|
||||
}
|
||||
if (range.negated) {
|
||||
return start == 0 && end == Character.MAX_VALUE;
|
||||
}
|
||||
return start <= range.start && end >= range.end;
|
||||
}
|
||||
|
||||
// Basics
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Compares two CharRange objects, returning true if they represent exactly the
|
||||
* same range of characters defined in the same way.
|
||||
* </p>
|
||||
*
|
||||
* @param obj the object to compare to
|
||||
* @return true if equal
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (obj == this) {
|
||||
return true;
|
||||
}
|
||||
if (!(obj instanceof CharRange)) {
|
||||
return false;
|
||||
}
|
||||
final CharRange other = (CharRange) obj;
|
||||
return start == other.start && end == other.end && negated == other.negated;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets a hashCode compatible with the equals method.
|
||||
* </p>
|
||||
*
|
||||
* @return a suitable hashCode
|
||||
*/
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return 83 + start + 7 * end + (negated ? 1 : 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets a string representation of the character range.
|
||||
* </p>
|
||||
*
|
||||
* @return string representation of this range
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
if (iToString == null) {
|
||||
final StringBuilder buf = new StringBuilder(4);
|
||||
if (isNegated()) {
|
||||
buf.append('^');
|
||||
}
|
||||
buf.append(start);
|
||||
if (start != end) {
|
||||
buf.append('-');
|
||||
buf.append(end);
|
||||
}
|
||||
iToString = buf.toString();
|
||||
}
|
||||
return iToString;
|
||||
}
|
||||
|
||||
// Expansions
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Returns an iterator which can be used to walk through the characters
|
||||
* described by this range.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* #NotThreadSafe# the iterator is not thread-safe
|
||||
* </p>
|
||||
*
|
||||
* @return an iterator to the chars represented by this range
|
||||
* @since 2.5
|
||||
*/
|
||||
@Override
|
||||
public Iterator<Character> iterator() {
|
||||
return new CharacterIterator(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Character {@link Iterator}.
|
||||
* <p>
|
||||
* #NotThreadSafe#
|
||||
* </p>
|
||||
*/
|
||||
private static class CharacterIterator implements Iterator<Character> {
|
||||
/** The current character */
|
||||
private char current;
|
||||
|
||||
private final CharRange range;
|
||||
private boolean hasNext;
|
||||
|
||||
/**
|
||||
* Constructs a new iterator for the character range.
|
||||
*
|
||||
* @param r The character range
|
||||
*/
|
||||
private CharacterIterator(final CharRange r) {
|
||||
range = r;
|
||||
hasNext = true;
|
||||
|
||||
if (range.negated) {
|
||||
if (range.start == 0) {
|
||||
if (range.end == Character.MAX_VALUE) {
|
||||
// This range is an empty set
|
||||
hasNext = false;
|
||||
} else {
|
||||
current = (char) (range.end + 1);
|
||||
}
|
||||
} else {
|
||||
current = 0;
|
||||
}
|
||||
} else {
|
||||
current = range.start;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the next character in the range.
|
||||
*/
|
||||
private void prepareNext() {
|
||||
if (range.negated) {
|
||||
if (current == Character.MAX_VALUE) {
|
||||
hasNext = false;
|
||||
} else if (current + 1 == range.start) {
|
||||
if (range.end == Character.MAX_VALUE) {
|
||||
hasNext = false;
|
||||
} else {
|
||||
current = (char) (range.end + 1);
|
||||
}
|
||||
} else {
|
||||
current = (char) (current + 1);
|
||||
}
|
||||
} else if (current < range.end) {
|
||||
current = (char) (current + 1);
|
||||
} else {
|
||||
hasNext = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Has the iterator not reached the end character yet?
|
||||
*
|
||||
* @return {@code true} if the iterator has yet to reach the character date
|
||||
*/
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return hasNext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the next character in the iteration
|
||||
*
|
||||
* @return {@code Character} for the next character
|
||||
*/
|
||||
@Override
|
||||
public Character next() {
|
||||
if (!hasNext) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
final char cur = current;
|
||||
prepareNext();
|
||||
return Character.valueOf(cur);
|
||||
}
|
||||
|
||||
/**
|
||||
* Always throws UnsupportedOperationException.
|
||||
*
|
||||
* @throws UnsupportedOperationException Always thrown.
|
||||
* @see java.util.Iterator#remove()
|
||||
*/
|
||||
@Override
|
||||
public void remove() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,402 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Operations on {@link CharSequence} that are {@code null} safe.
|
||||
* </p>
|
||||
*
|
||||
* @see CharSequence
|
||||
* @since 3.0
|
||||
*/
|
||||
public class CharSequenceUtils {
|
||||
|
||||
private static final int NOT_FOUND = -1;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* {@code CharSequenceUtils} instances should NOT be constructed in standard
|
||||
* programming.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This constructor is public to permit tools that require a JavaBean instance
|
||||
* to operate.
|
||||
* </p>
|
||||
*/
|
||||
public CharSequenceUtils() {
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Returns a new {@code CharSequence} that is a subsequence of this sequence
|
||||
* starting with the {@code char} value at the specified index.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This provides the {@code CharSequence} equivalent to
|
||||
* {@link String#substring(int)}. The length (in {@code char}) of the returned
|
||||
* sequence is {@code length() - start}, so if {@code start == end} then an
|
||||
* empty sequence is returned.
|
||||
* </p>
|
||||
*
|
||||
* @param cs the specified subsequence, null returns null
|
||||
* @param start the start index, inclusive, valid
|
||||
* @return a new subsequence, may be null
|
||||
* @throws IndexOutOfBoundsException if {@code start} is negative or if
|
||||
* {@code start} is greater than
|
||||
* {@code length()}
|
||||
*/
|
||||
public static CharSequence subSequence(final CharSequence cs, final int start) {
|
||||
return cs == null ? null : cs.subSequence(start, cs.length());
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Returns the index within {@code cs} of the first occurrence of the specified
|
||||
* character, starting the search at the specified index.
|
||||
* <p>
|
||||
* If a character with value {@code searchChar} occurs in the character sequence
|
||||
* represented by the {@code cs} object at an index no smaller than
|
||||
* {@code start}, then the index of the first such occurrence is returned. For
|
||||
* values of {@code searchChar} in the range from 0 to 0xFFFF (inclusive), this
|
||||
* is the smallest value <i>k</i> such that: <blockquote>
|
||||
*
|
||||
* <pre>
|
||||
* (this.charAt(<i>k</i>) == searchChar) && (<i>k</i> >= start)
|
||||
* </pre>
|
||||
*
|
||||
* </blockquote> is true. For other values of {@code searchChar}, it is the
|
||||
* smallest value <i>k</i> such that: <blockquote>
|
||||
*
|
||||
* <pre>
|
||||
* (this.codePointAt(<i>k</i>) == searchChar) && (<i>k</i> >= start)
|
||||
* </pre>
|
||||
*
|
||||
* </blockquote> is true. In either case, if no such character occurs inm
|
||||
* {@code cs} at or after position {@code start}, then {@code -1} is returned.
|
||||
*
|
||||
* <p>
|
||||
* There is no restriction on the value of {@code start}. If it is negative, it
|
||||
* has the same effect as if it were zero: the entire {@code CharSequence} may
|
||||
* be searched. If it is greater than the length of {@code cs}, it has the same
|
||||
* effect as if it were equal to the length of {@code cs}: {@code -1} is
|
||||
* returned.
|
||||
*
|
||||
* <p>
|
||||
* All indices are specified in {@code char} values (Unicode code units).
|
||||
*
|
||||
* @param cs the {@code CharSequence} to be processed, not null
|
||||
* @param searchChar the char to be searched for
|
||||
* @param start the start index, negative starts at the string start
|
||||
* @return the index where the search char was found, -1 if not found
|
||||
* @since 3.6 updated to behave more like {@code String}
|
||||
*/
|
||||
static int indexOf(final CharSequence cs, final int searchChar, int start) {
|
||||
if (cs instanceof String) {
|
||||
return ((String) cs).indexOf(searchChar, start);
|
||||
}
|
||||
final int sz = cs.length();
|
||||
if (start < 0) {
|
||||
start = 0;
|
||||
}
|
||||
if (searchChar < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
|
||||
for (int i = start; i < sz; i++) {
|
||||
if (cs.charAt(i) == searchChar) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return NOT_FOUND;
|
||||
}
|
||||
// supplementary characters (LANG1300)
|
||||
if (searchChar <= Character.MAX_CODE_POINT) {
|
||||
final char[] chars = Character.toChars(searchChar);
|
||||
for (int i = start; i < sz - 1; i++) {
|
||||
final char high = cs.charAt(i);
|
||||
final char low = cs.charAt(i + 1);
|
||||
if (high == chars[0] && low == chars[1]) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
return NOT_FOUND;
|
||||
}
|
||||
|
||||
/**
|
||||
* Used by the indexOf(CharSequence methods) as a green implementation of
|
||||
* indexOf.
|
||||
*
|
||||
* @param cs the {@code CharSequence} to be processed
|
||||
* @param searchChar the {@code CharSequence} to be searched for
|
||||
* @param start the start index
|
||||
* @return the index where the search sequence was found
|
||||
*/
|
||||
static int indexOf(final CharSequence cs, final CharSequence searchChar, final int start) {
|
||||
if (cs instanceof String) {
|
||||
return ((String) cs).indexOf(searchChar.toString(), start);
|
||||
} else if (cs instanceof StringBuilder) {
|
||||
return ((StringBuilder) cs).indexOf(searchChar.toString(), start);
|
||||
} else if (cs instanceof StringBuffer) {
|
||||
return ((StringBuffer) cs).indexOf(searchChar.toString(), start);
|
||||
}
|
||||
return cs.toString().indexOf(searchChar.toString(), start);
|
||||
// if (cs instanceof String && searchChar instanceof String) {
|
||||
// // TODO: Do we assume searchChar is usually relatively small;
|
||||
// // If so then calling toString() on it is better than reverting to
|
||||
// // the green implementation in the else block
|
||||
// return ((String) cs).indexOf((String) searchChar, start);
|
||||
// } else {
|
||||
// // TODO: Implement rather than convert to String
|
||||
// return cs.toString().indexOf(searchChar.toString(), start);
|
||||
// }
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the index within {@code cs} of the last occurrence of the specified
|
||||
* character, searching backward starting at the specified index. For values of
|
||||
* {@code searchChar} in the range from 0 to 0xFFFF (inclusive), the index
|
||||
* returned is the largest value <i>k</i> such that: <blockquote>
|
||||
*
|
||||
* <pre>
|
||||
* (this.charAt(<i>k</i>) == searchChar) && (<i>k</i> <= start)
|
||||
* </pre>
|
||||
*
|
||||
* </blockquote> is true. For other values of {@code searchChar}, it is the
|
||||
* largest value <i>k</i> such that: <blockquote>
|
||||
*
|
||||
* <pre>
|
||||
* (this.codePointAt(<i>k</i>) == searchChar) && (<i>k</i> <= start)
|
||||
* </pre>
|
||||
*
|
||||
* </blockquote> is true. In either case, if no such character occurs in
|
||||
* {@code cs} at or before position {@code start}, then {@code -1} is returned.
|
||||
*
|
||||
* <p>
|
||||
* All indices are specified in {@code char} values (Unicode code units).
|
||||
*
|
||||
* @param cs the {@code CharSequence} to be processed
|
||||
* @param searchChar the char to be searched for
|
||||
* @param start the start index, negative returns -1, beyond length starts
|
||||
* at end
|
||||
* @return the index where the search char was found, -1 if not found
|
||||
* @since 3.6 updated to behave more like {@code String}
|
||||
*/
|
||||
static int lastIndexOf(final CharSequence cs, final int searchChar, int start) {
|
||||
if (cs instanceof String) {
|
||||
return ((String) cs).lastIndexOf(searchChar, start);
|
||||
}
|
||||
final int sz = cs.length();
|
||||
if (start < 0) {
|
||||
return NOT_FOUND;
|
||||
}
|
||||
if (start >= sz) {
|
||||
start = sz - 1;
|
||||
}
|
||||
if (searchChar < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
|
||||
for (int i = start; i >= 0; --i) {
|
||||
if (cs.charAt(i) == searchChar) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return NOT_FOUND;
|
||||
}
|
||||
// supplementary characters (LANG1300)
|
||||
// NOTE - we must do a forward traversal for this to avoid duplicating code
|
||||
// points
|
||||
if (searchChar <= Character.MAX_CODE_POINT) {
|
||||
final char[] chars = Character.toChars(searchChar);
|
||||
// make sure it's not the last index
|
||||
if (start == sz - 1) {
|
||||
return NOT_FOUND;
|
||||
}
|
||||
for (int i = start; i >= 0; i--) {
|
||||
final char high = cs.charAt(i);
|
||||
final char low = cs.charAt(i + 1);
|
||||
if (chars[0] == high && chars[1] == low) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
return NOT_FOUND;
|
||||
}
|
||||
|
||||
static final int TO_STRING_LIMIT = 16;
|
||||
|
||||
/**
|
||||
* Used by the lastIndexOf(CharSequence methods) as a green implementation of
|
||||
* lastIndexOf
|
||||
*
|
||||
* @param cs the {@code CharSequence} to be processed
|
||||
* @param searchChar the {@code CharSequence} to find
|
||||
* @param start the start index
|
||||
* @return the index where the search sequence was found
|
||||
*/
|
||||
static int lastIndexOf(final CharSequence cs, final CharSequence searchChar, int start) {
|
||||
if (searchChar == null || cs == null) {
|
||||
return NOT_FOUND;
|
||||
}
|
||||
if (searchChar instanceof String) {
|
||||
if (cs instanceof String) {
|
||||
return ((String) cs).lastIndexOf((String) searchChar, start);
|
||||
} else if (cs instanceof StringBuilder) {
|
||||
return ((StringBuilder) cs).lastIndexOf((String) searchChar, start);
|
||||
} else if (cs instanceof StringBuffer) {
|
||||
return ((StringBuffer) cs).lastIndexOf((String) searchChar, start);
|
||||
}
|
||||
}
|
||||
|
||||
final int len1 = cs.length();
|
||||
final int len2 = searchChar.length();
|
||||
|
||||
if (start > len1) {
|
||||
start = len1;
|
||||
}
|
||||
|
||||
if (start < 0 || len2 < 0 || len2 > len1) {
|
||||
return NOT_FOUND;
|
||||
}
|
||||
|
||||
if (len2 == 0) {
|
||||
return start;
|
||||
}
|
||||
|
||||
if (len2 <= TO_STRING_LIMIT) {
|
||||
if (cs instanceof String) {
|
||||
return ((String) cs).lastIndexOf(searchChar.toString(), start);
|
||||
} else if (cs instanceof StringBuilder) {
|
||||
return ((StringBuilder) cs).lastIndexOf(searchChar.toString(), start);
|
||||
} else if (cs instanceof StringBuffer) {
|
||||
return ((StringBuffer) cs).lastIndexOf(searchChar.toString(), start);
|
||||
}
|
||||
}
|
||||
|
||||
if (start + len2 > len1) {
|
||||
start = len1 - len2;
|
||||
}
|
||||
|
||||
final char char0 = searchChar.charAt(0);
|
||||
|
||||
int i = start;
|
||||
while (true) {
|
||||
while (cs.charAt(i) != char0) {
|
||||
i--;
|
||||
if (i < 0) {
|
||||
return NOT_FOUND;
|
||||
}
|
||||
}
|
||||
if (checkLaterThan1(cs, searchChar, len2, i)) {
|
||||
return i;
|
||||
}
|
||||
i--;
|
||||
if (i < 0) {
|
||||
return NOT_FOUND;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean checkLaterThan1(final CharSequence cs, final CharSequence searchChar, final int len2,
|
||||
final int start1) {
|
||||
for (int i = 1, j = len2 - 1; i <= j; i++, j--) {
|
||||
if (cs.charAt(start1 + i) != searchChar.charAt(i) || cs.charAt(start1 + j) != searchChar.charAt(j)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given CharSequence to a char[].
|
||||
*
|
||||
* @param source the {@code CharSequence} to be processed.
|
||||
* @return the resulting char array, never null.
|
||||
* @since 3.11
|
||||
*/
|
||||
public static char[] toCharArray(final CharSequence source) {
|
||||
final int len = StringUtils.length(source);
|
||||
if (len == 0) {
|
||||
return new char[0];
|
||||
}
|
||||
if (source instanceof String) {
|
||||
return ((String) source).toCharArray();
|
||||
}
|
||||
final char[] array = new char[len];
|
||||
for (int i = 0; i < len; i++) {
|
||||
array[i] = source.charAt(i);
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Green implementation of regionMatches.
|
||||
*
|
||||
* @param cs the {@code CharSequence} to be processed
|
||||
* @param ignoreCase whether or not to be case insensitive
|
||||
* @param thisStart the index to start on the {@code cs} CharSequence
|
||||
* @param substring the {@code CharSequence} to be looked for
|
||||
* @param start the index to start on the {@code substring} CharSequence
|
||||
* @param length character length of the region
|
||||
* @return whether the region matched
|
||||
*/
|
||||
static boolean regionMatches(final CharSequence cs, final boolean ignoreCase, final int thisStart,
|
||||
final CharSequence substring, final int start, final int length) {
|
||||
if (cs instanceof String && substring instanceof String) {
|
||||
return ((String) cs).regionMatches(ignoreCase, thisStart, (String) substring, start, length);
|
||||
}
|
||||
int index1 = thisStart;
|
||||
int index2 = start;
|
||||
int tmpLen = length;
|
||||
|
||||
// Extract these first so we detect NPEs the same as the java.lang.String
|
||||
// version
|
||||
final int srcLen = cs.length() - thisStart;
|
||||
final int otherLen = substring.length() - start;
|
||||
|
||||
// Check for invalid parameters
|
||||
if (thisStart < 0 || start < 0 || length < 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check that the regions are long enough
|
||||
if (srcLen < length || otherLen < length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
while (tmpLen-- > 0) {
|
||||
final char c1 = cs.charAt(index1++);
|
||||
final char c2 = substring.charAt(index2++);
|
||||
|
||||
if (c1 == c2) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!ignoreCase) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// The real same check as in String.regionMatches():
|
||||
final char u1 = Character.toUpperCase(c1);
|
||||
final char u2 = Character.toUpperCase(c2);
|
||||
if (u1 != u2 && Character.toLowerCase(u1) != Character.toLowerCase(u2)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
339
sources/main/java/org/apache/commons/lang3/CharSet.java
Normal file
339
sources/main/java/org/apache/commons/lang3/CharSet.java
Normal file
@ -0,0 +1,339 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* A set of characters.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Instances are immutable, but instances of subclasses may not be.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* #ThreadSafe#
|
||||
* </p>
|
||||
*
|
||||
* @since 1.0
|
||||
*/
|
||||
public class CharSet implements Serializable {
|
||||
|
||||
/**
|
||||
* Required for serialization support. Lang version 2.0.
|
||||
*
|
||||
* @see java.io.Serializable
|
||||
*/
|
||||
private static final long serialVersionUID = 5947847346149275958L;
|
||||
|
||||
/**
|
||||
* A CharSet defining no characters.
|
||||
*
|
||||
* @since 2.0
|
||||
*/
|
||||
public static final CharSet EMPTY = new CharSet((String) null);
|
||||
|
||||
/**
|
||||
* A CharSet defining ASCII alphabetic characters "a-zA-Z".
|
||||
*
|
||||
* @since 2.0
|
||||
*/
|
||||
public static final CharSet ASCII_ALPHA = new CharSet("a-zA-Z");
|
||||
|
||||
/**
|
||||
* A CharSet defining ASCII alphabetic characters "a-z".
|
||||
*
|
||||
* @since 2.0
|
||||
*/
|
||||
public static final CharSet ASCII_ALPHA_LOWER = new CharSet("a-z");
|
||||
|
||||
/**
|
||||
* A CharSet defining ASCII alphabetic characters "A-Z".
|
||||
*
|
||||
* @since 2.0
|
||||
*/
|
||||
public static final CharSet ASCII_ALPHA_UPPER = new CharSet("A-Z");
|
||||
|
||||
/**
|
||||
* A CharSet defining ASCII alphabetic characters "0-9".
|
||||
*
|
||||
* @since 2.0
|
||||
*/
|
||||
public static final CharSet ASCII_NUMERIC = new CharSet("0-9");
|
||||
|
||||
/**
|
||||
* A Map of the common cases used in the factory. Subclasses can add more common
|
||||
* patterns if desired
|
||||
*
|
||||
* @since 2.0
|
||||
*/
|
||||
protected static final Map<String, CharSet> COMMON = Collections.synchronizedMap(new HashMap<>());
|
||||
|
||||
static {
|
||||
COMMON.put(null, EMPTY);
|
||||
COMMON.put(StringUtils.EMPTY, EMPTY);
|
||||
COMMON.put("a-zA-Z", ASCII_ALPHA);
|
||||
COMMON.put("A-Za-z", ASCII_ALPHA);
|
||||
COMMON.put("a-z", ASCII_ALPHA_LOWER);
|
||||
COMMON.put("A-Z", ASCII_ALPHA_UPPER);
|
||||
COMMON.put("0-9", ASCII_NUMERIC);
|
||||
}
|
||||
|
||||
/** The set of CharRange objects. */
|
||||
private final Set<CharRange> set = Collections.synchronizedSet(new HashSet<>());
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Factory method to create a new CharSet using a special syntax.
|
||||
* </p>
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code null} or empty string ("") - set containing no characters</li>
|
||||
* <li>Single character, such as "a" - set containing just that character</li>
|
||||
* <li>Multi character, such as "a-e" - set containing characters from one
|
||||
* character to the other</li>
|
||||
* <li>Negated, such as "^a" or "^a-e" - set containing all characters except
|
||||
* those defined</li>
|
||||
* <li>Combinations, such as "abe-g" - set containing all the characters from
|
||||
* the individual sets</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>
|
||||
* The matching order is:
|
||||
* </p>
|
||||
* <ol>
|
||||
* <li>Negated multi character range, such as "^a-e"
|
||||
* <li>Ordinary multi character range, such as "a-e"
|
||||
* <li>Negated single character, such as "^a"
|
||||
* <li>Ordinary single character, such as "a"
|
||||
* </ol>
|
||||
*
|
||||
* <p>
|
||||
* Matching works left to right. Once a match is found the search starts again
|
||||
* from the next character.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* If the same range is defined twice using the same syntax, only one range will
|
||||
* be kept. Thus, "a-ca-c" creates only one range of "a-c".
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* If the start and end of a range are in the wrong order, they are reversed.
|
||||
* Thus "a-e" is the same as "e-a". As a result, "a-ee-a" would create only one
|
||||
* range, as the "a-e" and "e-a" are the same.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The set of characters represented is the union of the specified ranges.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* There are two ways to add a literal negation character ({@code ^}):
|
||||
* </p>
|
||||
* <ul>
|
||||
* <li>As the last character in a string, e.g.
|
||||
* {@code CharSet.getInstance("a-z^")}</li>
|
||||
* <li>As a separate element, e.g. {@code CharSet.getInstance("^", "a-z")}</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>
|
||||
* Examples using the negation character:
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharSet.getInstance("^a-c").contains('a') = false
|
||||
* CharSet.getInstance("^a-c").contains('d') = true
|
||||
* CharSet.getInstance("^^a-c").contains('a') = true // (only '^' is negated)
|
||||
* CharSet.getInstance("^^a-c").contains('^') = false
|
||||
* CharSet.getInstance("^a-cd-f").contains('d') = true
|
||||
* CharSet.getInstance("a-c^").contains('^') = true
|
||||
* CharSet.getInstance("^", "a-c").contains('^') = true
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* All CharSet objects returned by this method will be immutable.
|
||||
* </p>
|
||||
*
|
||||
* @param setStrs Strings to merge into the set, may be null
|
||||
* @return a CharSet instance
|
||||
* @since 2.4
|
||||
*/
|
||||
public static CharSet getInstance(final String... setStrs) {
|
||||
if (setStrs == null) {
|
||||
return null;
|
||||
}
|
||||
if (setStrs.length == 1) {
|
||||
final CharSet common = COMMON.get(setStrs[0]);
|
||||
if (common != null) {
|
||||
return common;
|
||||
}
|
||||
}
|
||||
return new CharSet(setStrs);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Constructs a new CharSet using the set syntax. Each string is merged in with
|
||||
* the set.
|
||||
* </p>
|
||||
*
|
||||
* @param set Strings to merge into the initial set
|
||||
* @throws NullPointerException if set is {@code null}
|
||||
*/
|
||||
protected CharSet(final String... set) {
|
||||
for (final String s : set) {
|
||||
add(s);
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Add a set definition string to the {@code CharSet}.
|
||||
* </p>
|
||||
*
|
||||
* @param str set definition string
|
||||
*/
|
||||
protected void add(final String str) {
|
||||
if (str == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final int len = str.length();
|
||||
int pos = 0;
|
||||
while (pos < len) {
|
||||
final int remainder = len - pos;
|
||||
if (remainder >= 4 && str.charAt(pos) == '^' && str.charAt(pos + 2) == '-') {
|
||||
// negated range
|
||||
set.add(CharRange.isNotIn(str.charAt(pos + 1), str.charAt(pos + 3)));
|
||||
pos += 4;
|
||||
} else if (remainder >= 3 && str.charAt(pos + 1) == '-') {
|
||||
// range
|
||||
set.add(CharRange.isIn(str.charAt(pos), str.charAt(pos + 2)));
|
||||
pos += 3;
|
||||
} else if (remainder >= 2 && str.charAt(pos) == '^') {
|
||||
// negated char
|
||||
set.add(CharRange.isNot(str.charAt(pos + 1)));
|
||||
pos += 2;
|
||||
} else {
|
||||
// char
|
||||
set.add(CharRange.is(str.charAt(pos)));
|
||||
pos += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Gets the internal set as an array of CharRange objects.
|
||||
* </p>
|
||||
*
|
||||
* @return an array of immutable CharRange objects
|
||||
* @since 2.0
|
||||
*/
|
||||
// NOTE: This is no longer public as CharRange is no longer a public class.
|
||||
// It may be replaced when CharSet moves to Range.
|
||||
/* public */ CharRange[] getCharRanges() {
|
||||
return set.toArray(CharRange.EMPTY_ARRAY);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Does the {@code CharSet} contain the specified character {@code ch}.
|
||||
* </p>
|
||||
*
|
||||
* @param ch the character to check for
|
||||
* @return {@code true} if the set contains the characters
|
||||
*/
|
||||
public boolean contains(final char ch) {
|
||||
synchronized (set) {
|
||||
for (final CharRange range : set) {
|
||||
if (range.contains(ch)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Basics
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Compares two {@code CharSet} objects, returning true if they represent
|
||||
* exactly the same set of characters defined in the same way.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The two sets {@code abc} and {@code a-c} are <i>not</i> equal according to
|
||||
* this method.
|
||||
* </p>
|
||||
*
|
||||
* @param obj the object to compare to
|
||||
* @return true if equal
|
||||
* @since 2.0
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (obj == this) {
|
||||
return true;
|
||||
}
|
||||
if (!(obj instanceof CharSet)) {
|
||||
return false;
|
||||
}
|
||||
final CharSet other = (CharSet) obj;
|
||||
return set.equals(other.set);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets a hash code compatible with the equals method.
|
||||
* </p>
|
||||
*
|
||||
* @return a suitable hash code
|
||||
* @since 2.0
|
||||
*/
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return 89 + set.hashCode();
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets a string representation of the set.
|
||||
* </p>
|
||||
*
|
||||
* @return string representation of the set
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return set.toString();
|
||||
}
|
||||
|
||||
}
|
268
sources/main/java/org/apache/commons/lang3/CharSetUtils.java
Normal file
268
sources/main/java/org/apache/commons/lang3/CharSetUtils.java
Normal file
@ -0,0 +1,268 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Operations on {@code CharSet} instances.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This class handles {@code null} input gracefully. An exception will not be
|
||||
* thrown for a {@code null} input. Each method documents its behavior in more
|
||||
* detail.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* #ThreadSafe#
|
||||
* </p>
|
||||
*
|
||||
* @see CharSet
|
||||
* @since 1.0
|
||||
*/
|
||||
public class CharSetUtils {
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Takes an argument in set-syntax, see evaluateSet, and identifies whether any
|
||||
* of the characters are present in the specified string.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharSetUtils.containsAny(null, *) = false
|
||||
* CharSetUtils.containsAny("", *) = false
|
||||
* CharSetUtils.containsAny(*, null) = false
|
||||
* CharSetUtils.containsAny(*, "") = false
|
||||
* CharSetUtils.containsAny("hello", "k-p") = true
|
||||
* CharSetUtils.containsAny("hello", "a-d") = false
|
||||
* </pre>
|
||||
*
|
||||
* @see CharSet#getInstance(java.lang.String...) for set-syntax.
|
||||
* @param str String to look for characters in, may be null
|
||||
* @param set String[] set of characters to identify, may be null
|
||||
* @return whether or not the characters in the set are in the primary string
|
||||
* @since 3.2
|
||||
*/
|
||||
public static boolean containsAny(final String str, final String... set) {
|
||||
if (StringUtils.isEmpty(str) || deepEmpty(set)) {
|
||||
return false;
|
||||
}
|
||||
final CharSet chars = CharSet.getInstance(set);
|
||||
for (final char c : str.toCharArray()) {
|
||||
if (chars.contains(c)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Takes an argument in set-syntax, see evaluateSet, and returns the number of
|
||||
* characters present in the specified string.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharSetUtils.count(null, *) = 0
|
||||
* CharSetUtils.count("", *) = 0
|
||||
* CharSetUtils.count(*, null) = 0
|
||||
* CharSetUtils.count(*, "") = 0
|
||||
* CharSetUtils.count("hello", "k-p") = 3
|
||||
* CharSetUtils.count("hello", "a-e") = 1
|
||||
* </pre>
|
||||
*
|
||||
* @see CharSet#getInstance(java.lang.String...) for set-syntax.
|
||||
* @param str String to count characters in, may be null
|
||||
* @param set String[] set of characters to count, may be null
|
||||
* @return the character count, zero if null string input
|
||||
*/
|
||||
public static int count(final String str, final String... set) {
|
||||
if (StringUtils.isEmpty(str) || deepEmpty(set)) {
|
||||
return 0;
|
||||
}
|
||||
final CharSet chars = CharSet.getInstance(set);
|
||||
int count = 0;
|
||||
for (final char c : str.toCharArray()) {
|
||||
if (chars.contains(c)) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether or not all the Strings in an array are empty or not.
|
||||
*
|
||||
* @param strings String[] whose elements are being checked for emptiness
|
||||
* @return whether or not the String is empty
|
||||
*/
|
||||
private static boolean deepEmpty(final String[] strings) {
|
||||
if (strings != null) {
|
||||
for (final String s : strings) {
|
||||
if (StringUtils.isNotEmpty(s)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Takes an argument in set-syntax, see evaluateSet, and deletes any of
|
||||
* characters present in the specified string.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharSetUtils.delete(null, *) = null
|
||||
* CharSetUtils.delete("", *) = ""
|
||||
* CharSetUtils.delete(*, null) = *
|
||||
* CharSetUtils.delete(*, "") = *
|
||||
* CharSetUtils.delete("hello", "hl") = "eo"
|
||||
* CharSetUtils.delete("hello", "le") = "ho"
|
||||
* </pre>
|
||||
*
|
||||
* @see CharSet#getInstance(java.lang.String...) for set-syntax.
|
||||
* @param str String to delete characters from, may be null
|
||||
* @param set String[] set of characters to delete, may be null
|
||||
* @return the modified String, {@code null} if null string input
|
||||
*/
|
||||
public static String delete(final String str, final String... set) {
|
||||
if (StringUtils.isEmpty(str) || deepEmpty(set)) {
|
||||
return str;
|
||||
}
|
||||
return modify(str, set, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Takes an argument in set-syntax, see evaluateSet, and keeps any of characters
|
||||
* present in the specified string.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharSetUtils.keep(null, *) = null
|
||||
* CharSetUtils.keep("", *) = ""
|
||||
* CharSetUtils.keep(*, null) = ""
|
||||
* CharSetUtils.keep(*, "") = ""
|
||||
* CharSetUtils.keep("hello", "hl") = "hll"
|
||||
* CharSetUtils.keep("hello", "le") = "ell"
|
||||
* </pre>
|
||||
*
|
||||
* @see CharSet#getInstance(java.lang.String...) for set-syntax.
|
||||
* @param str String to keep characters from, may be null
|
||||
* @param set String[] set of characters to keep, may be null
|
||||
* @return the modified String, {@code null} if null string input
|
||||
* @since 2.0
|
||||
*/
|
||||
public static String keep(final String str, final String... set) {
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
if (str.isEmpty() || deepEmpty(set)) {
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
return modify(str, set, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implementation of delete and keep
|
||||
*
|
||||
* @param str String to modify characters within
|
||||
* @param set String[] set of characters to modify
|
||||
* @param expect whether to evaluate on match, or non-match
|
||||
* @return the modified String, not null
|
||||
*/
|
||||
private static String modify(final String str, final String[] set, final boolean expect) {
|
||||
final CharSet chars = CharSet.getInstance(set);
|
||||
final StringBuilder buffer = new StringBuilder(str.length());
|
||||
final char[] chrs = str.toCharArray();
|
||||
for (final char chr : chrs) {
|
||||
if (chars.contains(chr) == expect) {
|
||||
buffer.append(chr);
|
||||
}
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Squeezes any repetitions of a character that is mentioned in the supplied
|
||||
* set.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharSetUtils.squeeze(null, *) = null
|
||||
* CharSetUtils.squeeze("", *) = ""
|
||||
* CharSetUtils.squeeze(*, null) = *
|
||||
* CharSetUtils.squeeze(*, "") = *
|
||||
* CharSetUtils.squeeze("hello", "k-p") = "helo"
|
||||
* CharSetUtils.squeeze("hello", "a-e") = "hello"
|
||||
* </pre>
|
||||
*
|
||||
* @see CharSet#getInstance(java.lang.String...) for set-syntax.
|
||||
* @param str the string to squeeze, may be null
|
||||
* @param set the character set to use for manipulation, may be null
|
||||
* @return the modified String, {@code null} if null string input
|
||||
*/
|
||||
public static String squeeze(final String str, final String... set) {
|
||||
if (StringUtils.isEmpty(str) || deepEmpty(set)) {
|
||||
return str;
|
||||
}
|
||||
final CharSet chars = CharSet.getInstance(set);
|
||||
final StringBuilder buffer = new StringBuilder(str.length());
|
||||
final char[] chrs = str.toCharArray();
|
||||
final int sz = chrs.length;
|
||||
char lastChar = chrs[0];
|
||||
char ch = ' ';
|
||||
Character inChars = null;
|
||||
Character notInChars = null;
|
||||
buffer.append(lastChar);
|
||||
for (int i = 1; i < sz; i++) {
|
||||
ch = chrs[i];
|
||||
if (ch == lastChar) {
|
||||
if (inChars != null && ch == inChars) {
|
||||
continue;
|
||||
}
|
||||
if (notInChars == null || ch != notInChars) {
|
||||
if (chars.contains(ch)) {
|
||||
inChars = ch;
|
||||
continue;
|
||||
}
|
||||
notInChars = ch;
|
||||
}
|
||||
}
|
||||
buffer.append(ch);
|
||||
lastChar = ch;
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* CharSetUtils instances should NOT be constructed in standard programming.
|
||||
* Instead, the class should be used as {@code CharSetUtils.evaluateSet(null);}.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This constructor is public to permit tools that require a JavaBean instance
|
||||
* to operate.
|
||||
* </p>
|
||||
*/
|
||||
public CharSetUtils() {
|
||||
}
|
||||
}
|
635
sources/main/java/org/apache/commons/lang3/CharUtils.java
Normal file
635
sources/main/java/org/apache/commons/lang3/CharUtils.java
Normal file
@ -0,0 +1,635 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Operations on char primitives and Character objects.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This class tries to handle {@code null} input gracefully. An exception will
|
||||
* not be thrown for a {@code null} input. Each method documents its behavior in
|
||||
* more detail.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* #ThreadSafe#
|
||||
* </p>
|
||||
*
|
||||
* @since 2.1
|
||||
*/
|
||||
public class CharUtils {
|
||||
|
||||
private static final String[] CHAR_STRING_ARRAY = new String[128];
|
||||
|
||||
private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
|
||||
'e', 'f' };
|
||||
|
||||
/**
|
||||
* Linefeed character LF ({@code '\n'}, Unicode 000a).
|
||||
*
|
||||
* @see <a href=
|
||||
* "http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6">JLF:
|
||||
* Escape Sequences for Character and String Literals</a>
|
||||
* @since 2.2
|
||||
*/
|
||||
public static final char LF = '\n';
|
||||
|
||||
/**
|
||||
* Carriage return characterf CR ('\r', Unicode 000d).
|
||||
*
|
||||
* @see <a href=
|
||||
* "http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6">JLF:
|
||||
* Escape Sequences for Character and String Literals</a>
|
||||
* @since 2.2
|
||||
*/
|
||||
public static final char CR = '\r';
|
||||
|
||||
/**
|
||||
* {@code \u0000} null control character ('\0'), abbreviated NUL.
|
||||
*
|
||||
* @since 3.6
|
||||
*/
|
||||
public static final char NUL = '\0';
|
||||
|
||||
static {
|
||||
for (char c = 0; c < CHAR_STRING_ARRAY.length; c++) {
|
||||
CHAR_STRING_ARRAY[c] = String.valueOf(c);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* {@code CharUtils} instances should NOT be constructed in standard
|
||||
* programming. Instead, the class should be used as
|
||||
* {@code CharUtils.toString('c');}.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This constructor is public to permit tools that require a JavaBean instance
|
||||
* to operate.
|
||||
* </p>
|
||||
*/
|
||||
public CharUtils() {
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Converts the character to a Character.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* For ASCII 7 bit characters, this uses a cache that will return the same
|
||||
* Character object each time.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.toCharacterObject(' ') = ' '
|
||||
* CharUtils.toCharacterObject('A') = 'A'
|
||||
* </pre>
|
||||
*
|
||||
* @deprecated Java 5 introduced {@link Character#valueOf(char)} which caches
|
||||
* chars 0 through 127.
|
||||
* @param ch the character to convert
|
||||
* @return a Character of the specified character
|
||||
*/
|
||||
@Deprecated
|
||||
public static Character toCharacterObject(final char ch) {
|
||||
return Character.valueOf(ch);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Converts the String to a Character using the first character, returning null
|
||||
* for empty Strings.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* For ASCII 7 bit characters, this uses a cache that will return the same
|
||||
* Character object each time.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.toCharacterObject(null) = null
|
||||
* CharUtils.toCharacterObject("") = null
|
||||
* CharUtils.toCharacterObject("A") = 'A'
|
||||
* CharUtils.toCharacterObject("BA") = 'B'
|
||||
* </pre>
|
||||
*
|
||||
* @param str the character to convert
|
||||
* @return the Character value of the first letter of the String
|
||||
*/
|
||||
public static Character toCharacterObject(final String str) {
|
||||
if (StringUtils.isEmpty(str)) {
|
||||
return null;
|
||||
}
|
||||
return Character.valueOf(str.charAt(0));
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Converts the Character to a char throwing an exception for {@code null}.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.toChar(' ') = ' '
|
||||
* CharUtils.toChar('A') = 'A'
|
||||
* CharUtils.toChar(null) throws IllegalArgumentException
|
||||
* </pre>
|
||||
*
|
||||
* @param ch the character to convert
|
||||
* @return the char value of the Character
|
||||
* @throws NullPointerException if the Character is null
|
||||
*/
|
||||
public static char toChar(final Character ch) {
|
||||
Validate.notNull(ch, "ch");
|
||||
return ch.charValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Converts the Character to a char handling {@code null}.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.toChar(null, 'X') = 'X'
|
||||
* CharUtils.toChar(' ', 'X') = ' '
|
||||
* CharUtils.toChar('A', 'X') = 'A'
|
||||
* </pre>
|
||||
*
|
||||
* @param ch the character to convert
|
||||
* @param defaultValue the value to use if the Character is null
|
||||
* @return the char value of the Character or the default if null
|
||||
*/
|
||||
public static char toChar(final Character ch, final char defaultValue) {
|
||||
if (ch == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
return ch.charValue();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Converts the String to a char using the first character, throwing an
|
||||
* exception on empty Strings.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.toChar("A") = 'A'
|
||||
* CharUtils.toChar("BA") = 'B'
|
||||
* CharUtils.toChar(null) throws IllegalArgumentException
|
||||
* CharUtils.toChar("") throws IllegalArgumentException
|
||||
* </pre>
|
||||
*
|
||||
* @param str the character to convert
|
||||
* @return the char value of the first letter of the String
|
||||
* @throws NullPointerException if the string is null
|
||||
* @throws IllegalArgumentException if the String is empty
|
||||
*/
|
||||
public static char toChar(final String str) {
|
||||
Validate.notEmpty(str, "The String must not be empty");
|
||||
return str.charAt(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Converts the String to a char using the first character, defaulting the value
|
||||
* on empty Strings.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.toChar(null, 'X') = 'X'
|
||||
* CharUtils.toChar("", 'X') = 'X'
|
||||
* CharUtils.toChar("A", 'X') = 'A'
|
||||
* CharUtils.toChar("BA", 'X') = 'B'
|
||||
* </pre>
|
||||
*
|
||||
* @param str the character to convert
|
||||
* @param defaultValue the value to use if the Character is null
|
||||
* @return the char value of the first letter of the String or the default if
|
||||
* null
|
||||
*/
|
||||
public static char toChar(final String str, final char defaultValue) {
|
||||
if (StringUtils.isEmpty(str)) {
|
||||
return defaultValue;
|
||||
}
|
||||
return str.charAt(0);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Converts the character to the Integer it represents, throwing an exception if
|
||||
* the character is not numeric.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method converts the char '1' to the int 1 and so on.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.toIntValue('3') = 3
|
||||
* CharUtils.toIntValue('A') throws IllegalArgumentException
|
||||
* </pre>
|
||||
*
|
||||
* @param ch the character to convert
|
||||
* @return the int value of the character
|
||||
* @throws IllegalArgumentException if the character is not ASCII numeric
|
||||
*/
|
||||
public static int toIntValue(final char ch) {
|
||||
if (!isAsciiNumeric(ch)) {
|
||||
throw new IllegalArgumentException("The character " + ch + " is not in the range '0' - '9'");
|
||||
}
|
||||
return ch - 48;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Converts the character to the Integer it represents, throwing an exception if
|
||||
* the character is not numeric.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method converts the char '1' to the int 1 and so on.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.toIntValue('3', -1) = 3
|
||||
* CharUtils.toIntValue('A', -1) = -1
|
||||
* </pre>
|
||||
*
|
||||
* @param ch the character to convert
|
||||
* @param defaultValue the default value to use if the character is not numeric
|
||||
* @return the int value of the character
|
||||
*/
|
||||
public static int toIntValue(final char ch, final int defaultValue) {
|
||||
if (!isAsciiNumeric(ch)) {
|
||||
return defaultValue;
|
||||
}
|
||||
return ch - 48;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Converts the character to the Integer it represents, throwing an exception if
|
||||
* the character is not numeric.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method converts the char '1' to the int 1 and so on.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.toIntValue('3') = 3
|
||||
* CharUtils.toIntValue(null) throws IllegalArgumentException
|
||||
* CharUtils.toIntValue('A') throws IllegalArgumentException
|
||||
* </pre>
|
||||
*
|
||||
* @param ch the character to convert, not null
|
||||
* @return the int value of the character
|
||||
* @throws NullPointerException if the Character is null
|
||||
* @throws IllegalArgumentException if the Character is not ASCII numeric
|
||||
*/
|
||||
public static int toIntValue(final Character ch) {
|
||||
Validate.notNull(ch, "ch");
|
||||
return toIntValue(ch.charValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Converts the character to the Integer it represents, throwing an exception if
|
||||
* the character is not numeric.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method converts the char '1' to the int 1 and so on.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.toIntValue(null, -1) = -1
|
||||
* CharUtils.toIntValue('3', -1) = 3
|
||||
* CharUtils.toIntValue('A', -1) = -1
|
||||
* </pre>
|
||||
*
|
||||
* @param ch the character to convert
|
||||
* @param defaultValue the default value to use if the character is not numeric
|
||||
* @return the int value of the character
|
||||
*/
|
||||
public static int toIntValue(final Character ch, final int defaultValue) {
|
||||
if (ch == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
return toIntValue(ch.charValue(), defaultValue);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Converts the character to a String that contains the one character.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* For ASCII 7 bit characters, this uses a cache that will return the same
|
||||
* String object each time.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.toString(' ') = " "
|
||||
* CharUtils.toString('A') = "A"
|
||||
* </pre>
|
||||
*
|
||||
* @param ch the character to convert
|
||||
* @return a String containing the one specified character
|
||||
*/
|
||||
public static String toString(final char ch) {
|
||||
if (ch < 128) {
|
||||
return CHAR_STRING_ARRAY[ch];
|
||||
}
|
||||
return new String(new char[] { ch });
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Converts the character to a String that contains the one character.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* For ASCII 7 bit characters, this uses a cache that will return the same
|
||||
* String object each time.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* If {@code null} is passed in, {@code null} will be returned.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.toString(null) = null
|
||||
* CharUtils.toString(' ') = " "
|
||||
* CharUtils.toString('A') = "A"
|
||||
* </pre>
|
||||
*
|
||||
* @param ch the character to convert
|
||||
* @return a String containing the one specified character
|
||||
*/
|
||||
public static String toString(final Character ch) {
|
||||
if (ch == null) {
|
||||
return null;
|
||||
}
|
||||
return toString(ch.charValue());
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Converts the string to the Unicode format '\u0020'.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This format is the Java source code format.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.unicodeEscaped(' ') = "\u0020"
|
||||
* CharUtils.unicodeEscaped('A') = "\u0041"
|
||||
* </pre>
|
||||
*
|
||||
* @param ch the character to convert
|
||||
* @return the escaped Unicode string
|
||||
*/
|
||||
public static String unicodeEscaped(final char ch) {
|
||||
return "\\u" + HEX_DIGITS[(ch >> 12) & 15] + HEX_DIGITS[(ch >> 8) & 15] + HEX_DIGITS[(ch >> 4) & 15]
|
||||
+ HEX_DIGITS[(ch) & 15];
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Converts the string to the Unicode format '\u0020'.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This format is the Java source code format.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* If {@code null} is passed in, {@code null} will be returned.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.unicodeEscaped(null) = null
|
||||
* CharUtils.unicodeEscaped(' ') = "\u0020"
|
||||
* CharUtils.unicodeEscaped('A') = "\u0041"
|
||||
* </pre>
|
||||
*
|
||||
* @param ch the character to convert, may be null
|
||||
* @return the escaped Unicode string, null if null input
|
||||
*/
|
||||
public static String unicodeEscaped(final Character ch) {
|
||||
if (ch == null) {
|
||||
return null;
|
||||
}
|
||||
return unicodeEscaped(ch.charValue());
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Checks whether the character is ASCII 7 bit.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.isAscii('a') = true
|
||||
* CharUtils.isAscii('A') = true
|
||||
* CharUtils.isAscii('3') = true
|
||||
* CharUtils.isAscii('-') = true
|
||||
* CharUtils.isAscii('\n') = true
|
||||
* CharUtils.isAscii('©') = false
|
||||
* </pre>
|
||||
*
|
||||
* @param ch the character to check
|
||||
* @return true if less than 128
|
||||
*/
|
||||
public static boolean isAscii(final char ch) {
|
||||
return ch < 128;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Checks whether the character is ASCII 7 bit printable.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.isAsciiPrintable('a') = true
|
||||
* CharUtils.isAsciiPrintable('A') = true
|
||||
* CharUtils.isAsciiPrintable('3') = true
|
||||
* CharUtils.isAsciiPrintable('-') = true
|
||||
* CharUtils.isAsciiPrintable('\n') = false
|
||||
* CharUtils.isAsciiPrintable('©') = false
|
||||
* </pre>
|
||||
*
|
||||
* @param ch the character to check
|
||||
* @return true if between 32 and 126 inclusive
|
||||
*/
|
||||
public static boolean isAsciiPrintable(final char ch) {
|
||||
return ch >= 32 && ch < 127;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Checks whether the character is ASCII 7 bit control.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.isAsciiControl('a') = false
|
||||
* CharUtils.isAsciiControl('A') = false
|
||||
* CharUtils.isAsciiControl('3') = false
|
||||
* CharUtils.isAsciiControl('-') = false
|
||||
* CharUtils.isAsciiControl('\n') = true
|
||||
* CharUtils.isAsciiControl('©') = false
|
||||
* </pre>
|
||||
*
|
||||
* @param ch the character to check
|
||||
* @return true if less than 32 or equals 127
|
||||
*/
|
||||
public static boolean isAsciiControl(final char ch) {
|
||||
return ch < 32 || ch == 127;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Checks whether the character is ASCII 7 bit alphabetic.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.isAsciiAlpha('a') = true
|
||||
* CharUtils.isAsciiAlpha('A') = true
|
||||
* CharUtils.isAsciiAlpha('3') = false
|
||||
* CharUtils.isAsciiAlpha('-') = false
|
||||
* CharUtils.isAsciiAlpha('\n') = false
|
||||
* CharUtils.isAsciiAlpha('©') = false
|
||||
* </pre>
|
||||
*
|
||||
* @param ch the character to check
|
||||
* @return true if between 65 and 90 or 97 and 122 inclusive
|
||||
*/
|
||||
public static boolean isAsciiAlpha(final char ch) {
|
||||
return isAsciiAlphaUpper(ch) || isAsciiAlphaLower(ch);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Checks whether the character is ASCII 7 bit alphabetic upper case.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.isAsciiAlphaUpper('a') = false
|
||||
* CharUtils.isAsciiAlphaUpper('A') = true
|
||||
* CharUtils.isAsciiAlphaUpper('3') = false
|
||||
* CharUtils.isAsciiAlphaUpper('-') = false
|
||||
* CharUtils.isAsciiAlphaUpper('\n') = false
|
||||
* CharUtils.isAsciiAlphaUpper('©') = false
|
||||
* </pre>
|
||||
*
|
||||
* @param ch the character to check
|
||||
* @return true if between 65 and 90 inclusive
|
||||
*/
|
||||
public static boolean isAsciiAlphaUpper(final char ch) {
|
||||
return ch >= 'A' && ch <= 'Z';
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Checks whether the character is ASCII 7 bit alphabetic lower case.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.isAsciiAlphaLower('a') = true
|
||||
* CharUtils.isAsciiAlphaLower('A') = false
|
||||
* CharUtils.isAsciiAlphaLower('3') = false
|
||||
* CharUtils.isAsciiAlphaLower('-') = false
|
||||
* CharUtils.isAsciiAlphaLower('\n') = false
|
||||
* CharUtils.isAsciiAlphaLower('©') = false
|
||||
* </pre>
|
||||
*
|
||||
* @param ch the character to check
|
||||
* @return true if between 97 and 122 inclusive
|
||||
*/
|
||||
public static boolean isAsciiAlphaLower(final char ch) {
|
||||
return ch >= 'a' && ch <= 'z';
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Checks whether the character is ASCII 7 bit numeric.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.isAsciiNumeric('a') = false
|
||||
* CharUtils.isAsciiNumeric('A') = false
|
||||
* CharUtils.isAsciiNumeric('3') = true
|
||||
* CharUtils.isAsciiNumeric('-') = false
|
||||
* CharUtils.isAsciiNumeric('\n') = false
|
||||
* CharUtils.isAsciiNumeric('©') = false
|
||||
* </pre>
|
||||
*
|
||||
* @param ch the character to check
|
||||
* @return true if between 48 and 57 inclusive
|
||||
*/
|
||||
public static boolean isAsciiNumeric(final char ch) {
|
||||
return ch >= '0' && ch <= '9';
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Checks whether the character is ASCII 7 bit numeric.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* CharUtils.isAsciiAlphanumeric('a') = true
|
||||
* CharUtils.isAsciiAlphanumeric('A') = true
|
||||
* CharUtils.isAsciiAlphanumeric('3') = true
|
||||
* CharUtils.isAsciiAlphanumeric('-') = false
|
||||
* CharUtils.isAsciiAlphanumeric('\n') = false
|
||||
* CharUtils.isAsciiAlphanumeric('©') = false
|
||||
* </pre>
|
||||
*
|
||||
* @param ch the character to check
|
||||
* @return true if between 48 and 57 or 65 and 90 or 97 and 122 inclusive
|
||||
*/
|
||||
public static boolean isAsciiAlphanumeric(final char ch) {
|
||||
return isAsciiAlpha(ch) || isAsciiNumeric(ch);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Compares two {@code char} values numerically. This is the same functionality
|
||||
* as provided in Java 7.
|
||||
* </p>
|
||||
*
|
||||
* @param x the first {@code char} to compare
|
||||
* @param y the second {@code char} to compare
|
||||
* @return the value {@code 0} if {@code x == y}; a value less than {@code 0} if
|
||||
* {@code x < y}; and a value greater than {@code 0} if {@code x > y}
|
||||
* @since 3.4
|
||||
*/
|
||||
public static int compare(final char x, final char y) {
|
||||
return x - y;
|
||||
}
|
||||
}
|
76
sources/main/java/org/apache/commons/lang3/Charsets.java
Normal file
76
sources/main/java/org/apache/commons/lang3/Charsets.java
Normal file
@ -0,0 +1,76 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.UnsupportedCharsetException;
|
||||
|
||||
/**
|
||||
* Internal use only.
|
||||
* <p>
|
||||
* Provides utilities for {@link Charset}.
|
||||
* </p>
|
||||
* <p>
|
||||
* Package private since Apache Commons IO already provides a Charsets because
|
||||
* {@link Charset} is in {@code java.nio.charset}.
|
||||
* </p>
|
||||
*
|
||||
* @since 3.10
|
||||
*/
|
||||
class Charsets {
|
||||
|
||||
/**
|
||||
* Returns the given {@code charset} or the default Charset if {@code charset}
|
||||
* is null.
|
||||
*
|
||||
* @param charset a Charset or null.
|
||||
* @return the given {@code charset} or the default Charset if {@code charset}
|
||||
* is null.
|
||||
*/
|
||||
static Charset toCharset(final Charset charset) {
|
||||
return charset == null ? Charset.defaultCharset() : charset;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the given {@code charset} or the default Charset if {@code charset}
|
||||
* is null.
|
||||
*
|
||||
* @param charsetName a Charset or null.
|
||||
* @return the given {@code charset} or the default Charset if {@code charset}
|
||||
* is null.
|
||||
* @throws UnsupportedCharsetException If no support for the named charset is
|
||||
* available in this instance of the Java
|
||||
* virtual machine
|
||||
*/
|
||||
static Charset toCharset(final String charsetName) {
|
||||
return charsetName == null ? Charset.defaultCharset() : Charset.forName(charsetName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the given {@code charset} or the default Charset if {@code charset}
|
||||
* is null.
|
||||
*
|
||||
* @param charsetName a Charset or null.
|
||||
* @return the given {@code charset} or the default Charset if {@code charset}
|
||||
* is null.
|
||||
*/
|
||||
static String toCharsetName(final String charsetName) {
|
||||
return charsetName == null ? Charset.defaultCharset().name() : charsetName;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
import java.net.URLClassLoader;
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* Helps work with {@link ClassLoader}.
|
||||
*
|
||||
* @since 3.10
|
||||
*/
|
||||
public class ClassLoaderUtils {
|
||||
|
||||
/**
|
||||
* Converts the given class loader to a String calling
|
||||
* {@link #toString(URLClassLoader)}.
|
||||
*
|
||||
* @param classLoader to URLClassLoader to convert.
|
||||
* @return the formatted string.
|
||||
*/
|
||||
public static String toString(final ClassLoader classLoader) {
|
||||
if (classLoader instanceof URLClassLoader) {
|
||||
return toString((URLClassLoader) classLoader);
|
||||
}
|
||||
return classLoader.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given URLClassLoader to a String in the format
|
||||
* {@code "URLClassLoader.toString() + [URL1, URL2, ...]"}.
|
||||
*
|
||||
* @param classLoader to URLClassLoader to convert.
|
||||
* @return the formatted string.
|
||||
*/
|
||||
public static String toString(final URLClassLoader classLoader) {
|
||||
return classLoader + Arrays.toString(classLoader.getURLs());
|
||||
}
|
||||
}
|
158
sources/main/java/org/apache/commons/lang3/ClassPathUtils.java
Normal file
158
sources/main/java/org/apache/commons/lang3/ClassPathUtils.java
Normal file
@ -0,0 +1,158 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
/**
|
||||
* Operations regarding the classpath.
|
||||
*
|
||||
* <p>
|
||||
* The methods of this class do not allow {@code null} inputs.
|
||||
* </p>
|
||||
*
|
||||
* @since 3.3
|
||||
*/
|
||||
//@Immutable
|
||||
public class ClassPathUtils {
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* {@code ClassPathUtils} instances should NOT be constructed in standard
|
||||
* programming. Instead, the class should be used as
|
||||
* {@code ClassPathUtils.toFullyQualifiedName(MyClass.class, "MyClass.properties");}.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This constructor is public to permit tools that require a JavaBean instance
|
||||
* to operate.
|
||||
* </p>
|
||||
*/
|
||||
public ClassPathUtils() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the fully qualified name for the resource with name
|
||||
* {@code resourceName} relative to the given context.
|
||||
*
|
||||
* <p>
|
||||
* Note that this method does not check whether the resource actually exists. It
|
||||
* only constructs the name. Null inputs are not allowed.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* ClassPathUtils.toFullyQualifiedName(StringUtils.class,
|
||||
* "StringUtils.properties") = "org.apache.commons.lang3.StringUtils.properties"
|
||||
* </pre>
|
||||
*
|
||||
* @param context The context for constructing the name.
|
||||
* @param resourceName the resource name to construct the fully qualified name
|
||||
* for.
|
||||
* @return the fully qualified name of the resource with name
|
||||
* {@code resourceName}.
|
||||
* @throws java.lang.NullPointerException if either {@code context} or
|
||||
* {@code resourceName} is null.
|
||||
*/
|
||||
public static String toFullyQualifiedName(final Class<?> context, final String resourceName) {
|
||||
Validate.notNull(context, "context");
|
||||
Validate.notNull(resourceName, "resourceName");
|
||||
return toFullyQualifiedName(context.getPackage(), resourceName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the fully qualified name for the resource with name
|
||||
* {@code resourceName} relative to the given context.
|
||||
*
|
||||
* <p>
|
||||
* Note that this method does not check whether the resource actually exists. It
|
||||
* only constructs the name. Null inputs are not allowed.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* ClassPathUtils.toFullyQualifiedName(StringUtils.class.getPackage(),
|
||||
* "StringUtils.properties") = "org.apache.commons.lang3.StringUtils.properties"
|
||||
* </pre>
|
||||
*
|
||||
* @param context The context for constructing the name.
|
||||
* @param resourceName the resource name to construct the fully qualified name
|
||||
* for.
|
||||
* @return the fully qualified name of the resource with name
|
||||
* {@code resourceName}.
|
||||
* @throws java.lang.NullPointerException if either {@code context} or
|
||||
* {@code resourceName} is null.
|
||||
*/
|
||||
public static String toFullyQualifiedName(final Package context, final String resourceName) {
|
||||
Validate.notNull(context, "context");
|
||||
Validate.notNull(resourceName, "resourceName");
|
||||
return context.getName() + "." + resourceName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the fully qualified path for the resource with name
|
||||
* {@code resourceName} relative to the given context.
|
||||
*
|
||||
* <p>
|
||||
* Note that this method does not check whether the resource actually exists. It
|
||||
* only constructs the path. Null inputs are not allowed.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* ClassPathUtils.toFullyQualifiedPath(StringUtils.class,
|
||||
* "StringUtils.properties") = "org/apache/commons/lang3/StringUtils.properties"
|
||||
* </pre>
|
||||
*
|
||||
* @param context The context for constructing the path.
|
||||
* @param resourceName the resource name to construct the fully qualified path
|
||||
* for.
|
||||
* @return the fully qualified path of the resource with name
|
||||
* {@code resourceName}.
|
||||
* @throws java.lang.NullPointerException if either {@code context} or
|
||||
* {@code resourceName} is null.
|
||||
*/
|
||||
public static String toFullyQualifiedPath(final Class<?> context, final String resourceName) {
|
||||
Validate.notNull(context, "context");
|
||||
Validate.notNull(resourceName, "resourceName");
|
||||
return toFullyQualifiedPath(context.getPackage(), resourceName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the fully qualified path for the resource with name
|
||||
* {@code resourceName} relative to the given context.
|
||||
*
|
||||
* <p>
|
||||
* Note that this method does not check whether the resource actually exists. It
|
||||
* only constructs the path. Null inputs are not allowed.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* ClassPathUtils.toFullyQualifiedPath(StringUtils.class.getPackage(),
|
||||
* "StringUtils.properties") = "org/apache/commons/lang3/StringUtils.properties"
|
||||
* </pre>
|
||||
*
|
||||
* @param context The context for constructing the path.
|
||||
* @param resourceName the resource name to construct the fully qualified path
|
||||
* for.
|
||||
* @return the fully qualified path of the resource with name
|
||||
* {@code resourceName}.
|
||||
* @throws java.lang.NullPointerException if either {@code context} or
|
||||
* {@code resourceName} is null.
|
||||
*/
|
||||
public static String toFullyQualifiedPath(final Package context, final String resourceName) {
|
||||
Validate.notNull(context, "context");
|
||||
Validate.notNull(resourceName, "resourceName");
|
||||
return context.getName().replace('.', '/') + "/" + resourceName;
|
||||
}
|
||||
|
||||
}
|
1610
sources/main/java/org/apache/commons/lang3/Conversion.java
Normal file
1610
sources/main/java/org/apache/commons/lang3/Conversion.java
Normal file
File diff suppressed because it is too large
Load Diff
334
sources/main/java/org/apache/commons/lang3/EnumUtils.java
Normal file
334
sources/main/java/org/apache/commons/lang3/EnumUtils.java
Normal file
@ -0,0 +1,334 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Utility library to provide helper methods for Java enums.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* #ThreadSafe#
|
||||
* </p>
|
||||
*
|
||||
* @since 3.0
|
||||
*/
|
||||
public class EnumUtils {
|
||||
|
||||
private static final String NULL_ELEMENTS_NOT_PERMITTED = "null elements not permitted";
|
||||
private static final String CANNOT_STORE_S_S_VALUES_IN_S_BITS = "Cannot store %s %s values in %s bits";
|
||||
private static final String S_DOES_NOT_SEEM_TO_BE_AN_ENUM_TYPE = "%s does not seem to be an Enum type";
|
||||
private static final String ENUM_CLASS_MUST_BE_DEFINED = "EnumClass must be defined.";
|
||||
|
||||
/**
|
||||
* Validate {@code enumClass}.
|
||||
*
|
||||
* @param <E> the type of the enumeration
|
||||
* @param enumClass to check
|
||||
* @return {@code enumClass}
|
||||
* @throws NullPointerException if {@code enumClass} is {@code null}
|
||||
* @throws IllegalArgumentException if {@code enumClass} is not an enum class
|
||||
* @since 3.2
|
||||
*/
|
||||
private static <E extends Enum<E>> Class<E> asEnum(final Class<E> enumClass) {
|
||||
Validate.notNull(enumClass, ENUM_CLASS_MUST_BE_DEFINED);
|
||||
Validate.isTrue(enumClass.isEnum(), S_DOES_NOT_SEEM_TO_BE_AN_ENUM_TYPE, enumClass);
|
||||
return enumClass;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that {@code enumClass} is compatible with representation in a
|
||||
* {@code long}.
|
||||
*
|
||||
* @param <E> the type of the enumeration
|
||||
* @param enumClass to check
|
||||
* @return {@code enumClass}
|
||||
* @throws NullPointerException if {@code enumClass} is {@code null}
|
||||
* @throws IllegalArgumentException if {@code enumClass} is not an enum class or
|
||||
* has more than 64 values
|
||||
* @since 3.0.1
|
||||
*/
|
||||
private static <E extends Enum<E>> Class<E> checkBitVectorable(final Class<E> enumClass) {
|
||||
final E[] constants = asEnum(enumClass).getEnumConstants();
|
||||
Validate.isTrue(constants.length <= Long.SIZE, CANNOT_STORE_S_S_VALUES_IN_S_BITS,
|
||||
Integer.valueOf(constants.length), enumClass.getSimpleName(), Integer.valueOf(Long.SIZE));
|
||||
|
||||
return enumClass;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a long bit vector representation of the given array of Enum values.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This generates a value that is usable by {@link EnumUtils#processBitVector}.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Do not use this method if you have more than 64 values in your Enum, as this
|
||||
* would create a value greater than a long can hold.
|
||||
* </p>
|
||||
*
|
||||
* @param enumClass the class of the enum we are working with, not {@code null}
|
||||
* @param values the values we want to convert, not {@code null}
|
||||
* @param <E> the type of the enumeration
|
||||
* @return a long whose value provides a binary representation of the given set
|
||||
* of enum values.
|
||||
* @throws NullPointerException if {@code enumClass} or {@code values} is
|
||||
* {@code null}
|
||||
* @throws IllegalArgumentException if {@code enumClass} is not an enum class or
|
||||
* has more than 64 values
|
||||
* @since 3.0.1
|
||||
* @see #generateBitVectors(Class, Iterable)
|
||||
*/
|
||||
@SafeVarargs
|
||||
public static <E extends Enum<E>> long generateBitVector(final Class<E> enumClass, final E... values) {
|
||||
Validate.noNullElements(values);
|
||||
return generateBitVector(enumClass, Arrays.asList(values));
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a long bit vector representation of the given subset of an Enum.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This generates a value that is usable by {@link EnumUtils#processBitVector}.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Do not use this method if you have more than 64 values in your Enum, as this
|
||||
* would create a value greater than a long can hold.
|
||||
* </p>
|
||||
*
|
||||
* @param enumClass the class of the enum we are working with, not {@code null}
|
||||
* @param values the values we want to convert, not {@code null}, neither
|
||||
* containing {@code null}
|
||||
* @param <E> the type of the enumeration
|
||||
* @return a long whose value provides a binary representation of the given set
|
||||
* of enum values.
|
||||
* @throws NullPointerException if {@code enumClass} or {@code values} is
|
||||
* {@code null}
|
||||
* @throws IllegalArgumentException if {@code enumClass} is not an enum class or
|
||||
* has more than 64 values, or if any
|
||||
* {@code values} {@code null}
|
||||
* @since 3.0.1
|
||||
* @see #generateBitVectors(Class, Iterable)
|
||||
*/
|
||||
public static <E extends Enum<E>> long generateBitVector(final Class<E> enumClass,
|
||||
final Iterable<? extends E> values) {
|
||||
checkBitVectorable(enumClass);
|
||||
Validate.notNull(values);
|
||||
long total = 0;
|
||||
for (final E constant : values) {
|
||||
Validate.notNull(constant, NULL_ELEMENTS_NOT_PERMITTED);
|
||||
total |= 1L << constant.ordinal();
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets the enum for the class, returning {@code null} if not found.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method differs from {@link Enum#valueOf} in that it does not throw an
|
||||
* exception for an invalid enum name.
|
||||
* </p>
|
||||
*
|
||||
* @param <E> the type of the enumeration
|
||||
* @param enumClass the class of the enum to query, not null
|
||||
* @param enumName the enum name, null returns null
|
||||
* @return the enum, null if not found
|
||||
*/
|
||||
public static <E extends Enum<E>> E getEnum(final Class<E> enumClass, final String enumName) {
|
||||
return getEnum(enumClass, enumName, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets the enum for the class, returning {@code defaultEnum} if not found.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method differs from {@link Enum#valueOf} in that it does not throw an
|
||||
* exception for an invalid enum name.
|
||||
* </p>
|
||||
*
|
||||
* @param <E> the type of the enumeration
|
||||
* @param enumClass the class of the enum to query, not null
|
||||
* @param enumName the enum name, null returns default enum
|
||||
* @param defaultEnum the default enum
|
||||
* @return the enum, default enum if not found
|
||||
* @since 3.10
|
||||
*/
|
||||
public static <E extends Enum<E>> E getEnum(final Class<E> enumClass, final String enumName, final E defaultEnum) {
|
||||
if (enumName == null) {
|
||||
return defaultEnum;
|
||||
}
|
||||
try {
|
||||
return Enum.valueOf(enumClass, enumName);
|
||||
} catch (final IllegalArgumentException ex) {
|
||||
return defaultEnum;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets the enum for the class, returning {@code null} if not found.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method differs from {@link Enum#valueOf} in that it does not throw an
|
||||
* exception for an invalid enum name and performs case insensitive matching of
|
||||
* the name.
|
||||
* </p>
|
||||
*
|
||||
* @param <E> the type of the enumeration
|
||||
* @param enumClass the class of the enum to query, not null
|
||||
* @param enumName the enum name, null returns null
|
||||
* @return the enum, null if not found
|
||||
* @since 3.8
|
||||
*/
|
||||
public static <E extends Enum<E>> E getEnumIgnoreCase(final Class<E> enumClass, final String enumName) {
|
||||
return getEnumIgnoreCase(enumClass, enumName, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets the enum for the class, returning {@code defaultEnum} if not found.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method differs from {@link Enum#valueOf} in that it does not throw an
|
||||
* exception for an invalid enum name and performs case insensitive matching of
|
||||
* the name.
|
||||
* </p>
|
||||
*
|
||||
* @param <E> the type of the enumeration
|
||||
* @param enumClass the class of the enum to query, not null
|
||||
* @param enumName the enum name, null returns default enum
|
||||
* @param defaultEnum the default enum
|
||||
* @return the enum, default enum if not found
|
||||
* @since 3.10
|
||||
*/
|
||||
public static <E extends Enum<E>> E getEnumIgnoreCase(final Class<E> enumClass, final String enumName,
|
||||
final E defaultEnum) {
|
||||
if (enumName == null || !enumClass.isEnum()) {
|
||||
return defaultEnum;
|
||||
}
|
||||
for (final E each : enumClass.getEnumConstants()) {
|
||||
if (each.name().equalsIgnoreCase(enumName)) {
|
||||
return each;
|
||||
}
|
||||
}
|
||||
return defaultEnum;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets the {@code List} of enums.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method is useful when you need a list of enums rather than an array.
|
||||
* </p>
|
||||
*
|
||||
* @param <E> the type of the enumeration
|
||||
* @param enumClass the class of the enum to query, not null
|
||||
* @return the modifiable list of enums, never null
|
||||
*/
|
||||
public static <E extends Enum<E>> List<E> getEnumList(final Class<E> enumClass) {
|
||||
return new ArrayList<>(Arrays.asList(enumClass.getEnumConstants()));
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets the {@code Map} of enums by name.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method is useful when you need a map of enums by name.
|
||||
* </p>
|
||||
*
|
||||
* @param <E> the type of the enumeration
|
||||
* @param enumClass the class of the enum to query, not null
|
||||
* @return the modifiable map of enum names to enums, never null
|
||||
*/
|
||||
public static <E extends Enum<E>> Map<String, E> getEnumMap(final Class<E> enumClass) {
|
||||
final Map<String, E> map = new LinkedHashMap<>();
|
||||
for (final E e : enumClass.getEnumConstants()) {
|
||||
map.put(e.name(), e);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Checks if the specified name is a valid enum for the class.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method differs from {@link Enum#valueOf} in that checks if the name is a
|
||||
* valid enum without needing to catch the exception.
|
||||
* </p>
|
||||
*
|
||||
* @param <E> the type of the enumeration
|
||||
* @param enumClass the class of the enum to query, not null
|
||||
* @param enumName the enum name, null returns false
|
||||
* @return true if the enum name is valid, otherwise false
|
||||
*/
|
||||
public static <E extends Enum<E>> boolean isValidEnum(final Class<E> enumClass, final String enumName) {
|
||||
return getEnum(enumClass, enumName) != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Checks if the specified name is a valid enum for the class.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method differs from {@link Enum#valueOf} in that checks if the name is a
|
||||
* valid enum without needing to catch the exception and performs case
|
||||
* insensitive matching of the name.
|
||||
* </p>
|
||||
*
|
||||
* @param <E> the type of the enumeration
|
||||
* @param enumClass the class of the enum to query, not null
|
||||
* @param enumName the enum name, null returns false
|
||||
* @return true if the enum name is valid, otherwise false
|
||||
* @since 3.8
|
||||
*/
|
||||
public static <E extends Enum<E>> boolean isValidEnumIgnoreCase(final Class<E> enumClass, final String enumName) {
|
||||
return getEnumIgnoreCase(enumClass, enumName) != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* This constructor is public to permit tools that require a JavaBean instance
|
||||
* to operate.
|
||||
*/
|
||||
public EnumUtils() {
|
||||
}
|
||||
}
|
757
sources/main/java/org/apache/commons/lang3/Functions.java
Normal file
757
sources/main/java/org/apache/commons/lang3/Functions.java
Normal file
@ -0,0 +1,757 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.lang.reflect.UndeclaredThrowableException;
|
||||
import java.util.Collection;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.apache.commons.lang3.Streams.FailableStream;
|
||||
import org.apache.commons.lang3.function.FailableBooleanSupplier;
|
||||
|
||||
/**
|
||||
* This class provides utility functions, and classes for working with the
|
||||
* {@code java.util.function} package, or more generally, with Java 8 lambdas.
|
||||
* More specifically, it attempts to address the fact that lambdas are supposed
|
||||
* not to throw Exceptions, at least not checked Exceptions, AKA instances of
|
||||
* {@link Exception}. This enforces the use of constructs like:
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* @code
|
||||
* Consumer<java.lang.reflect.Method> consumer = m -> {
|
||||
* try {
|
||||
* m.invoke(o, args);
|
||||
* } catch (Throwable t) {
|
||||
* throw Functions.rethrow(t);
|
||||
* }
|
||||
* };
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* By replacing a {@link java.util.function.Consumer Consumer<O>} with a
|
||||
* {@link FailableConsumer FailableConsumer<O,? extends Throwable>}, this
|
||||
* can be written like follows:
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* {@code
|
||||
* Functions.accept((m) -> m.invoke(o,args));
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* Obviously, the second version is much more concise and the spirit of Lambda
|
||||
* expressions is met better than the second version.
|
||||
* </p>
|
||||
*
|
||||
* @since 3.9
|
||||
* @deprecated Use {@link org.apache.commons.lang3.function.Failable}.
|
||||
*/
|
||||
@Deprecated
|
||||
public class Functions {
|
||||
|
||||
/**
|
||||
* A functional interface like {@link BiConsumer} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* <p>
|
||||
* TODO for 4.0: Move to org.apache.commons.lang3.function.
|
||||
* </p>
|
||||
*
|
||||
* @param <O1> Consumed type 1.
|
||||
* @param <O2> Consumed type 2.
|
||||
* @param <T> Thrown exception.
|
||||
* @deprecated Use {@link org.apache.commons.lang3.function.FailableBiConsumer}.
|
||||
*/
|
||||
@Deprecated
|
||||
@FunctionalInterface
|
||||
public interface FailableBiConsumer<O1, O2, T extends Throwable> {
|
||||
|
||||
/**
|
||||
* Accepts the consumer.
|
||||
*
|
||||
* @param object1 the first parameter for the consumable to accept
|
||||
* @param object2 the second parameter for the consumable to accept
|
||||
* @throws T Thrown when the consumer fails.
|
||||
*/
|
||||
void accept(O1 object1, O2 object2) throws T;
|
||||
}
|
||||
|
||||
/**
|
||||
* A functional interface like {@link BiFunction} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* <p>
|
||||
* TODO for 4.0: Move to org.apache.commons.lang3.function.
|
||||
* </p>
|
||||
*
|
||||
* @param <O1> Input type 1.
|
||||
* @param <O2> Input type 2.
|
||||
* @param <R> Return type.
|
||||
* @param <T> Thrown exception.
|
||||
* @deprecated Use {@link org.apache.commons.lang3.function.FailableBiFunction}.
|
||||
*/
|
||||
@Deprecated
|
||||
@FunctionalInterface
|
||||
public interface FailableBiFunction<O1, O2, R, T extends Throwable> {
|
||||
|
||||
/**
|
||||
* Applies this function.
|
||||
*
|
||||
* @param input1 the first input for the function
|
||||
* @param input2 the second input for the function
|
||||
* @return the result of the function
|
||||
* @throws T Thrown when the function fails.
|
||||
*/
|
||||
R apply(O1 input1, O2 input2) throws T;
|
||||
}
|
||||
|
||||
/**
|
||||
* A functional interface like {@link BiPredicate} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* <p>
|
||||
* TODO for 4.0: Move to org.apache.commons.lang3.function.
|
||||
* </p>
|
||||
*
|
||||
* @param <O1> Predicate type 1.
|
||||
* @param <O2> Predicate type 2.
|
||||
* @param <T> Thrown exception.
|
||||
* @deprecated Use
|
||||
* {@link org.apache.commons.lang3.function.FailableBiPredicate}.
|
||||
*/
|
||||
@Deprecated
|
||||
@FunctionalInterface
|
||||
public interface FailableBiPredicate<O1, O2, T extends Throwable> {
|
||||
|
||||
/**
|
||||
* Tests the predicate.
|
||||
*
|
||||
* @param object1 the first object to test the predicate on
|
||||
* @param object2 the second object to test the predicate on
|
||||
* @return the predicate's evaluation
|
||||
* @throws T if the predicate fails
|
||||
*/
|
||||
boolean test(O1 object1, O2 object2) throws T;
|
||||
}
|
||||
|
||||
/**
|
||||
* A functional interface like {@link java.util.concurrent.Callable} that
|
||||
* declares a {@code Throwable}.
|
||||
*
|
||||
* <p>
|
||||
* TODO for 4.0: Move to org.apache.commons.lang3.function.
|
||||
* </p>
|
||||
*
|
||||
* @param <R> Return type.
|
||||
* @param <T> Thrown exception.
|
||||
* @deprecated Use {@link org.apache.commons.lang3.function.FailableCallable}.
|
||||
*/
|
||||
@Deprecated
|
||||
@FunctionalInterface
|
||||
public interface FailableCallable<R, T extends Throwable> {
|
||||
|
||||
/**
|
||||
* Calls the callable.
|
||||
*
|
||||
* @return The value returned from the callable
|
||||
* @throws T if the callable fails
|
||||
*/
|
||||
R call() throws T;
|
||||
}
|
||||
|
||||
/**
|
||||
* A functional interface like {@link Consumer} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* <p>
|
||||
* TODO for 4.0: Move to org.apache.commons.lang3.function.
|
||||
* </p>
|
||||
*
|
||||
* @param <O> Consumed type 1.
|
||||
* @param <T> Thrown exception.
|
||||
* @deprecated Use {@link org.apache.commons.lang3.function.FailableConsumer}.
|
||||
*/
|
||||
@Deprecated
|
||||
@FunctionalInterface
|
||||
public interface FailableConsumer<O, T extends Throwable> {
|
||||
|
||||
/**
|
||||
* Accepts the consumer.
|
||||
*
|
||||
* @param object the parameter for the consumable to accept
|
||||
* @throws T Thrown when the consumer fails.
|
||||
*/
|
||||
void accept(O object) throws T;
|
||||
}
|
||||
|
||||
/**
|
||||
* A functional interface like {@link Function} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* <p>
|
||||
* TODO for 4.0: Move to org.apache.commons.lang3.function.
|
||||
* </p>
|
||||
*
|
||||
* @param <I> Input type 1.
|
||||
* @param <R> Return type.
|
||||
* @param <T> Thrown exception.
|
||||
* @deprecated Use {@link org.apache.commons.lang3.function.FailableFunction}.
|
||||
*/
|
||||
@Deprecated
|
||||
@FunctionalInterface
|
||||
public interface FailableFunction<I, R, T extends Throwable> {
|
||||
|
||||
/**
|
||||
* Applies this function.
|
||||
*
|
||||
* @param input the input for the function
|
||||
* @return the result of the function
|
||||
* @throws T Thrown when the function fails.
|
||||
*/
|
||||
R apply(I input) throws T;
|
||||
}
|
||||
|
||||
/**
|
||||
* A functional interface like {@link Predicate} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* <p>
|
||||
* TODO for 4.0: Move to org.apache.commons.lang3.function.
|
||||
* </p>
|
||||
*
|
||||
* @param <I> Predicate type 1.
|
||||
* @param <T> Thrown exception.
|
||||
* @deprecated Use {@link org.apache.commons.lang3.function.FailablePredicate}.
|
||||
*/
|
||||
@Deprecated
|
||||
@FunctionalInterface
|
||||
public interface FailablePredicate<I, T extends Throwable> {
|
||||
|
||||
/**
|
||||
* Tests the predicate.
|
||||
*
|
||||
* @param object the object to test the predicate on
|
||||
* @return the predicate's evaluation
|
||||
* @throws T if the predicate fails
|
||||
*/
|
||||
boolean test(I object) throws T;
|
||||
}
|
||||
|
||||
/**
|
||||
* A functional interface like {@link Runnable} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* <p>
|
||||
* TODO for 4.0: Move to org.apache.commons.lang3.function.
|
||||
* </p>
|
||||
*
|
||||
* @param <T> Thrown exception.
|
||||
* @deprecated Use {@link org.apache.commons.lang3.function.FailableRunnable}.
|
||||
*/
|
||||
@Deprecated
|
||||
@FunctionalInterface
|
||||
public interface FailableRunnable<T extends Throwable> {
|
||||
|
||||
/**
|
||||
* Runs the function.
|
||||
*
|
||||
* @throws T Thrown when the function fails.
|
||||
*/
|
||||
void run() throws T;
|
||||
}
|
||||
|
||||
/**
|
||||
* A functional interface like {@link Supplier} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* <p>
|
||||
* TODO for 4.0: Move to org.apache.commons.lang3.function.
|
||||
* </p>
|
||||
*
|
||||
* @param <R> Return type.
|
||||
* @param <T> Thrown exception.
|
||||
* @deprecated Use {@link org.apache.commons.lang3.function.FailableSupplier}.
|
||||
*/
|
||||
@Deprecated
|
||||
@FunctionalInterface
|
||||
public interface FailableSupplier<R, T extends Throwable> {
|
||||
|
||||
/**
|
||||
* Supplies an object
|
||||
*
|
||||
* @return a result
|
||||
* @throws T if the supplier fails
|
||||
*/
|
||||
R get() throws T;
|
||||
}
|
||||
|
||||
/**
|
||||
* Consumes a consumer and rethrows any exception as a {@link RuntimeException}.
|
||||
*
|
||||
* @param consumer the consumer to consume
|
||||
* @param object1 the first object to consume by {@code consumer}
|
||||
* @param object2 the second object to consume by {@code consumer}
|
||||
* @param <O1> the type of the first argument the consumer accepts
|
||||
* @param <O2> the type of the second argument the consumer accepts
|
||||
* @param <T> the type of checked exception the consumer may throw
|
||||
*/
|
||||
public static <O1, O2, T extends Throwable> void accept(final FailableBiConsumer<O1, O2, T> consumer,
|
||||
final O1 object1, final O2 object2) {
|
||||
run(() -> consumer.accept(object1, object2));
|
||||
}
|
||||
|
||||
/**
|
||||
* Consumes a consumer and rethrows any exception as a {@link RuntimeException}.
|
||||
*
|
||||
* @param consumer the consumer to consume
|
||||
* @param object the object to consume by {@code consumer}
|
||||
* @param <O> the type the consumer accepts
|
||||
* @param <T> the type of checked exception the consumer may throw
|
||||
*/
|
||||
public static <O, T extends Throwable> void accept(final FailableConsumer<O, T> consumer, final O object) {
|
||||
run(() -> consumer.accept(object));
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a function and rethrows any exception as a {@link RuntimeException}.
|
||||
*
|
||||
* @param function the function to apply
|
||||
* @param input1 the first input to apply {@code function} on
|
||||
* @param input2 the second input to apply {@code function} on
|
||||
* @param <O1> the type of the first argument the function accepts
|
||||
* @param <O2> the type of the second argument the function accepts
|
||||
* @param <O> the return type of the function
|
||||
* @param <T> the type of checked exception the function may throw
|
||||
* @return the value returned from the function
|
||||
*/
|
||||
public static <O1, O2, O, T extends Throwable> O apply(final FailableBiFunction<O1, O2, O, T> function,
|
||||
final O1 input1, final O2 input2) {
|
||||
return get(() -> function.apply(input1, input2));
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a function and rethrows any exception as a {@link RuntimeException}.
|
||||
*
|
||||
* @param function the function to apply
|
||||
* @param input the input to apply {@code function} on
|
||||
* @param <I> the type of the argument the function accepts
|
||||
* @param <O> the return type of the function
|
||||
* @param <T> the type of checked exception the function may throw
|
||||
* @return the value returned from the function
|
||||
*/
|
||||
public static <I, O, T extends Throwable> O apply(final FailableFunction<I, O, T> function, final I input) {
|
||||
return get(() -> function.apply(input));
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given {@link FailableBiConsumer} into a standard
|
||||
* {@link BiConsumer}.
|
||||
*
|
||||
* @param <O1> the type of the first argument of the consumers
|
||||
* @param <O2> the type of the second argument of the consumers
|
||||
* @param consumer a failable {@code BiConsumer}
|
||||
* @return a standard {@code BiConsumer}
|
||||
* @since 3.10
|
||||
*/
|
||||
public static <O1, O2> BiConsumer<O1, O2> asBiConsumer(final FailableBiConsumer<O1, O2, ?> consumer) {
|
||||
return (input1, input2) -> accept(consumer, input1, input2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given {@link FailableBiFunction} into a standard
|
||||
* {@link BiFunction}.
|
||||
*
|
||||
* @param <O1> the type of the first argument of the input of the functions
|
||||
* @param <O2> the type of the second argument of the input of the functions
|
||||
* @param <O> the type of the output of the functions
|
||||
* @param function a {@code FailableBiFunction}
|
||||
* @return a standard {@code BiFunction}
|
||||
* @since 3.10
|
||||
*/
|
||||
public static <O1, O2, O> BiFunction<O1, O2, O> asBiFunction(final FailableBiFunction<O1, O2, O, ?> function) {
|
||||
return (input1, input2) -> apply(function, input1, input2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given {@link FailableBiPredicate} into a standard
|
||||
* {@link BiPredicate}.
|
||||
*
|
||||
* @param <O1> the type of the first argument used by the predicates
|
||||
* @param <O2> the type of the second argument used by the predicates
|
||||
* @param predicate a {@code FailableBiPredicate}
|
||||
* @return a standard {@code BiPredicate}
|
||||
* @since 3.10
|
||||
*/
|
||||
public static <O1, O2> BiPredicate<O1, O2> asBiPredicate(final FailableBiPredicate<O1, O2, ?> predicate) {
|
||||
return (input1, input2) -> test(predicate, input1, input2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given {@link FailableCallable} into a standard {@link Callable}.
|
||||
*
|
||||
* @param <O> the type used by the callables
|
||||
* @param callable a {@code FailableCallable}
|
||||
* @return a standard {@code Callable}
|
||||
* @since 3.10
|
||||
*/
|
||||
public static <O> Callable<O> asCallable(final FailableCallable<O, ?> callable) {
|
||||
return () -> call(callable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given {@link FailableConsumer} into a standard {@link Consumer}.
|
||||
*
|
||||
* @param <I> the type used by the consumers
|
||||
* @param consumer a {@code FailableConsumer}
|
||||
* @return a standard {@code Consumer}
|
||||
* @since 3.10
|
||||
*/
|
||||
public static <I> Consumer<I> asConsumer(final FailableConsumer<I, ?> consumer) {
|
||||
return input -> accept(consumer, input);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given {@link FailableFunction} into a standard {@link Function}.
|
||||
*
|
||||
* @param <I> the type of the input of the functions
|
||||
* @param <O> the type of the output of the functions
|
||||
* @param function a {code FailableFunction}
|
||||
* @return a standard {@code Function}
|
||||
* @since 3.10
|
||||
*/
|
||||
public static <I, O> Function<I, O> asFunction(final FailableFunction<I, O, ?> function) {
|
||||
return input -> apply(function, input);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given {@link FailablePredicate} into a standard
|
||||
* {@link Predicate}.
|
||||
*
|
||||
* @param <I> the type used by the predicates
|
||||
* @param predicate a {@code FailablePredicate}
|
||||
* @return a standard {@code Predicate}
|
||||
* @since 3.10
|
||||
*/
|
||||
public static <I> Predicate<I> asPredicate(final FailablePredicate<I, ?> predicate) {
|
||||
return input -> test(predicate, input);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given {@link FailableRunnable} into a standard {@link Runnable}.
|
||||
*
|
||||
* @param runnable a {@code FailableRunnable}
|
||||
* @return a standard {@code Runnable}
|
||||
* @since 3.10
|
||||
*/
|
||||
public static Runnable asRunnable(final FailableRunnable<?> runnable) {
|
||||
return () -> run(runnable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given {@link FailableSupplier} into a standard {@link Supplier}.
|
||||
*
|
||||
* @param <O> the type supplied by the suppliers
|
||||
* @param supplier a {@code FailableSupplier}
|
||||
* @return a standard {@code Supplier}
|
||||
* @since 3.10
|
||||
*/
|
||||
public static <O> Supplier<O> asSupplier(final FailableSupplier<O, ?> supplier) {
|
||||
return () -> get(supplier);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls a callable and rethrows any exception as a {@link RuntimeException}.
|
||||
*
|
||||
* @param callable the callable to call
|
||||
* @param <O> the return type of the callable
|
||||
* @param <T> the type of checked exception the callable may throw
|
||||
* @return the value returned from the callable
|
||||
*/
|
||||
public static <O, T extends Throwable> O call(final FailableCallable<O, T> callable) {
|
||||
return get(callable::call);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes a supplier, and returns the result.
|
||||
*
|
||||
* @param supplier The supplier to invoke.
|
||||
* @param <O> The suppliers output type.
|
||||
* @param <T> The type of checked exception, which the supplier can throw.
|
||||
* @return The object, which has been created by the supplier
|
||||
* @since 3.10
|
||||
*/
|
||||
public static <O, T extends Throwable> O get(final FailableSupplier<O, T> supplier) {
|
||||
try {
|
||||
return supplier.get();
|
||||
} catch (final Throwable t) {
|
||||
throw rethrow(t);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes a boolean supplier, and returns the result.
|
||||
*
|
||||
* @param supplier The boolean supplier to invoke.
|
||||
* @param <T> The type of checked exception, which the supplier can throw.
|
||||
* @return The boolean, which has been created by the supplier
|
||||
*/
|
||||
private static <T extends Throwable> boolean getAsBoolean(final FailableBooleanSupplier<T> supplier) {
|
||||
try {
|
||||
return supplier.getAsBoolean();
|
||||
} catch (final Throwable t) {
|
||||
throw rethrow(t);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Rethrows a {@link Throwable} as an unchecked exception. If the argument is
|
||||
* already unchecked, namely a {@code RuntimeException} or {@code Error} then
|
||||
* the argument will be rethrown without modification. If the exception is
|
||||
* {@code IOException} then it will be wrapped into a
|
||||
* {@code UncheckedIOException}. In every other cases the exception will be
|
||||
* wrapped into a {@code
|
||||
* UndeclaredThrowableException}
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Note that there is a declared return type for this method, even though it
|
||||
* never returns. The reason for that is to support the usual pattern:
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* throw rethrow(myUncheckedException);
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* instead of just calling the method. This pattern may help the Java compiler
|
||||
* to recognize that at that point an exception will be thrown and the code flow
|
||||
* analysis will not demand otherwise mandatory commands that could follow the
|
||||
* method call, like a {@code return} statement from a value returning method.
|
||||
* </p>
|
||||
*
|
||||
* @param throwable The throwable to rethrow ossibly wrapped into an unchecked
|
||||
* exception
|
||||
* @return Never returns anything, this method never terminates normally.
|
||||
*/
|
||||
public static RuntimeException rethrow(final Throwable throwable) {
|
||||
Objects.requireNonNull(throwable, "throwable");
|
||||
if (throwable instanceof RuntimeException) {
|
||||
throw (RuntimeException) throwable;
|
||||
} else if (throwable instanceof Error) {
|
||||
throw (Error) throwable;
|
||||
} else if (throwable instanceof IOException) {
|
||||
throw new UncheckedIOException((IOException) throwable);
|
||||
} else {
|
||||
throw new UndeclaredThrowableException(throwable);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a runnable and rethrows any exception as a {@link RuntimeException}.
|
||||
*
|
||||
* @param runnable The runnable to run
|
||||
* @param <T> the type of checked exception the runnable may throw
|
||||
*/
|
||||
public static <T extends Throwable> void run(final FailableRunnable<T> runnable) {
|
||||
try {
|
||||
runnable.run();
|
||||
} catch (final Throwable t) {
|
||||
throw rethrow(t);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given collection into a {@link FailableStream}. The
|
||||
* {@link FailableStream} consists of the collections elements. Shortcut for
|
||||
*
|
||||
* <pre>
|
||||
* Functions.stream(collection.stream());
|
||||
* </pre>
|
||||
*
|
||||
* @param collection The collection, which is being converted into a
|
||||
* {@link FailableStream}.
|
||||
* @param <O> The collections element type. (In turn, the result streams
|
||||
* element type.)
|
||||
* @return The created {@link FailableStream}.
|
||||
* @since 3.10
|
||||
*/
|
||||
public static <O> FailableStream<O> stream(final Collection<O> collection) {
|
||||
return new FailableStream<>(collection.stream());
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given stream into a {@link FailableStream}. The
|
||||
* {@link FailableStream} consists of the same elements, than the input stream.
|
||||
* However, failable lambdas, like {@link FailablePredicate},
|
||||
* {@link FailableFunction}, and {@link FailableConsumer} may be applied, rather
|
||||
* than {@link Predicate}, {@link Function}, {@link Consumer}, etc.
|
||||
*
|
||||
* @param stream The stream, which is being converted into a
|
||||
* {@link FailableStream}.
|
||||
* @param <O> The streams element type.
|
||||
* @return The created {@link FailableStream}.
|
||||
* @since 3.10
|
||||
*/
|
||||
public static <O> FailableStream<O> stream(final Stream<O> stream) {
|
||||
return new FailableStream<>(stream);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests a predicate and rethrows any exception as a {@link RuntimeException}.
|
||||
*
|
||||
* @param predicate the predicate to test
|
||||
* @param object1 the first input to test by {@code predicate}
|
||||
* @param object2 the second input to test by {@code predicate}
|
||||
* @param <O1> the type of the first argument the predicate tests
|
||||
* @param <O2> the type of the second argument the predicate tests
|
||||
* @param <T> the type of checked exception the predicate may throw
|
||||
* @return the boolean value returned by the predicate
|
||||
*/
|
||||
public static <O1, O2, T extends Throwable> boolean test(final FailableBiPredicate<O1, O2, T> predicate,
|
||||
final O1 object1, final O2 object2) {
|
||||
return getAsBoolean(() -> predicate.test(object1, object2));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests a predicate and rethrows any exception as a {@link RuntimeException}.
|
||||
*
|
||||
* @param predicate the predicate to test
|
||||
* @param object the input to test by {@code predicate}
|
||||
* @param <O> the type of argument the predicate tests
|
||||
* @param <T> the type of checked exception the predicate may throw
|
||||
* @return the boolean value returned by the predicate
|
||||
*/
|
||||
public static <O, T extends Throwable> boolean test(final FailablePredicate<O, T> predicate, final O object) {
|
||||
return getAsBoolean(() -> predicate.test(object));
|
||||
}
|
||||
|
||||
/**
|
||||
* A simple try-with-resources implementation, that can be used, if your objects
|
||||
* do not implement the {@link AutoCloseable} interface. The method executes the
|
||||
* {@code action}. The method guarantees, that <em>all</em> the
|
||||
* {@code resources} are being executed, in the given order, afterwards, and
|
||||
* regardless of success, or failure. If either the original action, or any of
|
||||
* the resource action fails, then the <em>first</em> failure (AKA
|
||||
* {@link Throwable} is rethrown. Example use:
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* @code
|
||||
* final FileInputStream fis = new FileInputStream("my.file");
|
||||
* Functions.tryWithResources(useInputStream(fis), null, () -> fis.close());
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* @param action The action to execute. This object <em>will</em> always
|
||||
* be invoked.
|
||||
* @param errorHandler An optional error handler, which will be invoked finally,
|
||||
* if any error occurred. The error handler will receive the
|
||||
* first error, AKA {@link Throwable}.
|
||||
* @param resources The resource actions to execute. <em>All</em> resource
|
||||
* actions will be invoked, in the given order. A resource
|
||||
* action is an instance of {@link FailableRunnable}, which
|
||||
* will be executed.
|
||||
* @see #tryWithResources(FailableRunnable, FailableRunnable...)
|
||||
*/
|
||||
@SafeVarargs
|
||||
public static void tryWithResources(final FailableRunnable<? extends Throwable> action,
|
||||
final FailableConsumer<Throwable, ? extends Throwable> errorHandler,
|
||||
final FailableRunnable<? extends Throwable>... resources) {
|
||||
final FailableConsumer<Throwable, ? extends Throwable> actualErrorHandler;
|
||||
if (errorHandler == null) {
|
||||
actualErrorHandler = Functions::rethrow;
|
||||
} else {
|
||||
actualErrorHandler = errorHandler;
|
||||
}
|
||||
if (resources != null) {
|
||||
for (final FailableRunnable<? extends Throwable> failableRunnable : resources) {
|
||||
Objects.requireNonNull(failableRunnable, "runnable");
|
||||
}
|
||||
}
|
||||
Throwable th = null;
|
||||
try {
|
||||
action.run();
|
||||
} catch (final Throwable t) {
|
||||
th = t;
|
||||
}
|
||||
if (resources != null) {
|
||||
for (final FailableRunnable<?> runnable : resources) {
|
||||
try {
|
||||
runnable.run();
|
||||
} catch (final Throwable t) {
|
||||
if (th == null) {
|
||||
th = t;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (th != null) {
|
||||
try {
|
||||
actualErrorHandler.accept(th);
|
||||
} catch (final Throwable t) {
|
||||
throw rethrow(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A simple try-with-resources implementation, that can be used, if your objects
|
||||
* do not implement the {@link AutoCloseable} interface. The method executes the
|
||||
* {@code action}. The method guarantees, that <em>all</em> the
|
||||
* {@code resources} are being executed, in the given order, afterwards, and
|
||||
* regardless of success, or failure. If either the original action, or any of
|
||||
* the resource action fails, then the <em>first</em> failure (AKA
|
||||
* {@link Throwable} is rethrown. Example use:
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* @code
|
||||
* final FileInputStream fis = new FileInputStream("my.file");
|
||||
* Functions.tryWithResources(useInputStream(fis), () -> fis.close());
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* @param action The action to execute. This object <em>will</em> always be
|
||||
* invoked.
|
||||
* @param resources The resource actions to execute. <em>All</em> resource
|
||||
* actions will be invoked, in the given order. A resource
|
||||
* action is an instance of {@link FailableRunnable}, which
|
||||
* will be executed.
|
||||
* @see #tryWithResources(FailableRunnable, FailableConsumer,
|
||||
* FailableRunnable...)
|
||||
*/
|
||||
@SafeVarargs
|
||||
public static void tryWithResources(final FailableRunnable<? extends Throwable> action,
|
||||
final FailableRunnable<? extends Throwable>... resources) {
|
||||
tryWithResources(action, null, resources);
|
||||
}
|
||||
}
|
343
sources/main/java/org/apache/commons/lang3/JavaVersion.java
Normal file
343
sources/main/java/org/apache/commons/lang3/JavaVersion.java
Normal file
@ -0,0 +1,343 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* An enum representing all the versions of the Java specification. This is
|
||||
* intended to mirror available values from the
|
||||
* <em>java.specification.version</em> System property.
|
||||
* </p>
|
||||
*
|
||||
* @since 3.0
|
||||
*/
|
||||
public enum JavaVersion {
|
||||
|
||||
/**
|
||||
* The Java version reported by Android. This is not an official Java version
|
||||
* number.
|
||||
*/
|
||||
JAVA_0_9(1.5f, "0.9"),
|
||||
|
||||
/**
|
||||
* Java 1.1.
|
||||
*/
|
||||
JAVA_1_1(1.1f, "1.1"),
|
||||
|
||||
/**
|
||||
* Java 1.2.
|
||||
*/
|
||||
JAVA_1_2(1.2f, "1.2"),
|
||||
|
||||
/**
|
||||
* Java 1.3.
|
||||
*/
|
||||
JAVA_1_3(1.3f, "1.3"),
|
||||
|
||||
/**
|
||||
* Java 1.4.
|
||||
*/
|
||||
JAVA_1_4(1.4f, "1.4"),
|
||||
|
||||
/**
|
||||
* Java 1.5.
|
||||
*/
|
||||
JAVA_1_5(1.5f, "1.5"),
|
||||
|
||||
/**
|
||||
* Java 1.6.
|
||||
*/
|
||||
JAVA_1_6(1.6f, "1.6"),
|
||||
|
||||
/**
|
||||
* Java 1.7.
|
||||
*/
|
||||
JAVA_1_7(1.7f, "1.7"),
|
||||
|
||||
/**
|
||||
* Java 1.8.
|
||||
*/
|
||||
JAVA_1_8(1.8f, "1.8"),
|
||||
|
||||
/**
|
||||
* Java 1.9.
|
||||
*
|
||||
* @deprecated As of release 3.5, replaced by {@link #JAVA_9}
|
||||
*/
|
||||
@Deprecated
|
||||
JAVA_1_9(9.0f, "9"),
|
||||
|
||||
/**
|
||||
* Java 9.
|
||||
*
|
||||
* @since 3.5
|
||||
*/
|
||||
JAVA_9(9.0f, "9"),
|
||||
|
||||
/**
|
||||
* Java 10.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
JAVA_10(10.0f, "10"),
|
||||
|
||||
/**
|
||||
* Java 11.
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
JAVA_11(11.0f, "11"),
|
||||
|
||||
/**
|
||||
* Java 12.
|
||||
*
|
||||
* @since 3.9
|
||||
*/
|
||||
JAVA_12(12.0f, "12"),
|
||||
|
||||
/**
|
||||
* Java 13.
|
||||
*
|
||||
* @since 3.9
|
||||
*/
|
||||
JAVA_13(13.0f, "13"),
|
||||
|
||||
/**
|
||||
* Java 14.
|
||||
*
|
||||
* @since 3.11
|
||||
*/
|
||||
JAVA_14(14.0f, "14"),
|
||||
|
||||
/**
|
||||
* Java 15.
|
||||
*
|
||||
* @since 3.11
|
||||
*/
|
||||
JAVA_15(15.0f, "15"),
|
||||
|
||||
/**
|
||||
* Java 16.
|
||||
*
|
||||
* @since 3.11
|
||||
*/
|
||||
JAVA_16(16.0f, "16"),
|
||||
|
||||
/**
|
||||
* Java 17.
|
||||
*
|
||||
* @since 3.12.0
|
||||
*/
|
||||
JAVA_17(17.0f, "17"),
|
||||
|
||||
/**
|
||||
* The most recent java version. Mainly introduced to avoid to break when a new
|
||||
* version of Java is used.
|
||||
*/
|
||||
JAVA_RECENT(maxVersion(), Float.toString(maxVersion()));
|
||||
|
||||
/**
|
||||
* The float value.
|
||||
*/
|
||||
private final float value;
|
||||
|
||||
/**
|
||||
* The standard name.
|
||||
*/
|
||||
private final String name;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param value the float value
|
||||
* @param name the standard name, not null
|
||||
*/
|
||||
JavaVersion(final float value, final String name) {
|
||||
this.value = value;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Whether this version of Java is at least the version of Java passed in.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* For example:<br>
|
||||
* {@code myVersion.atLeast(JavaVersion.JAVA_1_4)}
|
||||
* <p>
|
||||
*
|
||||
* @param requiredVersion the version to check against, not null
|
||||
* @return true if this version is equal to or greater than the specified
|
||||
* version
|
||||
*/
|
||||
public boolean atLeast(final JavaVersion requiredVersion) {
|
||||
return this.value >= requiredVersion.value;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Whether this version of Java is at most the version of Java passed in.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* For example:<br>
|
||||
* {@code myVersion.atMost(JavaVersion.JAVA_1_4)}
|
||||
* <p>
|
||||
*
|
||||
* @param requiredVersion the version to check against, not null
|
||||
* @return true if this version is equal to or greater than the specified
|
||||
* version
|
||||
* @since 3.9
|
||||
*/
|
||||
public boolean atMost(final JavaVersion requiredVersion) {
|
||||
return this.value <= requiredVersion.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms the given string with a Java version number to the corresponding
|
||||
* constant of this enumeration class. This method is used internally.
|
||||
*
|
||||
* @param nom the Java version as string
|
||||
* @return the corresponding enumeration constant or <b>null</b> if the version
|
||||
* is unknown
|
||||
*/
|
||||
// helper for static importing
|
||||
static JavaVersion getJavaVersion(final String nom) {
|
||||
return get(nom);
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms the given string with a Java version number to the corresponding
|
||||
* constant of this enumeration class. This method is used internally.
|
||||
*
|
||||
* @param versionStr the Java version as string
|
||||
* @return the corresponding enumeration constant or <b>null</b> if the version
|
||||
* is unknown
|
||||
*/
|
||||
static JavaVersion get(final String versionStr) {
|
||||
if (versionStr == null) {
|
||||
return null;
|
||||
}
|
||||
switch (versionStr) {
|
||||
case "0.9":
|
||||
return JAVA_0_9;
|
||||
case "1.1":
|
||||
return JAVA_1_1;
|
||||
case "1.2":
|
||||
return JAVA_1_2;
|
||||
case "1.3":
|
||||
return JAVA_1_3;
|
||||
case "1.4":
|
||||
return JAVA_1_4;
|
||||
case "1.5":
|
||||
return JAVA_1_5;
|
||||
case "1.6":
|
||||
return JAVA_1_6;
|
||||
case "1.7":
|
||||
return JAVA_1_7;
|
||||
case "1.8":
|
||||
return JAVA_1_8;
|
||||
case "9":
|
||||
return JAVA_9;
|
||||
case "10":
|
||||
return JAVA_10;
|
||||
case "11":
|
||||
return JAVA_11;
|
||||
case "12":
|
||||
return JAVA_12;
|
||||
case "13":
|
||||
return JAVA_13;
|
||||
case "14":
|
||||
return JAVA_14;
|
||||
case "15":
|
||||
return JAVA_15;
|
||||
case "16":
|
||||
return JAVA_16;
|
||||
case "17":
|
||||
return JAVA_17;
|
||||
default:
|
||||
final float v = toFloatVersion(versionStr);
|
||||
if ((v - 1.) < 1.) { // then we need to check decimals > .9
|
||||
final int firstComma = Math.max(versionStr.indexOf('.'), versionStr.indexOf(','));
|
||||
final int end = Math.max(versionStr.length(), versionStr.indexOf(',', firstComma));
|
||||
if (Float.parseFloat(versionStr.substring(firstComma + 1, end)) > .9f) {
|
||||
return JAVA_RECENT;
|
||||
}
|
||||
} else if (v > 10) {
|
||||
return JAVA_RECENT;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* The string value is overridden to return the standard name.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* For example, {@code "1.5"}.
|
||||
* </p>
|
||||
*
|
||||
* @return the name, not null
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the Java Version from the system or 99.0 if the
|
||||
* {@code java.specification.version} system property is not set.
|
||||
*
|
||||
* @return the value of {@code java.specification.version} system property or
|
||||
* 99.0 if it is not set.
|
||||
*/
|
||||
private static float maxVersion() {
|
||||
final float v = toFloatVersion(System.getProperty("java.specification.version", "99.0"));
|
||||
if (v > 0) {
|
||||
return v;
|
||||
}
|
||||
return 99f;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a float value from a String.
|
||||
*
|
||||
* @param value the String to parse.
|
||||
* @return the float value represented by the string or -1 if the given String
|
||||
* can not be parsed.
|
||||
*/
|
||||
private static float toFloatVersion(final String value) {
|
||||
final int defaultReturnValue = -1;
|
||||
if (value.contains(".")) {
|
||||
final String[] toParse = value.split("\\.");
|
||||
if (toParse.length >= 2) {
|
||||
return NumberUtils.toFloat(toParse[0] + '.' + toParse[1], defaultReturnValue);
|
||||
}
|
||||
} else {
|
||||
return NumberUtils.toFloat(value, defaultReturnValue);
|
||||
}
|
||||
return defaultReturnValue;
|
||||
}
|
||||
}
|
396
sources/main/java/org/apache/commons/lang3/LocaleUtils.java
Normal file
396
sources/main/java/org/apache/commons/lang3/LocaleUtils.java
Normal file
@ -0,0 +1,396 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Operations to assist when working with a {@link Locale}.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This class tries to handle {@code null} input gracefully. An exception will
|
||||
* not be thrown for a {@code null} input. Each method documents its behavior in
|
||||
* more detail.
|
||||
* </p>
|
||||
*
|
||||
* @since 2.2
|
||||
*/
|
||||
public class LocaleUtils {
|
||||
|
||||
// class to avoid synchronization (Init on demand)
|
||||
static class SyncAvoid {
|
||||
/** Unmodifiable list of available locales. */
|
||||
private static final List<Locale> AVAILABLE_LOCALE_LIST;
|
||||
/** Unmodifiable set of available locales. */
|
||||
private static final Set<Locale> AVAILABLE_LOCALE_SET;
|
||||
|
||||
static {
|
||||
final List<Locale> list = new ArrayList<>(Arrays.asList(Locale.getAvailableLocales())); // extra safe
|
||||
AVAILABLE_LOCALE_LIST = Collections.unmodifiableList(list);
|
||||
AVAILABLE_LOCALE_SET = Collections.unmodifiableSet(new HashSet<>(list));
|
||||
}
|
||||
}
|
||||
|
||||
/** Concurrent map of language locales by country. */
|
||||
private static final Map<String, List<Locale>> cLanguagesByCountry = new HashMap<>();
|
||||
|
||||
/** Concurrent map of country locales by language. */
|
||||
private static final Map<String, List<Locale>> cCountriesByLanguage = new HashMap<>();
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Obtains an unmodifiable list of installed locales.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method is a wrapper around {@link Locale#getAvailableLocales()}. It is
|
||||
* more efficient, as the JDK method must create a new array each time it is
|
||||
* called.
|
||||
* </p>
|
||||
*
|
||||
* @return the unmodifiable list of available locales
|
||||
*/
|
||||
public static List<Locale> availableLocaleList() {
|
||||
return SyncAvoid.AVAILABLE_LOCALE_LIST;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Obtains an unmodifiable set of installed locales.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method is a wrapper around {@link Locale#getAvailableLocales()}. It is
|
||||
* more efficient, as the JDK method must create a new array each time it is
|
||||
* called.
|
||||
* </p>
|
||||
*
|
||||
* @return the unmodifiable set of available locales
|
||||
*/
|
||||
public static Set<Locale> availableLocaleSet() {
|
||||
return SyncAvoid.AVAILABLE_LOCALE_SET;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Obtains the list of countries supported for a given language.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method takes a language code and searches to find the countries
|
||||
* available for that language. Variant locales are removed.
|
||||
* </p>
|
||||
*
|
||||
* @param languageCode the 2 letter language code, null returns empty
|
||||
* @return an unmodifiable List of Locale objects, not null
|
||||
*/
|
||||
public static List<Locale> countriesByLanguage(final String languageCode) {
|
||||
if (languageCode == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
List<Locale> countries = cCountriesByLanguage.get(languageCode);
|
||||
if (countries == null) {
|
||||
countries = new ArrayList<>();
|
||||
final List<Locale> locales = availableLocaleList();
|
||||
for (final Locale locale : locales) {
|
||||
if (languageCode.equals(locale.getLanguage()) && !locale.getCountry().isEmpty()
|
||||
&& locale.getVariant().isEmpty()) {
|
||||
countries.add(locale);
|
||||
}
|
||||
}
|
||||
countries = Collections.unmodifiableList(countries);
|
||||
cCountriesByLanguage.putIfAbsent(languageCode, countries);
|
||||
countries = cCountriesByLanguage.get(languageCode);
|
||||
}
|
||||
return countries;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Checks if the locale specified is in the list of available locales.
|
||||
* </p>
|
||||
*
|
||||
* @param locale the Locale object to check if it is available
|
||||
* @return true if the locale is a known locale
|
||||
*/
|
||||
public static boolean isAvailableLocale(final Locale locale) {
|
||||
return availableLocaleList().contains(locale);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given String is a ISO 3166 alpha-2 country code.
|
||||
*
|
||||
* @param str the String to check
|
||||
* @return true, is the given String is a ISO 3166 compliant country code.
|
||||
*/
|
||||
private static boolean isISO3166CountryCode(final String str) {
|
||||
return StringUtils.isAllUpperCase(str) && str.length() == 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given String is a ISO 639 compliant language code.
|
||||
*
|
||||
* @param str the String to check.
|
||||
* @return true, if the given String is a ISO 639 compliant language code.
|
||||
*/
|
||||
private static boolean isISO639LanguageCode(final String str) {
|
||||
return StringUtils.isAllLowerCase(str) && (str.length() == 2 || str.length() == 3);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given String is a UN M.49 numeric area code.
|
||||
*
|
||||
* @param str the String to check
|
||||
* @return true, is the given String is a UN M.49 numeric area code.
|
||||
*/
|
||||
private static boolean isNumericAreaCode(final String str) {
|
||||
return StringUtils.isNumeric(str) && str.length() == 3;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Obtains the list of languages supported for a given country.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method takes a country code and searches to find the languages available
|
||||
* for that country. Variant locales are removed.
|
||||
* </p>
|
||||
*
|
||||
* @param countryCode the 2 letter country code, null returns empty
|
||||
* @return an unmodifiable List of Locale objects, not null
|
||||
*/
|
||||
public static List<Locale> languagesByCountry(final String countryCode) {
|
||||
if (countryCode == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
List<Locale> langs = cLanguagesByCountry.get(countryCode);
|
||||
if (langs == null) {
|
||||
langs = new ArrayList<>();
|
||||
final List<Locale> locales = availableLocaleList();
|
||||
for (final Locale locale : locales) {
|
||||
if (countryCode.equals(locale.getCountry()) && locale.getVariant().isEmpty()) {
|
||||
langs.add(locale);
|
||||
}
|
||||
}
|
||||
langs = Collections.unmodifiableList(langs);
|
||||
cLanguagesByCountry.putIfAbsent(countryCode, langs);
|
||||
langs = cLanguagesByCountry.get(countryCode);
|
||||
}
|
||||
return langs;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Obtains the list of locales to search through when performing a locale
|
||||
* search.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* localeLookupList(Locale("fr", "CA", "xxx"))
|
||||
* = [Locale("fr", "CA", "xxx"), Locale("fr", "CA"), Locale("fr")]
|
||||
* </pre>
|
||||
*
|
||||
* @param locale the locale to start from
|
||||
* @return the unmodifiable list of Locale objects, 0 being locale, not null
|
||||
*/
|
||||
public static List<Locale> localeLookupList(final Locale locale) {
|
||||
return localeLookupList(locale, locale);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Obtains the list of locales to search through when performing a locale
|
||||
* search.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* localeLookupList(Locale("fr", "CA", "xxx"), Locale("en"))
|
||||
* = [Locale("fr", "CA", "xxx"), Locale("fr", "CA"), Locale("fr"), Locale("en"]
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* The result list begins with the most specific locale, then the next more
|
||||
* general and so on, finishing with the default locale. The list will never
|
||||
* contain the same locale twice.
|
||||
* </p>
|
||||
*
|
||||
* @param locale the locale to start from, null returns empty list
|
||||
* @param defaultLocale the default locale to use if no other is found
|
||||
* @return the unmodifiable list of Locale objects, 0 being locale, not null
|
||||
*/
|
||||
public static List<Locale> localeLookupList(final Locale locale, final Locale defaultLocale) {
|
||||
final List<Locale> list = new ArrayList<>(4);
|
||||
if (locale != null) {
|
||||
list.add(locale);
|
||||
if (!locale.getVariant().isEmpty()) {
|
||||
list.add(new Locale(locale.getLanguage(), locale.getCountry()));
|
||||
}
|
||||
if (!locale.getCountry().isEmpty()) {
|
||||
list.add(new Locale(locale.getLanguage(), StringUtils.EMPTY));
|
||||
}
|
||||
if (!list.contains(defaultLocale)) {
|
||||
list.add(defaultLocale);
|
||||
}
|
||||
}
|
||||
return Collections.unmodifiableList(list);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to parse a locale from the given String.
|
||||
*
|
||||
* @param str the String to parse a locale from.
|
||||
* @return a Locale instance parsed from the given String.
|
||||
* @throws IllegalArgumentException if the given String can not be parsed.
|
||||
*/
|
||||
private static Locale parseLocale(final String str) {
|
||||
if (isISO639LanguageCode(str)) {
|
||||
return new Locale(str);
|
||||
}
|
||||
|
||||
final String[] segments = str.split("_", -1);
|
||||
final String language = segments[0];
|
||||
if (segments.length == 2) {
|
||||
final String country = segments[1];
|
||||
if (isISO639LanguageCode(language) && isISO3166CountryCode(country) || isNumericAreaCode(country)) {
|
||||
return new Locale(language, country);
|
||||
}
|
||||
} else if (segments.length == 3) {
|
||||
final String country = segments[1];
|
||||
final String variant = segments[2];
|
||||
if (isISO639LanguageCode(language)
|
||||
&& (country.isEmpty() || isISO3166CountryCode(country) || isNumericAreaCode(country))
|
||||
&& !variant.isEmpty()) {
|
||||
return new Locale(language, country, variant);
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Invalid locale format: " + str);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the given locale if non-{@code null}, otherwise
|
||||
* {@link Locale#getDefault()}.
|
||||
*
|
||||
* @param locale a locale or {@code null}.
|
||||
* @return the given locale if non-{@code null}, otherwise
|
||||
* {@link Locale#getDefault()}.
|
||||
* @since 3.12.0
|
||||
*/
|
||||
public static Locale toLocale(final Locale locale) {
|
||||
return locale != null ? locale : Locale.getDefault();
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Converts a String to a Locale.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method takes the string format of a locale and creates the locale object
|
||||
* from it.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* LocaleUtils.toLocale("") = new Locale("", "")
|
||||
* LocaleUtils.toLocale("en") = new Locale("en", "")
|
||||
* LocaleUtils.toLocale("en_GB") = new Locale("en", "GB")
|
||||
* LocaleUtils.toLocale("en_001") = new Locale("en", "001")
|
||||
* LocaleUtils.toLocale("en_GB_xxx") = new Locale("en", "GB", "xxx") (#)
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* (#) The behavior of the JDK variant constructor changed between JDK1.3 and
|
||||
* JDK1.4. In JDK1.3, the constructor upper cases the variant, in JDK1.4, it
|
||||
* doesn't. Thus, the result from getVariant() may vary depending on your JDK.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method validates the input strictly. The language code must be
|
||||
* lowercase. The country code must be uppercase. The separator must be an
|
||||
* underscore. The length must be correct.
|
||||
* </p>
|
||||
*
|
||||
* @param str the locale String to convert, null returns null
|
||||
* @return a Locale, null if null input
|
||||
* @throws IllegalArgumentException if the string is an invalid format
|
||||
* @see Locale#forLanguageTag(String)
|
||||
*/
|
||||
public static Locale toLocale(final String str) {
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
if (str.isEmpty()) { // LANG-941 - JDK 8 introduced an empty locale where all fields are blank
|
||||
return new Locale(StringUtils.EMPTY, StringUtils.EMPTY);
|
||||
}
|
||||
if (str.contains("#")) { // LANG-879 - Cannot handle Java 7 script & extensions
|
||||
throw new IllegalArgumentException("Invalid locale format: " + str);
|
||||
}
|
||||
final int len = str.length();
|
||||
if (len < 2) {
|
||||
throw new IllegalArgumentException("Invalid locale format: " + str);
|
||||
}
|
||||
final char ch0 = str.charAt(0);
|
||||
if (ch0 == '_') {
|
||||
if (len < 3) {
|
||||
throw new IllegalArgumentException("Invalid locale format: " + str);
|
||||
}
|
||||
final char ch1 = str.charAt(1);
|
||||
final char ch2 = str.charAt(2);
|
||||
if (!Character.isUpperCase(ch1) || !Character.isUpperCase(ch2)) {
|
||||
throw new IllegalArgumentException("Invalid locale format: " + str);
|
||||
}
|
||||
if (len == 3) {
|
||||
return new Locale(StringUtils.EMPTY, str.substring(1, 3));
|
||||
}
|
||||
if (len < 5) {
|
||||
throw new IllegalArgumentException("Invalid locale format: " + str);
|
||||
}
|
||||
if (str.charAt(3) != '_') {
|
||||
throw new IllegalArgumentException("Invalid locale format: " + str);
|
||||
}
|
||||
return new Locale(StringUtils.EMPTY, str.substring(1, 3), str.substring(4));
|
||||
}
|
||||
|
||||
return parseLocale(str);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* {@code LocaleUtils} instances should NOT be constructed in standard
|
||||
* programming. Instead, the class should be used as
|
||||
* {@code LocaleUtils.toLocale("en_GB");}.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This constructor is public to permit tools that require a JavaBean instance
|
||||
* to operate.
|
||||
* </p>
|
||||
*/
|
||||
public LocaleUtils() {
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,144 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Thrown to indicate that a block of code has not been implemented. This
|
||||
* exception supplements {@code UnsupportedOperationException} by providing a
|
||||
* more semantically rich description of the problem.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* {@code NotImplementedException} represents the case where the author has yet
|
||||
* to implement the logic at this point in the program. This can act as an
|
||||
* exception based TODO tag.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* public void foo() {
|
||||
* try {
|
||||
* // do something that throws an Exception
|
||||
* } catch (Exception ex) {
|
||||
* // don't know what to do here yet
|
||||
* throw new NotImplementedException("TODO", ex);
|
||||
* }
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* This class was originally added in Lang 2.0, but removed in 3.0.
|
||||
*
|
||||
* @since 3.2
|
||||
*/
|
||||
public class NotImplementedException extends UnsupportedOperationException {
|
||||
|
||||
private static final long serialVersionUID = 20131021L;
|
||||
|
||||
private final String code;
|
||||
|
||||
/**
|
||||
* Constructs a NotImplementedException.
|
||||
*
|
||||
* @since 3.10
|
||||
*/
|
||||
public NotImplementedException() {
|
||||
this.code = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a NotImplementedException.
|
||||
*
|
||||
* @param message description of the exception
|
||||
* @since 3.2
|
||||
*/
|
||||
public NotImplementedException(final String message) {
|
||||
this(message, (String) null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a NotImplementedException.
|
||||
*
|
||||
* @param cause cause of the exception
|
||||
* @since 3.2
|
||||
*/
|
||||
public NotImplementedException(final Throwable cause) {
|
||||
this(cause, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a NotImplementedException.
|
||||
*
|
||||
* @param message description of the exception
|
||||
* @param cause cause of the exception
|
||||
* @since 3.2
|
||||
*/
|
||||
public NotImplementedException(final String message, final Throwable cause) {
|
||||
this(message, cause, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a NotImplementedException.
|
||||
*
|
||||
* @param message description of the exception
|
||||
* @param code code indicating a resource for more information regarding the
|
||||
* lack of implementation
|
||||
* @since 3.2
|
||||
*/
|
||||
public NotImplementedException(final String message, final String code) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a NotImplementedException.
|
||||
*
|
||||
* @param cause cause of the exception
|
||||
* @param code code indicating a resource for more information regarding the
|
||||
* lack of implementation
|
||||
* @since 3.2
|
||||
*/
|
||||
public NotImplementedException(final Throwable cause, final String code) {
|
||||
super(cause);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a NotImplementedException.
|
||||
*
|
||||
* @param message description of the exception
|
||||
* @param cause cause of the exception
|
||||
* @param code code indicating a resource for more information regarding the
|
||||
* lack of implementation
|
||||
* @since 3.2
|
||||
*/
|
||||
public NotImplementedException(final String message, final Throwable cause, final String code) {
|
||||
super(message, cause);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtain the not implemented code. This is an unformatted piece of text
|
||||
* intended to point to further information regarding the lack of
|
||||
* implementation. It might, for example, be an issue tracker ID or a URL.
|
||||
*
|
||||
* @return a code indicating a resource for more information regarding the lack
|
||||
* of implementation
|
||||
*/
|
||||
public String getCode() {
|
||||
return this.code;
|
||||
}
|
||||
}
|
1377
sources/main/java/org/apache/commons/lang3/ObjectUtils.java
Normal file
1377
sources/main/java/org/apache/commons/lang3/ObjectUtils.java
Normal file
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,577 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Generates random {@code String}s.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* <b>Caveat: Instances of {@link EaglercraftRandom}, upon which the implementation of this
|
||||
* class relies, are not cryptographically secure.</b>
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* RandomStringUtils is intended for simple use cases. For more advanced use
|
||||
* cases consider using Apache Commons Text's <a href=
|
||||
* "https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/RandomStringGenerator.html">
|
||||
* RandomStringGenerator</a> instead.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The Apache Commons project provides
|
||||
* <a href="https://commons.apache.org/rng">Commons RNG</a> dedicated to
|
||||
* pseudo-random number generation, that may be a better choice for applications
|
||||
* with more stringent requirements (performance and/or correctness).
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Note that <em>private high surrogate</em> characters are ignored. These are
|
||||
* Unicode characters that fall between the values 56192 (db80) and 56319 (dbff)
|
||||
* as we don't know how to handle them. High and low surrogates are correctly
|
||||
* dealt with - that is if a high surrogate is randomly chosen, 55296 (d800) to
|
||||
* 56191 (db7f) then it is followed by a low surrogate. If a low surrogate is
|
||||
* chosen, 56320 (dc00) to 57343 (dfff) then it is placed after a randomly
|
||||
* chosen high surrogate.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* #ThreadSafe#
|
||||
* </p>
|
||||
*
|
||||
* @since 1.0
|
||||
*/
|
||||
public class RandomStringUtils {
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Random object used by random method. This has to be not local to the random
|
||||
* method so as to not return the same value in the same millisecond.
|
||||
* </p>
|
||||
*/
|
||||
private static final EaglercraftRandom RANDOM = new EaglercraftRandom();
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* {@code RandomStringUtils} instances should NOT be constructed in standard
|
||||
* programming. Instead, the class should be used as
|
||||
* {@code RandomStringUtils.random(5);}.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This constructor is public to permit tools that require a JavaBean instance
|
||||
* to operate.
|
||||
* </p>
|
||||
*/
|
||||
public RandomStringUtils() {
|
||||
}
|
||||
|
||||
// Random
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* <p>
|
||||
* Creates a random string whose length is the number of characters specified.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Characters will be chosen from the set of all characters.
|
||||
* </p>
|
||||
*
|
||||
* @param count the length of random string to create
|
||||
* @return the random string
|
||||
*/
|
||||
public static String random(final int count) {
|
||||
return random(count, false, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a random string whose length is the number of characters specified.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Characters will be chosen from the set of characters whose ASCII value is
|
||||
* between {@code 32} and {@code 126} (inclusive).
|
||||
* </p>
|
||||
*
|
||||
* @param count the length of random string to create
|
||||
* @return the random string
|
||||
*/
|
||||
public static String randomAscii(final int count) {
|
||||
return random(count, 32, 127, false, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a random string whose length is between the inclusive minimum and the
|
||||
* exclusive maximum.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Characters will be chosen from the set of characters whose ASCII value is
|
||||
* between {@code 32} and {@code 126} (inclusive).
|
||||
* </p>
|
||||
*
|
||||
* @param minLengthInclusive the inclusive minimum length of the string to
|
||||
* generate
|
||||
* @param maxLengthExclusive the exclusive maximum length of the string to
|
||||
* generate
|
||||
* @return the random string
|
||||
* @since 3.5
|
||||
*/
|
||||
public static String randomAscii(final int minLengthInclusive, final int maxLengthExclusive) {
|
||||
return randomAscii(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive));
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a random string whose length is the number of characters specified.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Characters will be chosen from the set of Latin alphabetic characters (a-z,
|
||||
* A-Z).
|
||||
* </p>
|
||||
*
|
||||
* @param count the length of random string to create
|
||||
* @return the random string
|
||||
*/
|
||||
public static String randomAlphabetic(final int count) {
|
||||
return random(count, true, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a random string whose length is between the inclusive minimum and the
|
||||
* exclusive maximum.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Characters will be chosen from the set of Latin alphabetic characters (a-z,
|
||||
* A-Z).
|
||||
* </p>
|
||||
*
|
||||
* @param minLengthInclusive the inclusive minimum length of the string to
|
||||
* generate
|
||||
* @param maxLengthExclusive the exclusive maximum length of the string to
|
||||
* generate
|
||||
* @return the random string
|
||||
* @since 3.5
|
||||
*/
|
||||
public static String randomAlphabetic(final int minLengthInclusive, final int maxLengthExclusive) {
|
||||
return randomAlphabetic(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive));
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a random string whose length is the number of characters specified.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Characters will be chosen from the set of Latin alphabetic characters (a-z,
|
||||
* A-Z) and the digits 0-9.
|
||||
* </p>
|
||||
*
|
||||
* @param count the length of random string to create
|
||||
* @return the random string
|
||||
*/
|
||||
public static String randomAlphanumeric(final int count) {
|
||||
return random(count, true, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a random string whose length is between the inclusive minimum and the
|
||||
* exclusive maximum.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Characters will be chosen from the set of Latin alphabetic characters (a-z,
|
||||
* A-Z) and the digits 0-9.
|
||||
* </p>
|
||||
*
|
||||
* @param minLengthInclusive the inclusive minimum length of the string to
|
||||
* generate
|
||||
* @param maxLengthExclusive the exclusive maximum length of the string to
|
||||
* generate
|
||||
* @return the random string
|
||||
* @since 3.5
|
||||
*/
|
||||
public static String randomAlphanumeric(final int minLengthInclusive, final int maxLengthExclusive) {
|
||||
return randomAlphanumeric(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive));
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a random string whose length is the number of characters specified.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Characters will be chosen from the set of characters which match the POSIX
|
||||
* [:graph:] regular expression character class. This class contains all visible
|
||||
* ASCII characters (i.e. anything except spaces and control characters).
|
||||
* </p>
|
||||
*
|
||||
* @param count the length of random string to create
|
||||
* @return the random string
|
||||
* @since 3.5
|
||||
*/
|
||||
public static String randomGraph(final int count) {
|
||||
return random(count, 33, 126, false, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a random string whose length is between the inclusive minimum and the
|
||||
* exclusive maximum.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Characters will be chosen from the set of \p{Graph} characters.
|
||||
* </p>
|
||||
*
|
||||
* @param minLengthInclusive the inclusive minimum length of the string to
|
||||
* generate
|
||||
* @param maxLengthExclusive the exclusive maximum length of the string to
|
||||
* generate
|
||||
* @return the random string
|
||||
* @since 3.5
|
||||
*/
|
||||
public static String randomGraph(final int minLengthInclusive, final int maxLengthExclusive) {
|
||||
return randomGraph(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive));
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a random string whose length is the number of characters specified.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Characters will be chosen from the set of numeric characters.
|
||||
* </p>
|
||||
*
|
||||
* @param count the length of random string to create
|
||||
* @return the random string
|
||||
*/
|
||||
public static String randomNumeric(final int count) {
|
||||
return random(count, false, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a random string whose length is between the inclusive minimum and the
|
||||
* exclusive maximum.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Characters will be chosen from the set of \p{Digit} characters.
|
||||
* </p>
|
||||
*
|
||||
* @param minLengthInclusive the inclusive minimum length of the string to
|
||||
* generate
|
||||
* @param maxLengthExclusive the exclusive maximum length of the string to
|
||||
* generate
|
||||
* @return the random string
|
||||
* @since 3.5
|
||||
*/
|
||||
public static String randomNumeric(final int minLengthInclusive, final int maxLengthExclusive) {
|
||||
return randomNumeric(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive));
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a random string whose length is the number of characters specified.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Characters will be chosen from the set of characters which match the POSIX
|
||||
* [:print:] regular expression character class. This class includes all visible
|
||||
* ASCII characters and spaces (i.e. anything except control characters).
|
||||
* </p>
|
||||
*
|
||||
* @param count the length of random string to create
|
||||
* @return the random string
|
||||
* @since 3.5
|
||||
*/
|
||||
public static String randomPrint(final int count) {
|
||||
return random(count, 32, 126, false, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a random string whose length is between the inclusive minimum and the
|
||||
* exclusive maximum.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Characters will be chosen from the set of \p{Print} characters.
|
||||
* </p>
|
||||
*
|
||||
* @param minLengthInclusive the inclusive minimum length of the string to
|
||||
* generate
|
||||
* @param maxLengthExclusive the exclusive maximum length of the string to
|
||||
* generate
|
||||
* @return the random string
|
||||
* @since 3.5
|
||||
*/
|
||||
public static String randomPrint(final int minLengthInclusive, final int maxLengthExclusive) {
|
||||
return randomPrint(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive));
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a random string whose length is the number of characters specified.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Characters will be chosen from the set of alpha-numeric characters as
|
||||
* indicated by the arguments.
|
||||
* </p>
|
||||
*
|
||||
* @param count the length of random string to create
|
||||
* @param letters if {@code true}, generated string may include alphabetic
|
||||
* characters
|
||||
* @param numbers if {@code true}, generated string may include numeric
|
||||
* characters
|
||||
* @return the random string
|
||||
*/
|
||||
public static String random(final int count, final boolean letters, final boolean numbers) {
|
||||
return random(count, 0, 0, letters, numbers);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a random string whose length is the number of characters specified.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Characters will be chosen from the set of alpha-numeric characters as
|
||||
* indicated by the arguments.
|
||||
* </p>
|
||||
*
|
||||
* @param count the length of random string to create
|
||||
* @param start the position in set of chars to start at
|
||||
* @param end the position in set of chars to end before
|
||||
* @param letters if {@code true}, generated string may include alphabetic
|
||||
* characters
|
||||
* @param numbers if {@code true}, generated string may include numeric
|
||||
* characters
|
||||
* @return the random string
|
||||
*/
|
||||
public static String random(final int count, final int start, final int end, final boolean letters,
|
||||
final boolean numbers) {
|
||||
return random(count, start, end, letters, numbers, null, RANDOM);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a random string based on a variety of options, using default source
|
||||
* of randomness.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method has exactly the same semantics as
|
||||
* {@link #random(int,int,int,boolean,boolean,char[],EaglercraftRandom)}, but instead of
|
||||
* using an externally supplied source of randomness, it uses the internal
|
||||
* static {@link EaglercraftRandom} instance.
|
||||
* </p>
|
||||
*
|
||||
* @param count the length of random string to create
|
||||
* @param start the position in set of chars to start at
|
||||
* @param end the position in set of chars to end before
|
||||
* @param letters if {@code true}, generated string may include alphabetic
|
||||
* characters
|
||||
* @param numbers if {@code true}, generated string may include numeric
|
||||
* characters
|
||||
* @param chars the set of chars to choose randoms from. If {@code null}, then
|
||||
* it will use the set of all chars.
|
||||
* @return the random string
|
||||
* @throws ArrayIndexOutOfBoundsException if there are not
|
||||
* {@code (end - start) + 1} characters
|
||||
* in the set array.
|
||||
*/
|
||||
public static String random(final int count, final int start, final int end, final boolean letters,
|
||||
final boolean numbers, final char... chars) {
|
||||
return random(count, start, end, letters, numbers, chars, RANDOM);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a random string based on a variety of options, using supplied source
|
||||
* of randomness.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* If start and end are both {@code 0}, start and end are set to {@code ' '} and
|
||||
* {@code 'z'}, the ASCII printable characters, will be used, unless letters and
|
||||
* numbers are both {@code false}, in which case, start and end are set to
|
||||
* {@code 0} and {@link Character#MAX_CODE_POINT}.
|
||||
*
|
||||
* <p>
|
||||
* If set is not {@code null}, characters between start and end are chosen.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method accepts a user-supplied {@link EaglercraftRandom} instance to use as a
|
||||
* source of randomness. By seeding a single {@link EaglercraftRandom} instance with a
|
||||
* fixed seed and using it for each call, the same random sequence of strings
|
||||
* can be generated repeatedly and predictably.
|
||||
* </p>
|
||||
*
|
||||
* @param count the length of random string to create
|
||||
* @param start the position in set of chars to start at (inclusive)
|
||||
* @param end the position in set of chars to end before (exclusive)
|
||||
* @param letters if {@code true}, generated string may include alphabetic
|
||||
* characters
|
||||
* @param numbers if {@code true}, generated string may include numeric
|
||||
* characters
|
||||
* @param chars the set of chars to choose randoms from, must not be empty. If
|
||||
* {@code null}, then it will use the set of all chars.
|
||||
* @param random a source of randomness.
|
||||
* @return the random string
|
||||
* @throws ArrayIndexOutOfBoundsException if there are not
|
||||
* {@code (end - start) + 1} characters
|
||||
* in the set array.
|
||||
* @throws IllegalArgumentException if {@code count} < 0 or the
|
||||
* provided chars array is empty.
|
||||
* @since 2.0
|
||||
*/
|
||||
public static String random(int count, int start, int end, final boolean letters, final boolean numbers,
|
||||
final char[] chars, final EaglercraftRandom random) {
|
||||
if (count == 0) {
|
||||
return StringUtils.EMPTY;
|
||||
} else if (count < 0) {
|
||||
throw new IllegalArgumentException("Requested random string length " + count + " is less than 0.");
|
||||
}
|
||||
if (chars != null && chars.length == 0) {
|
||||
throw new IllegalArgumentException("The chars array must not be empty");
|
||||
}
|
||||
|
||||
if (start == 0 && end == 0) {
|
||||
if (chars != null) {
|
||||
end = chars.length;
|
||||
} else if (!letters && !numbers) {
|
||||
end = Character.MAX_CODE_POINT;
|
||||
} else {
|
||||
end = 'z' + 1;
|
||||
start = ' ';
|
||||
}
|
||||
} else if (end <= start) {
|
||||
throw new IllegalArgumentException(
|
||||
"Parameter end (" + end + ") must be greater than start (" + start + ")");
|
||||
}
|
||||
|
||||
final int zero_digit_ascii = 48;
|
||||
final int first_letter_ascii = 65;
|
||||
|
||||
if (chars == null && (numbers && end <= zero_digit_ascii || letters && end <= first_letter_ascii)) {
|
||||
throw new IllegalArgumentException(
|
||||
"Parameter end (" + end + ") must be greater then (" + zero_digit_ascii + ") for generating digits "
|
||||
+ "or greater then (" + first_letter_ascii + ") for generating letters.");
|
||||
}
|
||||
|
||||
final StringBuilder builder = new StringBuilder(count);
|
||||
final int gap = end - start;
|
||||
|
||||
while (count-- != 0) {
|
||||
final int codePoint;
|
||||
if (chars == null) {
|
||||
codePoint = random.nextInt(gap) + start;
|
||||
|
||||
switch (Character.getType(codePoint)) {
|
||||
case Character.UNASSIGNED:
|
||||
case Character.PRIVATE_USE:
|
||||
case Character.SURROGATE:
|
||||
count++;
|
||||
continue;
|
||||
}
|
||||
|
||||
} else {
|
||||
codePoint = chars[random.nextInt(gap) + start];
|
||||
}
|
||||
|
||||
final int numberOfChars = Character.charCount(codePoint);
|
||||
if (count == 0 && numberOfChars > 1) {
|
||||
count++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (letters && Character.isLetter(codePoint) || numbers && Character.isDigit(codePoint)
|
||||
|| !letters && !numbers) {
|
||||
builder.appendCodePoint(codePoint);
|
||||
|
||||
if (numberOfChars == 2) {
|
||||
count--;
|
||||
}
|
||||
|
||||
} else {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a random string whose length is the number of characters specified.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Characters will be chosen from the set of characters specified by the string,
|
||||
* must not be empty. If null, the set of all characters is used.
|
||||
* </p>
|
||||
*
|
||||
* @param count the length of random string to create
|
||||
* @param chars the String containing the set of characters to use, may be null,
|
||||
* but must not be empty
|
||||
* @return the random string
|
||||
* @throws IllegalArgumentException if {@code count} < 0 or the string is
|
||||
* empty.
|
||||
*/
|
||||
public static String random(final int count, final String chars) {
|
||||
if (chars == null) {
|
||||
return random(count, 0, 0, false, false, null, RANDOM);
|
||||
}
|
||||
return random(count, chars.toCharArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a random string whose length is the number of characters specified.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Characters will be chosen from the set of characters specified.
|
||||
* </p>
|
||||
*
|
||||
* @param count the length of random string to create
|
||||
* @param chars the character array containing the set of characters to use, may
|
||||
* be null
|
||||
* @return the random string
|
||||
* @throws IllegalArgumentException if {@code count} < 0.
|
||||
*/
|
||||
public static String random(final int count, final char... chars) {
|
||||
if (chars == null) {
|
||||
return random(count, 0, 0, false, false, null, RANDOM);
|
||||
}
|
||||
return random(count, 0, chars.length, false, false, chars, RANDOM);
|
||||
}
|
||||
|
||||
}
|
255
sources/main/java/org/apache/commons/lang3/RandomUtils.java
Normal file
255
sources/main/java/org/apache/commons/lang3/RandomUtils.java
Normal file
@ -0,0 +1,255 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Utility library that supplements the standard {@link EaglercraftRandom} class.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Caveat: Instances of {@link EaglercraftRandom} are not cryptographically secure.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Please note that the Apache Commons project provides a component dedicated to
|
||||
* pseudo-random number generation, namely
|
||||
* <a href="https://commons.apache.org/rng">Commons RNG</a>, that may be a
|
||||
* better choice for applications with more stringent requirements (performance
|
||||
* and/or correctness).
|
||||
* </p>
|
||||
*
|
||||
* @since 3.3
|
||||
*/
|
||||
public class RandomUtils {
|
||||
|
||||
/**
|
||||
* Random object used by random method. This has to be not local to the random
|
||||
* method so as to not return the same value in the same millisecond.
|
||||
*/
|
||||
private static final EaglercraftRandom RANDOM = new EaglercraftRandom();
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* {@code RandomUtils} instances should NOT be constructed in standard
|
||||
* programming. Instead, the class should be used as
|
||||
* {@code RandomUtils.nextBytes(5);}.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This constructor is public to permit tools that require a JavaBean instance
|
||||
* to operate.
|
||||
* </p>
|
||||
*/
|
||||
public RandomUtils() {
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Returns a random boolean value
|
||||
* </p>
|
||||
*
|
||||
* @return the random boolean
|
||||
* @since 3.5
|
||||
*/
|
||||
public static boolean nextBoolean() {
|
||||
return RANDOM.nextBoolean();
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates an array of random bytes.
|
||||
* </p>
|
||||
*
|
||||
* @param count the size of the returned array
|
||||
* @return the random byte array
|
||||
* @throws IllegalArgumentException if {@code count} is negative
|
||||
*/
|
||||
public static byte[] nextBytes(final int count) {
|
||||
Validate.isTrue(count >= 0, "Count cannot be negative.");
|
||||
|
||||
final byte[] result = new byte[count];
|
||||
RANDOM.nextBytes(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Returns a random integer within the specified range.
|
||||
* </p>
|
||||
*
|
||||
* @param startInclusive the smallest value that can be returned, must be
|
||||
* non-negative
|
||||
* @param endExclusive the upper bound (not included)
|
||||
* @throws IllegalArgumentException if {@code startInclusive > endExclusive} or
|
||||
* if {@code startInclusive} is negative
|
||||
* @return the random integer
|
||||
*/
|
||||
public static int nextInt(final int startInclusive, final int endExclusive) {
|
||||
Validate.isTrue(endExclusive >= startInclusive, "Start value must be smaller or equal to end value.");
|
||||
Validate.isTrue(startInclusive >= 0, "Both range values must be non-negative.");
|
||||
|
||||
if (startInclusive == endExclusive) {
|
||||
return startInclusive;
|
||||
}
|
||||
|
||||
return startInclusive + RANDOM.nextInt(endExclusive - startInclusive);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Returns a random int within 0 - Integer.MAX_VALUE
|
||||
* </p>
|
||||
*
|
||||
* @return the random integer
|
||||
* @see #nextInt(int, int)
|
||||
* @since 3.5
|
||||
*/
|
||||
public static int nextInt() {
|
||||
return nextInt(0, Integer.MAX_VALUE);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Returns a random long within the specified range.
|
||||
* </p>
|
||||
*
|
||||
* @param startInclusive the smallest value that can be returned, must be
|
||||
* non-negative
|
||||
* @param endExclusive the upper bound (not included)
|
||||
* @throws IllegalArgumentException if {@code startInclusive > endExclusive} or
|
||||
* if {@code startInclusive} is negative
|
||||
* @return the random long
|
||||
*/
|
||||
public static long nextLong(final long startInclusive, final long endExclusive) {
|
||||
Validate.isTrue(endExclusive >= startInclusive, "Start value must be smaller or equal to end value.");
|
||||
Validate.isTrue(startInclusive >= 0, "Both range values must be non-negative.");
|
||||
|
||||
if (startInclusive == endExclusive) {
|
||||
return startInclusive;
|
||||
}
|
||||
|
||||
return startInclusive + nextLong(endExclusive - startInclusive);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Returns a random long within 0 - Long.MAX_VALUE
|
||||
* </p>
|
||||
*
|
||||
* @return the random long
|
||||
* @see #nextLong(long, long)
|
||||
* @since 3.5
|
||||
*/
|
||||
public static long nextLong() {
|
||||
return nextLong(Long.MAX_VALUE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a {@code long} value between 0 (inclusive) and the specified value
|
||||
* (exclusive).
|
||||
*
|
||||
* @param n Bound on the random number to be returned. Must be positive.
|
||||
* @return a random {@code long} value between 0 (inclusive) and {@code n}
|
||||
* (exclusive).
|
||||
*/
|
||||
private static long nextLong(final long n) {
|
||||
// Extracted from o.a.c.rng.core.BaseProvider.nextLong(long)
|
||||
long bits;
|
||||
long val;
|
||||
do {
|
||||
bits = RANDOM.nextLong() >>> 1;
|
||||
val = bits % n;
|
||||
} while (bits - val + (n - 1) < 0);
|
||||
|
||||
return val;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Returns a random double within the specified range.
|
||||
* </p>
|
||||
*
|
||||
* @param startInclusive the smallest value that can be returned, must be
|
||||
* non-negative
|
||||
* @param endExclusive the upper bound (not included)
|
||||
* @throws IllegalArgumentException if {@code startInclusive > endExclusive} or
|
||||
* if {@code startInclusive} is negative
|
||||
* @return the random double
|
||||
*/
|
||||
public static double nextDouble(final double startInclusive, final double endExclusive) {
|
||||
Validate.isTrue(endExclusive >= startInclusive, "Start value must be smaller or equal to end value.");
|
||||
Validate.isTrue(startInclusive >= 0, "Both range values must be non-negative.");
|
||||
|
||||
if (startInclusive == endExclusive) {
|
||||
return startInclusive;
|
||||
}
|
||||
|
||||
return startInclusive + ((endExclusive - startInclusive) * RANDOM.nextDouble());
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Returns a random double within 0 - Double.MAX_VALUE
|
||||
* </p>
|
||||
*
|
||||
* @return the random double
|
||||
* @see #nextDouble(double, double)
|
||||
* @since 3.5
|
||||
*/
|
||||
public static double nextDouble() {
|
||||
return nextDouble(0, Double.MAX_VALUE);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Returns a random float within the specified range.
|
||||
* </p>
|
||||
*
|
||||
* @param startInclusive the smallest value that can be returned, must be
|
||||
* non-negative
|
||||
* @param endExclusive the upper bound (not included)
|
||||
* @throws IllegalArgumentException if {@code startInclusive > endExclusive} or
|
||||
* if {@code startInclusive} is negative
|
||||
* @return the random float
|
||||
*/
|
||||
public static float nextFloat(final float startInclusive, final float endExclusive) {
|
||||
Validate.isTrue(endExclusive >= startInclusive, "Start value must be smaller or equal to end value.");
|
||||
Validate.isTrue(startInclusive >= 0, "Both range values must be non-negative.");
|
||||
|
||||
if (startInclusive == endExclusive) {
|
||||
return startInclusive;
|
||||
}
|
||||
|
||||
return startInclusive + ((endExclusive - startInclusive) * RANDOM.nextFloat());
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Returns a random float within 0 - Float.MAX_VALUE
|
||||
* </p>
|
||||
*
|
||||
* @return the random float
|
||||
* @see #nextFloat(float, float)
|
||||
* @since 3.5
|
||||
*/
|
||||
public static float nextFloat() {
|
||||
return nextFloat(0, Float.MAX_VALUE);
|
||||
}
|
||||
}
|
616
sources/main/java/org/apache/commons/lang3/Range.java
Normal file
616
sources/main/java/org/apache/commons/lang3/Range.java
Normal file
@ -0,0 +1,616 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Comparator;
|
||||
|
||||
import net.lax1dude.eaglercraft.v1_8.HString;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* An immutable range of objects from a minimum to maximum point inclusive.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The objects need to either be implementations of {@code Comparable} or you
|
||||
* need to supply a {@code Comparator}.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* #ThreadSafe# if the objects and comparator are thread-safe
|
||||
* </p>
|
||||
*
|
||||
* @param <T> The type of range values.
|
||||
* @since 3.0
|
||||
*/
|
||||
public final class Range<T> implements Serializable {
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
private enum ComparableComparator implements Comparator {
|
||||
INSTANCE;
|
||||
|
||||
/**
|
||||
* Comparable based compare implementation.
|
||||
*
|
||||
* @param obj1 left hand side of comparison
|
||||
* @param obj2 right hand side of comparison
|
||||
* @return negative, 0, positive comparison value
|
||||
*/
|
||||
@Override
|
||||
public int compare(final Object obj1, final Object obj2) {
|
||||
return ((Comparable) obj1).compareTo(obj2);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialization version.
|
||||
*
|
||||
* @see java.io.Serializable
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Obtains a range with the specified minimum and maximum values (both
|
||||
* inclusive).
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The range uses the natural ordering of the elements to determine where values
|
||||
* lie in the range.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The arguments may be passed in the order (min,max) or (max,min). The
|
||||
* getMinimum and getMaximum methods will return the correct values.
|
||||
* </p>
|
||||
*
|
||||
* @param <T> the type of the elements in this range
|
||||
* @param fromInclusive the first value that defines the edge of the range,
|
||||
* inclusive
|
||||
* @param toInclusive the second value that defines the edge of the range,
|
||||
* inclusive
|
||||
* @return the range object, not null
|
||||
* @throws IllegalArgumentException if either element is null
|
||||
* @throws ClassCastException if the elements are not {@code Comparable}
|
||||
*/
|
||||
public static <T extends Comparable<T>> Range<T> between(final T fromInclusive, final T toInclusive) {
|
||||
return between(fromInclusive, toInclusive, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Obtains a range with the specified minimum and maximum values (both
|
||||
* inclusive).
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The range uses the specified {@code Comparator} to determine where values lie
|
||||
* in the range.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The arguments may be passed in the order (min,max) or (max,min). The
|
||||
* getMinimum and getMaximum methods will return the correct values.
|
||||
* </p>
|
||||
*
|
||||
* @param <T> the type of the elements in this range
|
||||
* @param fromInclusive the first value that defines the edge of the range,
|
||||
* inclusive
|
||||
* @param toInclusive the second value that defines the edge of the range,
|
||||
* inclusive
|
||||
* @param comparator the comparator to be used, null for natural ordering
|
||||
* @return the range object, not null
|
||||
* @throws IllegalArgumentException if either element is null
|
||||
* @throws ClassCastException if using natural ordering and the elements
|
||||
* are not {@code Comparable}
|
||||
*/
|
||||
public static <T> Range<T> between(final T fromInclusive, final T toInclusive, final Comparator<T> comparator) {
|
||||
return new Range<>(fromInclusive, toInclusive, comparator);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Obtains a range using the specified element as both the minimum and maximum
|
||||
* in this range.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The range uses the natural ordering of the elements to determine where values
|
||||
* lie in the range.
|
||||
* </p>
|
||||
*
|
||||
* @param <T> the type of the elements in this range
|
||||
* @param element the value to use for this range, not null
|
||||
* @return the range object, not null
|
||||
* @throws IllegalArgumentException if the element is null
|
||||
* @throws ClassCastException if the element is not {@code Comparable}
|
||||
*/
|
||||
public static <T extends Comparable<T>> Range<T> is(final T element) {
|
||||
return between(element, element, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Obtains a range using the specified element as both the minimum and maximum
|
||||
* in this range.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The range uses the specified {@code Comparator} to determine where values lie
|
||||
* in the range.
|
||||
* </p>
|
||||
*
|
||||
* @param <T> the type of the elements in this range
|
||||
* @param element the value to use for this range, must not be {@code null}
|
||||
* @param comparator the comparator to be used, null for natural ordering
|
||||
* @return the range object, not null
|
||||
* @throws IllegalArgumentException if the element is null
|
||||
* @throws ClassCastException if using natural ordering and the elements
|
||||
* are not {@code Comparable}
|
||||
*/
|
||||
public static <T> Range<T> is(final T element, final Comparator<T> comparator) {
|
||||
return between(element, element, comparator);
|
||||
}
|
||||
|
||||
/**
|
||||
* The ordering scheme used in this range.
|
||||
*/
|
||||
private final Comparator<T> comparator;
|
||||
|
||||
/**
|
||||
* Cached output hashCode (class is immutable).
|
||||
*/
|
||||
private transient int hashCode;
|
||||
|
||||
/**
|
||||
* The maximum value in this range (inclusive).
|
||||
*/
|
||||
private final T maximum;
|
||||
|
||||
/**
|
||||
* The minimum value in this range (inclusive).
|
||||
*/
|
||||
private final T minimum;
|
||||
|
||||
/**
|
||||
* Cached output toString (class is immutable).
|
||||
*/
|
||||
private transient String toString;
|
||||
|
||||
/**
|
||||
* Creates an instance.
|
||||
*
|
||||
* @param element1 the first element, not null
|
||||
* @param element2 the second element, not null
|
||||
* @param comp the comparator to be used, null for natural ordering
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private Range(final T element1, final T element2, final Comparator<T> comp) {
|
||||
if (element1 == null || element2 == null) {
|
||||
throw new IllegalArgumentException(
|
||||
"Elements in a range must not be null: element1=" + element1 + ", element2=" + element2);
|
||||
}
|
||||
if (comp == null) {
|
||||
this.comparator = ComparableComparator.INSTANCE;
|
||||
} else {
|
||||
this.comparator = comp;
|
||||
}
|
||||
if (this.comparator.compare(element1, element2) < 1) {
|
||||
this.minimum = element1;
|
||||
this.maximum = element2;
|
||||
} else {
|
||||
this.minimum = element2;
|
||||
this.maximum = element1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Checks whether the specified element occurs within this range.
|
||||
* </p>
|
||||
*
|
||||
* @param element the element to check for, null returns false
|
||||
* @return true if the specified element occurs within this range
|
||||
*/
|
||||
public boolean contains(final T element) {
|
||||
if (element == null) {
|
||||
return false;
|
||||
}
|
||||
return comparator.compare(element, minimum) > -1 && comparator.compare(element, maximum) < 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Checks whether this range contains all the elements of the specified range.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method may fail if the ranges have two different comparators or element
|
||||
* types.
|
||||
* </p>
|
||||
*
|
||||
* @param otherRange the range to check, null returns false
|
||||
* @return true if this range contains the specified range
|
||||
* @throws RuntimeException if ranges cannot be compared
|
||||
*/
|
||||
public boolean containsRange(final Range<T> otherRange) {
|
||||
if (otherRange == null) {
|
||||
return false;
|
||||
}
|
||||
return contains(otherRange.minimum) && contains(otherRange.maximum);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Checks where the specified element occurs relative to this range.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The API is reminiscent of the Comparable interface returning {@code -1} if
|
||||
* the element is before the range, {@code 0} if contained within the range and
|
||||
* {@code 1} if the element is after the range.
|
||||
* </p>
|
||||
*
|
||||
* @param element the element to check for, not null
|
||||
* @return -1, 0 or +1 depending on the element's location relative to the range
|
||||
*/
|
||||
public int elementCompareTo(final T element) {
|
||||
// Comparable API says throw NPE on null
|
||||
Validate.notNull(element, "element");
|
||||
if (isAfter(element)) {
|
||||
return -1;
|
||||
} else if (isBefore(element)) {
|
||||
return 1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Element tests
|
||||
// --------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Compares this range to another object to test if they are equal.
|
||||
* </p>
|
||||
* .
|
||||
*
|
||||
* <p>
|
||||
* To be equal, the minimum and maximum values must be equal, which ignores any
|
||||
* differences in the comparator.
|
||||
* </p>
|
||||
*
|
||||
* @param obj the reference object with which to compare
|
||||
* @return true if this object is equal
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (obj == this) {
|
||||
return true;
|
||||
} else if (obj == null || obj.getClass() != getClass()) {
|
||||
return false;
|
||||
} else {
|
||||
@SuppressWarnings("unchecked") // OK because we checked the class above
|
||||
final Range<T> range = (Range<T>) obj;
|
||||
return minimum.equals(range.minimum) && maximum.equals(range.maximum);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets the comparator being used to determine if objects are within the range.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Natural ordering uses an internal comparator implementation, thus this method
|
||||
* never returns null. See {@link #isNaturalOrdering()}.
|
||||
* </p>
|
||||
*
|
||||
* @return the comparator being used, not null
|
||||
*/
|
||||
public Comparator<T> getComparator() {
|
||||
return comparator;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets the maximum value in this range.
|
||||
* </p>
|
||||
*
|
||||
* @return the maximum value in this range, not null
|
||||
*/
|
||||
public T getMaximum() {
|
||||
return maximum;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets the minimum value in this range.
|
||||
* </p>
|
||||
*
|
||||
* @return the minimum value in this range, not null
|
||||
*/
|
||||
public T getMinimum() {
|
||||
return minimum;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets a suitable hash code for the range.
|
||||
* </p>
|
||||
*
|
||||
* @return a hash code value for this object
|
||||
*/
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = hashCode;
|
||||
if (hashCode == 0) {
|
||||
result = 17;
|
||||
result = 37 * result + getClass().hashCode();
|
||||
result = 37 * result + minimum.hashCode();
|
||||
result = 37 * result + maximum.hashCode();
|
||||
hashCode = result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the intersection of {@code this} and an overlapping Range.
|
||||
*
|
||||
* @param other overlapping Range
|
||||
* @return range representing the intersection of {@code this} and {@code other}
|
||||
* ({@code this} if equal)
|
||||
* @throws IllegalArgumentException if {@code other} does not overlap
|
||||
* {@code this}
|
||||
* @since 3.0.1
|
||||
*/
|
||||
public Range<T> intersectionWith(final Range<T> other) {
|
||||
if (!this.isOverlappedBy(other)) {
|
||||
throw new IllegalArgumentException(
|
||||
HString.format("Cannot calculate intersection with non-overlapping range %s", other));
|
||||
}
|
||||
if (this.equals(other)) {
|
||||
return this;
|
||||
}
|
||||
final T min = getComparator().compare(minimum, other.minimum) < 0 ? other.minimum : minimum;
|
||||
final T max = getComparator().compare(maximum, other.maximum) < 0 ? maximum : other.maximum;
|
||||
return between(min, max, getComparator());
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Checks whether this range is after the specified element.
|
||||
* </p>
|
||||
*
|
||||
* @param element the element to check for, null returns false
|
||||
* @return true if this range is entirely after the specified element
|
||||
*/
|
||||
public boolean isAfter(final T element) {
|
||||
if (element == null) {
|
||||
return false;
|
||||
}
|
||||
return comparator.compare(element, minimum) < 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Checks whether this range is completely after the specified range.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method may fail if the ranges have two different comparators or element
|
||||
* types.
|
||||
* </p>
|
||||
*
|
||||
* @param otherRange the range to check, null returns false
|
||||
* @return true if this range is completely after the specified range
|
||||
* @throws RuntimeException if ranges cannot be compared
|
||||
*/
|
||||
public boolean isAfterRange(final Range<T> otherRange) {
|
||||
if (otherRange == null) {
|
||||
return false;
|
||||
}
|
||||
return isAfter(otherRange.maximum);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Checks whether this range is before the specified element.
|
||||
* </p>
|
||||
*
|
||||
* @param element the element to check for, null returns false
|
||||
* @return true if this range is entirely before the specified element
|
||||
*/
|
||||
public boolean isBefore(final T element) {
|
||||
if (element == null) {
|
||||
return false;
|
||||
}
|
||||
return comparator.compare(element, maximum) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Checks whether this range is completely before the specified range.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method may fail if the ranges have two different comparators or element
|
||||
* types.
|
||||
* </p>
|
||||
*
|
||||
* @param otherRange the range to check, null returns false
|
||||
* @return true if this range is completely before the specified range
|
||||
* @throws RuntimeException if ranges cannot be compared
|
||||
*/
|
||||
public boolean isBeforeRange(final Range<T> otherRange) {
|
||||
if (otherRange == null) {
|
||||
return false;
|
||||
}
|
||||
return isBefore(otherRange.minimum);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Checks whether this range ends with the specified element.
|
||||
* </p>
|
||||
*
|
||||
* @param element the element to check for, null returns false
|
||||
* @return true if the specified element occurs within this range
|
||||
*/
|
||||
public boolean isEndedBy(final T element) {
|
||||
if (element == null) {
|
||||
return false;
|
||||
}
|
||||
return comparator.compare(element, maximum) == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Whether or not the Range is using the natural ordering of the elements.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Natural ordering uses an internal comparator implementation, thus this method
|
||||
* is the only way to check if a null comparator was specified.
|
||||
* </p>
|
||||
*
|
||||
* @return true if using natural ordering
|
||||
*/
|
||||
public boolean isNaturalOrdering() {
|
||||
return comparator == ComparableComparator.INSTANCE;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Checks whether this range is overlapped by the specified range.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Two ranges overlap if there is at least one element in common.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This method may fail if the ranges have two different comparators or element
|
||||
* types.
|
||||
* </p>
|
||||
*
|
||||
* @param otherRange the range to test, null returns false
|
||||
* @return true if the specified range overlaps with this range; otherwise,
|
||||
* {@code false}
|
||||
* @throws RuntimeException if ranges cannot be compared
|
||||
*/
|
||||
public boolean isOverlappedBy(final Range<T> otherRange) {
|
||||
if (otherRange == null) {
|
||||
return false;
|
||||
}
|
||||
return otherRange.contains(minimum) || otherRange.contains(maximum) || contains(otherRange.minimum);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Checks whether this range starts with the specified element.
|
||||
* </p>
|
||||
*
|
||||
* @param element the element to check for, null returns false
|
||||
* @return true if the specified element occurs within this range
|
||||
*/
|
||||
public boolean isStartedBy(final T element) {
|
||||
if (element == null) {
|
||||
return false;
|
||||
}
|
||||
return comparator.compare(element, minimum) == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Fits the given element into this range by returning the given element or, if
|
||||
* out of bounds, the range minimum if below, or the range maximum if above.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* Range<Integer> range = Range.between(16, 64);
|
||||
* range.fit(-9) --> 16
|
||||
* range.fit(0) --> 16
|
||||
* range.fit(15) --> 16
|
||||
* range.fit(16) --> 16
|
||||
* range.fit(17) --> 17
|
||||
* ...
|
||||
* range.fit(63) --> 63
|
||||
* range.fit(64) --> 64
|
||||
* range.fit(99) --> 64
|
||||
* </pre>
|
||||
*
|
||||
* @param element the element to check for, not null
|
||||
* @return the minimum, the element, or the maximum depending on the element's
|
||||
* location relative to the range
|
||||
* @since 3.10
|
||||
*/
|
||||
public T fit(final T element) {
|
||||
// Comparable API says throw NPE on null
|
||||
Validate.notNull(element, "element");
|
||||
if (isAfter(element)) {
|
||||
return minimum;
|
||||
} else if (isBefore(element)) {
|
||||
return maximum;
|
||||
} else {
|
||||
return element;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets the range as a {@code String}.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The format of the String is '[<i>min</i>..<i>max</i>]'.
|
||||
* </p>
|
||||
*
|
||||
* @return the {@code String} representation of this range
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
if (toString == null) {
|
||||
toString = "[" + minimum + ".." + maximum + "]";
|
||||
}
|
||||
return toString;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Formats the receiver using the given format.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This uses {@link java.util.Formattable} to perform the formatting. Three
|
||||
* variables may be used to embed the minimum, maximum and comparator. Use
|
||||
* {@code %1$s} for the minimum element, {@code %2$s} for the maximum element
|
||||
* and {@code %3$s} for the comparator. The default format used by
|
||||
* {@code toString()} is {@code [%1$s..%2$s]}.
|
||||
* </p>
|
||||
*
|
||||
* @param format the format string, optionally containing {@code %1$s},
|
||||
* {@code %2$s} and {@code %3$s}, not null
|
||||
* @return the formatted string, not null
|
||||
*/
|
||||
public String toString(final String format) {
|
||||
return HString.format(format, minimum, maximum, comparator);
|
||||
}
|
||||
|
||||
}
|
517
sources/main/java/org/apache/commons/lang3/RegExUtils.java
Normal file
517
sources/main/java/org/apache/commons/lang3/RegExUtils.java
Normal file
@ -0,0 +1,517 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Helpers to process Strings using regular expressions.
|
||||
* </p>
|
||||
*
|
||||
* @see java.util.regex.Pattern
|
||||
* @since 3.8
|
||||
*/
|
||||
public class RegExUtils {
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Removes each substring of the text String that matches the given regular
|
||||
* expression pattern.
|
||||
* </p>
|
||||
*
|
||||
* This method is a {@code null} safe equivalent to:
|
||||
* <ul>
|
||||
* <li>{@code pattern.matcher(text).replaceAll(StringUtils.EMPTY)}</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>
|
||||
* A {@code null} reference passed to this method is a no-op.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* StringUtils.removeAll(null, *) = null
|
||||
* StringUtils.removeAll("any", (Pattern) null) = "any"
|
||||
* StringUtils.removeAll("any", Pattern.compile("")) = "any"
|
||||
* StringUtils.removeAll("any", Pattern.compile(".*")) = ""
|
||||
* StringUtils.removeAll("any", Pattern.compile(".+")) = ""
|
||||
* StringUtils.removeAll("abc", Pattern.compile(".?")) = ""
|
||||
* StringUtils.removeAll("A<__>\n<__>B", Pattern.compile("<.*>")) = "A\nB"
|
||||
* StringUtils.removeAll("A<__>\n<__>B", Pattern.compile("(?s)<.*>")) = "AB"
|
||||
* StringUtils.removeAll("A<__>\n<__>B", Pattern.compile("<.*>", Pattern.DOTALL)) = "AB"
|
||||
* StringUtils.removeAll("ABCabc123abc", Pattern.compile("[a-z]")) = "ABC123"
|
||||
* </pre>
|
||||
*
|
||||
* @param text text to remove from, may be null
|
||||
* @param regex the regular expression to which this string is to be matched
|
||||
* @return the text with any removes processed, {@code null} if null String
|
||||
* input
|
||||
*
|
||||
* @see #replaceAll(String, Pattern, String)
|
||||
* @see java.util.regex.Matcher#replaceAll(String)
|
||||
* @see java.util.regex.Pattern
|
||||
*/
|
||||
public static String removeAll(final String text, final Pattern regex) {
|
||||
return replaceAll(text, regex, StringUtils.EMPTY);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Removes each substring of the text String that matches the given regular
|
||||
* expression.
|
||||
* </p>
|
||||
*
|
||||
* This method is a {@code null} safe equivalent to:
|
||||
* <ul>
|
||||
* <li>{@code text.replaceAll(regex, StringUtils.EMPTY)}</li>
|
||||
* <li>{@code Pattern.compile(regex).matcher(text).replaceAll(StringUtils.EMPTY)}</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>
|
||||
* A {@code null} reference passed to this method is a no-op.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Unlike in the {@link #removePattern(String, String)} method, the
|
||||
* {@link Pattern#DOTALL} option is NOT automatically added. To use the DOTALL
|
||||
* option prepend {@code "(?s)"} to the regex. DOTALL is also known as
|
||||
* single-line mode in Perl.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* StringUtils.removeAll(null, *) = null
|
||||
* StringUtils.removeAll("any", (String) null) = "any"
|
||||
* StringUtils.removeAll("any", "") = "any"
|
||||
* StringUtils.removeAll("any", ".*") = ""
|
||||
* StringUtils.removeAll("any", ".+") = ""
|
||||
* StringUtils.removeAll("abc", ".?") = ""
|
||||
* StringUtils.removeAll("A<__>\n<__>B", "<.*>") = "A\nB"
|
||||
* StringUtils.removeAll("A<__>\n<__>B", "(?s)<.*>") = "AB"
|
||||
* StringUtils.removeAll("ABCabc123abc", "[a-z]") = "ABC123"
|
||||
* </pre>
|
||||
*
|
||||
* @param text text to remove from, may be null
|
||||
* @param regex the regular expression to which this string is to be matched
|
||||
* @return the text with any removes processed, {@code null} if null String
|
||||
* input
|
||||
*
|
||||
* @throws java.util.regex.PatternSyntaxException if the regular expression's
|
||||
* syntax is invalid
|
||||
*
|
||||
* @see #replaceAll(String, String, String)
|
||||
* @see #removePattern(String, String)
|
||||
* @see String#replaceAll(String, String)
|
||||
* @see java.util.regex.Pattern
|
||||
* @see java.util.regex.Pattern#DOTALL
|
||||
*/
|
||||
public static String removeAll(final String text, final String regex) {
|
||||
return replaceAll(text, regex, StringUtils.EMPTY);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Removes the first substring of the text string that matches the given regular
|
||||
* expression pattern.
|
||||
* </p>
|
||||
*
|
||||
* This method is a {@code null} safe equivalent to:
|
||||
* <ul>
|
||||
* <li>{@code pattern.matcher(text).replaceFirst(StringUtils.EMPTY)}</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>
|
||||
* A {@code null} reference passed to this method is a no-op.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* StringUtils.removeFirst(null, *) = null
|
||||
* StringUtils.removeFirst("any", (Pattern) null) = "any"
|
||||
* StringUtils.removeFirst("any", Pattern.compile("")) = "any"
|
||||
* StringUtils.removeFirst("any", Pattern.compile(".*")) = ""
|
||||
* StringUtils.removeFirst("any", Pattern.compile(".+")) = ""
|
||||
* StringUtils.removeFirst("abc", Pattern.compile(".?")) = "bc"
|
||||
* StringUtils.removeFirst("A<__>\n<__>B", Pattern.compile("<.*>")) = "A\n<__>B"
|
||||
* StringUtils.removeFirst("A<__>\n<__>B", Pattern.compile("(?s)<.*>")) = "AB"
|
||||
* StringUtils.removeFirst("ABCabc123", Pattern.compile("[a-z]")) = "ABCbc123"
|
||||
* StringUtils.removeFirst("ABCabc123abc", Pattern.compile("[a-z]+")) = "ABC123abc"
|
||||
* </pre>
|
||||
*
|
||||
* @param text text to remove from, may be null
|
||||
* @param regex the regular expression pattern to which this string is to be
|
||||
* matched
|
||||
* @return the text with the first replacement processed, {@code null} if null
|
||||
* String input
|
||||
*
|
||||
* @see #replaceFirst(String, Pattern, String)
|
||||
* @see java.util.regex.Matcher#replaceFirst(String)
|
||||
* @see java.util.regex.Pattern
|
||||
*/
|
||||
public static String removeFirst(final String text, final Pattern regex) {
|
||||
return replaceFirst(text, regex, StringUtils.EMPTY);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Removes the first substring of the text string that matches the given regular
|
||||
* expression.
|
||||
* </p>
|
||||
*
|
||||
* This method is a {@code null} safe equivalent to:
|
||||
* <ul>
|
||||
* <li>{@code text.replaceFirst(regex, StringUtils.EMPTY)}</li>
|
||||
* <li>{@code Pattern.compile(regex).matcher(text).replaceFirst(StringUtils.EMPTY)}</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>
|
||||
* A {@code null} reference passed to this method is a no-op.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The {@link Pattern#DOTALL} option is NOT automatically added. To use the
|
||||
* DOTALL option prepend {@code "(?s)"} to the regex. DOTALL is also known as
|
||||
* single-line mode in Perl.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* StringUtils.removeFirst(null, *) = null
|
||||
* StringUtils.removeFirst("any", (String) null) = "any"
|
||||
* StringUtils.removeFirst("any", "") = "any"
|
||||
* StringUtils.removeFirst("any", ".*") = ""
|
||||
* StringUtils.removeFirst("any", ".+") = ""
|
||||
* StringUtils.removeFirst("abc", ".?") = "bc"
|
||||
* StringUtils.removeFirst("A<__>\n<__>B", "<.*>") = "A\n<__>B"
|
||||
* StringUtils.removeFirst("A<__>\n<__>B", "(?s)<.*>") = "AB"
|
||||
* StringUtils.removeFirst("ABCabc123", "[a-z]") = "ABCbc123"
|
||||
* StringUtils.removeFirst("ABCabc123abc", "[a-z]+") = "ABC123abc"
|
||||
* </pre>
|
||||
*
|
||||
* @param text text to remove from, may be null
|
||||
* @param regex the regular expression to which this string is to be matched
|
||||
* @return the text with the first replacement processed, {@code null} if null
|
||||
* String input
|
||||
*
|
||||
* @throws java.util.regex.PatternSyntaxException if the regular expression's
|
||||
* syntax is invalid
|
||||
*
|
||||
* @see #replaceFirst(String, String, String)
|
||||
* @see String#replaceFirst(String, String)
|
||||
* @see java.util.regex.Pattern
|
||||
* @see java.util.regex.Pattern#DOTALL
|
||||
*/
|
||||
public static String removeFirst(final String text, final String regex) {
|
||||
return replaceFirst(text, regex, StringUtils.EMPTY);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Removes each substring of the source String that matches the given regular
|
||||
* expression using the DOTALL option.
|
||||
* </p>
|
||||
*
|
||||
* This call is a {@code null} safe equivalent to:
|
||||
* <ul>
|
||||
* <li>{@code text.replaceAll("(?s)" + regex, StringUtils.EMPTY)}</li>
|
||||
* <li>{@code Pattern.compile(regex, Pattern.DOTALL).matcher(text).replaceAll(StringUtils.EMPTY)}</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>
|
||||
* A {@code null} reference passed to this method is a no-op.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* StringUtils.removePattern(null, *) = null
|
||||
* StringUtils.removePattern("any", (String) null) = "any"
|
||||
* StringUtils.removePattern("A<__>\n<__>B", "<.*>") = "AB"
|
||||
* StringUtils.removePattern("ABCabc123", "[a-z]") = "ABC123"
|
||||
* </pre>
|
||||
*
|
||||
* @param text the source string
|
||||
* @param regex the regular expression to which this string is to be matched
|
||||
* @return The resulting {@code String}
|
||||
* @see #replacePattern(String, String, String)
|
||||
* @see String#replaceAll(String, String)
|
||||
* @see Pattern#DOTALL
|
||||
*/
|
||||
public static String removePattern(final String text, final String regex) {
|
||||
return replacePattern(text, regex, StringUtils.EMPTY);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Replaces each substring of the text String that matches the given regular
|
||||
* expression pattern with the given replacement.
|
||||
* </p>
|
||||
*
|
||||
* This method is a {@code null} safe equivalent to:
|
||||
* <ul>
|
||||
* <li>{@code pattern.matcher(text).replaceAll(replacement)}</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>
|
||||
* A {@code null} reference passed to this method is a no-op.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* StringUtils.replaceAll(null, *, *) = null
|
||||
* StringUtils.replaceAll("any", (Pattern) null, *) = "any"
|
||||
* StringUtils.replaceAll("any", *, null) = "any"
|
||||
* StringUtils.replaceAll("", Pattern.compile(""), "zzz") = "zzz"
|
||||
* StringUtils.replaceAll("", Pattern.compile(".*"), "zzz") = "zzz"
|
||||
* StringUtils.replaceAll("", Pattern.compile(".+"), "zzz") = ""
|
||||
* StringUtils.replaceAll("abc", Pattern.compile(""), "ZZ") = "ZZaZZbZZcZZ"
|
||||
* StringUtils.replaceAll("<__>\n<__>", Pattern.compile("<.*>"), "z") = "z\nz"
|
||||
* StringUtils.replaceAll("<__>\n<__>", Pattern.compile("<.*>", Pattern.DOTALL), "z") = "z"
|
||||
* StringUtils.replaceAll("<__>\n<__>", Pattern.compile("(?s)<.*>"), "z") = "z"
|
||||
* StringUtils.replaceAll("ABCabc123", Pattern.compile("[a-z]"), "_") = "ABC___123"
|
||||
* StringUtils.replaceAll("ABCabc123", Pattern.compile("[^A-Z0-9]+"), "_") = "ABC_123"
|
||||
* StringUtils.replaceAll("ABCabc123", Pattern.compile("[^A-Z0-9]+"), "") = "ABC123"
|
||||
* StringUtils.replaceAll("Lorem ipsum dolor sit", Pattern.compile("( +)([a-z]+)"), "_$2") = "Lorem_ipsum_dolor_sit"
|
||||
* </pre>
|
||||
*
|
||||
* @param text text to search and replace in, may be null
|
||||
* @param regex the regular expression pattern to which this string is to
|
||||
* be matched
|
||||
* @param replacement the string to be substituted for each match
|
||||
* @return the text with any replacements processed, {@code null} if null String
|
||||
* input
|
||||
*
|
||||
* @see java.util.regex.Matcher#replaceAll(String)
|
||||
* @see java.util.regex.Pattern
|
||||
*/
|
||||
public static String replaceAll(final String text, final Pattern regex, final String replacement) {
|
||||
if (ObjectUtils.anyNull(text, regex, replacement)) {
|
||||
return text;
|
||||
}
|
||||
return regex.matcher(text).replaceAll(replacement);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Replaces each substring of the text String that matches the given regular
|
||||
* expression with the given replacement.
|
||||
* </p>
|
||||
*
|
||||
* This method is a {@code null} safe equivalent to:
|
||||
* <ul>
|
||||
* <li>{@code text.replaceAll(regex, replacement)}</li>
|
||||
* <li>{@code Pattern.compile(regex).matcher(text).replaceAll(replacement)}</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>
|
||||
* A {@code null} reference passed to this method is a no-op.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Unlike in the {@link #replacePattern(String, String, String)} method, the
|
||||
* {@link Pattern#DOTALL} option is NOT automatically added. To use the DOTALL
|
||||
* option prepend {@code "(?s)"} to the regex. DOTALL is also known as
|
||||
* single-line mode in Perl.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* StringUtils.replaceAll(null, *, *) = null
|
||||
* StringUtils.replaceAll("any", (String) null, *) = "any"
|
||||
* StringUtils.replaceAll("any", *, null) = "any"
|
||||
* StringUtils.replaceAll("", "", "zzz") = "zzz"
|
||||
* StringUtils.replaceAll("", ".*", "zzz") = "zzz"
|
||||
* StringUtils.replaceAll("", ".+", "zzz") = ""
|
||||
* StringUtils.replaceAll("abc", "", "ZZ") = "ZZaZZbZZcZZ"
|
||||
* StringUtils.replaceAll("<__>\n<__>", "<.*>", "z") = "z\nz"
|
||||
* StringUtils.replaceAll("<__>\n<__>", "(?s)<.*>", "z") = "z"
|
||||
* StringUtils.replaceAll("ABCabc123", "[a-z]", "_") = "ABC___123"
|
||||
* StringUtils.replaceAll("ABCabc123", "[^A-Z0-9]+", "_") = "ABC_123"
|
||||
* StringUtils.replaceAll("ABCabc123", "[^A-Z0-9]+", "") = "ABC123"
|
||||
* StringUtils.replaceAll("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2") = "Lorem_ipsum_dolor_sit"
|
||||
* </pre>
|
||||
*
|
||||
* @param text text to search and replace in, may be null
|
||||
* @param regex the regular expression to which this string is to be
|
||||
* matched
|
||||
* @param replacement the string to be substituted for each match
|
||||
* @return the text with any replacements processed, {@code null} if null String
|
||||
* input
|
||||
*
|
||||
* @throws java.util.regex.PatternSyntaxException if the regular expression's
|
||||
* syntax is invalid
|
||||
*
|
||||
* @see #replacePattern(String, String, String)
|
||||
* @see String#replaceAll(String, String)
|
||||
* @see java.util.regex.Pattern
|
||||
* @see java.util.regex.Pattern#DOTALL
|
||||
*/
|
||||
public static String replaceAll(final String text, final String regex, final String replacement) {
|
||||
if (ObjectUtils.anyNull(text, regex, replacement)) {
|
||||
return text;
|
||||
}
|
||||
return text.replaceAll(regex, replacement);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Replaces the first substring of the text string that matches the given
|
||||
* regular expression pattern with the given replacement.
|
||||
* </p>
|
||||
*
|
||||
* This method is a {@code null} safe equivalent to:
|
||||
* <ul>
|
||||
* <li>{@code pattern.matcher(text).replaceFirst(replacement)}</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>
|
||||
* A {@code null} reference passed to this method is a no-op.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* StringUtils.replaceFirst(null, *, *) = null
|
||||
* StringUtils.replaceFirst("any", (Pattern) null, *) = "any"
|
||||
* StringUtils.replaceFirst("any", *, null) = "any"
|
||||
* StringUtils.replaceFirst("", Pattern.compile(""), "zzz") = "zzz"
|
||||
* StringUtils.replaceFirst("", Pattern.compile(".*"), "zzz") = "zzz"
|
||||
* StringUtils.replaceFirst("", Pattern.compile(".+"), "zzz") = ""
|
||||
* StringUtils.replaceFirst("abc", Pattern.compile(""), "ZZ") = "ZZabc"
|
||||
* StringUtils.replaceFirst("<__>\n<__>", Pattern.compile("<.*>"), "z") = "z\n<__>"
|
||||
* StringUtils.replaceFirst("<__>\n<__>", Pattern.compile("(?s)<.*>"), "z") = "z"
|
||||
* StringUtils.replaceFirst("ABCabc123", Pattern.compile("[a-z]"), "_") = "ABC_bc123"
|
||||
* StringUtils.replaceFirst("ABCabc123abc", Pattern.compile("[^A-Z0-9]+"), "_") = "ABC_123abc"
|
||||
* StringUtils.replaceFirst("ABCabc123abc", Pattern.compile("[^A-Z0-9]+"), "") = "ABC123abc"
|
||||
* StringUtils.replaceFirst("Lorem ipsum dolor sit", Pattern.compile("( +)([a-z]+)"), "_$2") = "Lorem_ipsum dolor sit"
|
||||
* </pre>
|
||||
*
|
||||
* @param text text to search and replace in, may be null
|
||||
* @param regex the regular expression pattern to which this string is to
|
||||
* be matched
|
||||
* @param replacement the string to be substituted for the first match
|
||||
* @return the text with the first replacement processed, {@code null} if null
|
||||
* String input
|
||||
*
|
||||
* @see java.util.regex.Matcher#replaceFirst(String)
|
||||
* @see java.util.regex.Pattern
|
||||
*/
|
||||
public static String replaceFirst(final String text, final Pattern regex, final String replacement) {
|
||||
if (text == null || regex == null || replacement == null) {
|
||||
return text;
|
||||
}
|
||||
return regex.matcher(text).replaceFirst(replacement);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Replaces the first substring of the text string that matches the given
|
||||
* regular expression with the given replacement.
|
||||
* </p>
|
||||
*
|
||||
* This method is a {@code null} safe equivalent to:
|
||||
* <ul>
|
||||
* <li>{@code text.replaceFirst(regex, replacement)}</li>
|
||||
* <li>{@code Pattern.compile(regex).matcher(text).replaceFirst(replacement)}</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>
|
||||
* A {@code null} reference passed to this method is a no-op.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The {@link Pattern#DOTALL} option is NOT automatically added. To use the
|
||||
* DOTALL option prepend {@code "(?s)"} to the regex. DOTALL is also known as
|
||||
* single-line mode in Perl.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* StringUtils.replaceFirst(null, *, *) = null
|
||||
* StringUtils.replaceFirst("any", (String) null, *) = "any"
|
||||
* StringUtils.replaceFirst("any", *, null) = "any"
|
||||
* StringUtils.replaceFirst("", "", "zzz") = "zzz"
|
||||
* StringUtils.replaceFirst("", ".*", "zzz") = "zzz"
|
||||
* StringUtils.replaceFirst("", ".+", "zzz") = ""
|
||||
* StringUtils.replaceFirst("abc", "", "ZZ") = "ZZabc"
|
||||
* StringUtils.replaceFirst("<__>\n<__>", "<.*>", "z") = "z\n<__>"
|
||||
* StringUtils.replaceFirst("<__>\n<__>", "(?s)<.*>", "z") = "z"
|
||||
* StringUtils.replaceFirst("ABCabc123", "[a-z]", "_") = "ABC_bc123"
|
||||
* StringUtils.replaceFirst("ABCabc123abc", "[^A-Z0-9]+", "_") = "ABC_123abc"
|
||||
* StringUtils.replaceFirst("ABCabc123abc", "[^A-Z0-9]+", "") = "ABC123abc"
|
||||
* StringUtils.replaceFirst("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2") = "Lorem_ipsum dolor sit"
|
||||
* </pre>
|
||||
*
|
||||
* @param text text to search and replace in, may be null
|
||||
* @param regex the regular expression to which this string is to be
|
||||
* matched
|
||||
* @param replacement the string to be substituted for the first match
|
||||
* @return the text with the first replacement processed, {@code null} if null
|
||||
* String input
|
||||
*
|
||||
* @throws java.util.regex.PatternSyntaxException if the regular expression's
|
||||
* syntax is invalid
|
||||
*
|
||||
* @see String#replaceFirst(String, String)
|
||||
* @see java.util.regex.Pattern
|
||||
* @see java.util.regex.Pattern#DOTALL
|
||||
*/
|
||||
public static String replaceFirst(final String text, final String regex, final String replacement) {
|
||||
if (text == null || regex == null || replacement == null) {
|
||||
return text;
|
||||
}
|
||||
return text.replaceFirst(regex, replacement);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Replaces each substring of the source String that matches the given regular
|
||||
* expression with the given replacement using the {@link Pattern#DOTALL}
|
||||
* option. DOTALL is also known as single-line mode in Perl.
|
||||
* </p>
|
||||
*
|
||||
* This call is a {@code null} safe equivalent to:
|
||||
* <ul>
|
||||
* <li>{@code text.replaceAll("(?s)" + regex, replacement)}</li>
|
||||
* <li>{@code Pattern.compile(regex, Pattern.DOTALL).matcher(text).replaceAll(replacement)}</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>
|
||||
* A {@code null} reference passed to this method is a no-op.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* StringUtils.replacePattern(null, *, *) = null
|
||||
* StringUtils.replacePattern("any", (String) null, *) = "any"
|
||||
* StringUtils.replacePattern("any", *, null) = "any"
|
||||
* StringUtils.replacePattern("", "", "zzz") = "zzz"
|
||||
* StringUtils.replacePattern("", ".*", "zzz") = "zzz"
|
||||
* StringUtils.replacePattern("", ".+", "zzz") = ""
|
||||
* StringUtils.replacePattern("<__>\n<__>", "<.*>", "z") = "z"
|
||||
* StringUtils.replacePattern("ABCabc123", "[a-z]", "_") = "ABC___123"
|
||||
* StringUtils.replacePattern("ABCabc123", "[^A-Z0-9]+", "_") = "ABC_123"
|
||||
* StringUtils.replacePattern("ABCabc123", "[^A-Z0-9]+", "") = "ABC123"
|
||||
* StringUtils.replacePattern("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2") = "Lorem_ipsum_dolor_sit"
|
||||
* </pre>
|
||||
*
|
||||
* @param text the source string
|
||||
* @param regex the regular expression to which this string is to be
|
||||
* matched
|
||||
* @param replacement the string to be substituted for each match
|
||||
* @return The resulting {@code String}
|
||||
* @see #replaceAll(String, String, String)
|
||||
* @see String#replaceAll(String, String)
|
||||
* @see Pattern#DOTALL
|
||||
*/
|
||||
public static String replacePattern(final String text, final String regex, final String replacement) {
|
||||
if (ObjectUtils.anyNull(text, regex, replacement)) {
|
||||
return text;
|
||||
}
|
||||
return Pattern.compile(regex, Pattern.DOTALL).matcher(text).replaceAll(replacement);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,91 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Exception thrown when the Serialization process fails.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The original error is wrapped within this one.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* #NotThreadSafe# because Throwable is not thread-safe
|
||||
* </p>
|
||||
*
|
||||
* @since 1.0
|
||||
*/
|
||||
public class SerializationException extends RuntimeException {
|
||||
|
||||
/**
|
||||
* Required for serialization support.
|
||||
*
|
||||
* @see java.io.Serializable
|
||||
*/
|
||||
private static final long serialVersionUID = 4029025366392702726L;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Constructs a new {@code SerializationException} without specified detail
|
||||
* message.
|
||||
* </p>
|
||||
*/
|
||||
public SerializationException() {
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Constructs a new {@code SerializationException} with specified detail
|
||||
* message.
|
||||
* </p>
|
||||
*
|
||||
* @param msg The error message.
|
||||
*/
|
||||
public SerializationException(final String msg) {
|
||||
super(msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Constructs a new {@code SerializationException} with specified nested
|
||||
* {@code Throwable}.
|
||||
* </p>
|
||||
*
|
||||
* @param cause The {@code Exception} or {@code Error} that caused this
|
||||
* exception to be thrown.
|
||||
*/
|
||||
public SerializationException(final Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Constructs a new {@code SerializationException} with specified detail message
|
||||
* and nested {@code Throwable}.
|
||||
* </p>
|
||||
*
|
||||
* @param msg The error message.
|
||||
* @param cause The {@code Exception} or {@code Error} that caused this
|
||||
* exception to be thrown.
|
||||
*/
|
||||
public SerializationException(final String msg, final Throwable cause) {
|
||||
super(msg, cause);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,317 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.ObjectStreamClass;
|
||||
import java.io.OutputStream;
|
||||
import java.io.Serializable;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import net.lax1dude.eaglercraft.v1_8.EaglerInputStream;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Assists with the serialization process and performs additional functionality
|
||||
* based on serialization.
|
||||
* </p>
|
||||
*
|
||||
* <ul>
|
||||
* <li>Deep clone using serialization
|
||||
* <li>Serialize managing finally and IOException
|
||||
* <li>Deserialize managing finally and IOException
|
||||
* </ul>
|
||||
*
|
||||
* <p>
|
||||
* This class throws exceptions for invalid {@code null} inputs. Each method
|
||||
* documents its behavior in more detail.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* #ThreadSafe#
|
||||
* </p>
|
||||
*
|
||||
* @since 1.0
|
||||
*/
|
||||
public class SerializationUtils {
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Custom specialization of the standard JDK {@link java.io.ObjectInputStream}
|
||||
* that uses a custom {@code ClassLoader} to resolve a class. If the specified
|
||||
* {@code ClassLoader} is not able to resolve the class, the context classloader
|
||||
* of the current thread will be used. This way, the standard deserialization
|
||||
* work also in web-application containers and application servers, no matter in
|
||||
* which of the {@code ClassLoader} the particular class that encapsulates
|
||||
* serialization/deserialization lives.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* For more in-depth information about the problem for which this class here is
|
||||
* a workaround, see the JIRA issue LANG-626.
|
||||
* </p>
|
||||
*/
|
||||
static class ClassLoaderAwareObjectInputStream extends ObjectInputStream {
|
||||
private static final Map<String, Class<?>> primitiveTypes = new HashMap<>();
|
||||
|
||||
static {
|
||||
primitiveTypes.put("byte", byte.class);
|
||||
primitiveTypes.put("short", short.class);
|
||||
primitiveTypes.put("int", int.class);
|
||||
primitiveTypes.put("long", long.class);
|
||||
primitiveTypes.put("float", float.class);
|
||||
primitiveTypes.put("double", double.class);
|
||||
primitiveTypes.put("boolean", boolean.class);
|
||||
primitiveTypes.put("char", char.class);
|
||||
primitiveTypes.put("void", void.class);
|
||||
}
|
||||
|
||||
private final ClassLoader classLoader;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param in The {@code InputStream}.
|
||||
* @param classLoader classloader to use
|
||||
* @throws IOException if an I/O error occurs while reading stream header.
|
||||
* @see java.io.ObjectInputStream
|
||||
*/
|
||||
ClassLoaderAwareObjectInputStream(final InputStream in, final ClassLoader classLoader) throws IOException {
|
||||
super(in);
|
||||
this.classLoader = classLoader;
|
||||
}
|
||||
|
||||
/**
|
||||
* Overridden version that uses the parameterized {@code ClassLoader} or the
|
||||
* {@code ClassLoader} of the current {@code Thread} to resolve the class.
|
||||
*
|
||||
* @param desc An instance of class {@code ObjectStreamClass}.
|
||||
* @return A {@code Class} object corresponding to {@code desc}.
|
||||
* @throws IOException Any of the usual Input/Output exceptions.
|
||||
* @throws ClassNotFoundException If class of a serialized object cannot be
|
||||
* found.
|
||||
*/
|
||||
@Override
|
||||
protected Class<?> resolveClass(final ObjectStreamClass desc) throws IOException, ClassNotFoundException {
|
||||
final String name = desc.getName();
|
||||
try {
|
||||
return Class.forName(name, false, classLoader);
|
||||
} catch (final ClassNotFoundException ex) {
|
||||
try {
|
||||
return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
|
||||
} catch (final ClassNotFoundException cnfe) {
|
||||
final Class<?> cls = primitiveTypes.get(name);
|
||||
if (cls != null) {
|
||||
return cls;
|
||||
}
|
||||
throw cnfe;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Deep clone an {@code Object} using serialization.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This is many times slower than writing clone methods by hand on all objects
|
||||
* in your object graph. However, for complex object graphs, or for those that
|
||||
* don't support deep cloning this can be a simple alternative implementation.
|
||||
* Of course all the objects must be {@code Serializable}.
|
||||
* </p>
|
||||
*
|
||||
* @param <T> the type of the object involved
|
||||
* @param object the {@code Serializable} object to clone
|
||||
* @return the cloned object
|
||||
* @throws SerializationException (runtime) if the serialization fails
|
||||
*/
|
||||
public static <T extends Serializable> T clone(final T object) {
|
||||
if (object == null) {
|
||||
return null;
|
||||
}
|
||||
final byte[] objectData = serialize(object);
|
||||
final EaglerInputStream bais = new EaglerInputStream(objectData);
|
||||
|
||||
try (ClassLoaderAwareObjectInputStream in = new ClassLoaderAwareObjectInputStream(bais,
|
||||
object.getClass().getClassLoader())) {
|
||||
/*
|
||||
* when we serialize and deserialize an object, it is reasonable to assume the
|
||||
* deserialized object is of the same type as the original serialized object
|
||||
*/
|
||||
@SuppressWarnings("unchecked") // see above
|
||||
final T readObject = (T) in.readObject();
|
||||
return readObject;
|
||||
|
||||
} catch (final ClassNotFoundException ex) {
|
||||
throw new SerializationException("ClassNotFoundException while reading cloned object data", ex);
|
||||
} catch (final IOException ex) {
|
||||
throw new SerializationException("IOException while reading or closing cloned object data", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Deserializes a single {@code Object} from an array of bytes.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* If the call site incorrectly types the return value, a
|
||||
* {@link ClassCastException} is thrown from the call site. Without Generics in
|
||||
* this declaration, the call site must type cast and can cause the same
|
||||
* ClassCastException. Note that in both cases, the ClassCastException is in the
|
||||
* call site, not in this method.
|
||||
* </p>
|
||||
*
|
||||
* @param <T> the object type to be deserialized
|
||||
* @param objectData the serialized object, must not be null
|
||||
* @return the deserialized object
|
||||
* @throws NullPointerException if {@code objectData} is {@code null}
|
||||
* @throws SerializationException (runtime) if the serialization fails
|
||||
*/
|
||||
public static <T> T deserialize(final byte[] objectData) {
|
||||
Validate.notNull(objectData, "objectData");
|
||||
return deserialize(new EaglerInputStream(objectData));
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Deserializes an {@code Object} from the specified stream.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The stream will be closed once the object is written. This avoids the need
|
||||
* for a finally clause, and maybe also exception handling, in the application
|
||||
* code.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The stream passed in is not buffered internally within this method. This is
|
||||
* the responsibility of your application if desired.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* If the call site incorrectly types the return value, a
|
||||
* {@link ClassCastException} is thrown from the call site. Without Generics in
|
||||
* this declaration, the call site must type cast and can cause the same
|
||||
* ClassCastException. Note that in both cases, the ClassCastException is in the
|
||||
* call site, not in this method.
|
||||
* </p>
|
||||
*
|
||||
* @param <T> the object type to be deserialized
|
||||
* @param inputStream the serialized object input stream, must not be null
|
||||
* @return the deserialized object
|
||||
* @throws NullPointerException if {@code inputStream} is {@code null}
|
||||
* @throws SerializationException (runtime) if the serialization fails
|
||||
*/
|
||||
@SuppressWarnings("resource") // inputStream is managed by the caller
|
||||
public static <T> T deserialize(final InputStream inputStream) {
|
||||
Validate.notNull(inputStream, "inputStream");
|
||||
try (ObjectInputStream in = new ObjectInputStream(inputStream)) {
|
||||
@SuppressWarnings("unchecked")
|
||||
final T obj = (T) in.readObject();
|
||||
return obj;
|
||||
} catch (final ClassNotFoundException | IOException ex) {
|
||||
throw new SerializationException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a serialization roundtrip. Serializes and deserializes the given
|
||||
* object, great for testing objects that implement {@link Serializable}.
|
||||
*
|
||||
* @param <T> the type of the object involved
|
||||
* @param obj the object to roundtrip
|
||||
* @return the serialized and deserialized object
|
||||
* @since 3.3
|
||||
*/
|
||||
@SuppressWarnings("unchecked") // OK, because we serialized a type `T`
|
||||
public static <T extends Serializable> T roundtrip(final T obj) {
|
||||
return (T) deserialize(serialize(obj));
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Serializes an {@code Object} to a byte array for storage/serialization.
|
||||
* </p>
|
||||
*
|
||||
* @param obj the object to serialize to bytes
|
||||
* @return a byte[] with the converted Serializable
|
||||
* @throws SerializationException (runtime) if the serialization fails
|
||||
*/
|
||||
public static byte[] serialize(final Serializable obj) {
|
||||
final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
|
||||
serialize(obj, baos);
|
||||
return baos.toByteArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Serializes an {@code Object} to the specified stream.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The stream will be closed once the object is written. This avoids the need
|
||||
* for a finally clause, and maybe also exception handling, in the application
|
||||
* code.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The stream passed in is not buffered internally within this method. This is
|
||||
* the responsibility of your application if desired.
|
||||
* </p>
|
||||
*
|
||||
* @param obj the object to serialize to bytes, may be null
|
||||
* @param outputStream the stream to write to, must not be null
|
||||
* @throws NullPointerException if {@code outputStream} is {@code null}
|
||||
* @throws SerializationException (runtime) if the serialization fails
|
||||
*/
|
||||
@SuppressWarnings("resource") // outputStream is managed by the caller
|
||||
public static void serialize(final Serializable obj, final OutputStream outputStream) {
|
||||
Validate.notNull(outputStream, "outputStream");
|
||||
try (ObjectOutputStream out = new ObjectOutputStream(outputStream)) {
|
||||
out.writeObject(obj);
|
||||
} catch (final IOException ex) {
|
||||
throw new SerializationException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* SerializationUtils instances should NOT be constructed in standard
|
||||
* programming. Instead, the class should be used as
|
||||
* {@code SerializationUtils.clone(object)}.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* This constructor is public to permit tools that require a JavaBean instance
|
||||
* to operate.
|
||||
* </p>
|
||||
*
|
||||
* @since 2.0
|
||||
*/
|
||||
public SerializationUtils() {
|
||||
}
|
||||
|
||||
}
|
565
sources/main/java/org/apache/commons/lang3/Streams.java
Normal file
565
sources/main/java/org/apache/commons/lang3/Streams.java
Normal file
@ -0,0 +1,565 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.BinaryOperator;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collector;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.apache.commons.lang3.Functions.FailableConsumer;
|
||||
import org.apache.commons.lang3.Functions.FailableFunction;
|
||||
import org.apache.commons.lang3.Functions.FailablePredicate;
|
||||
|
||||
/**
|
||||
* Provides utility functions, and classes for working with the
|
||||
* {@code java.util.stream} package, or more generally, with Java 8 lambdas.
|
||||
* More specifically, it attempts to address the fact that lambdas are supposed
|
||||
* not to throw Exceptions, at least not checked Exceptions, AKA instances of
|
||||
* {@link Exception}. This enforces the use of constructs like
|
||||
*
|
||||
* <pre>
|
||||
* Consumer<java.lang.reflect.Method> consumer = m -> {
|
||||
* try {
|
||||
* m.invoke(o, args);
|
||||
* } catch (Throwable t) {
|
||||
* throw Functions.rethrow(t);
|
||||
* }
|
||||
* };
|
||||
* stream.forEach(consumer);
|
||||
* </pre>
|
||||
*
|
||||
* Using a {@link FailableStream}, this can be rewritten as follows:
|
||||
*
|
||||
* <pre>
|
||||
* Streams.failable(stream).forEach((m) -> m.invoke(o, args));
|
||||
* </pre>
|
||||
*
|
||||
* Obviously, the second version is much more concise and the spirit of Lambda
|
||||
* expressions is met better than in the first version.
|
||||
*
|
||||
* @see Stream
|
||||
* @see Functions
|
||||
* @since 3.10
|
||||
* @deprecated Use {@link org.apache.commons.lang3.stream.Streams}.
|
||||
*/
|
||||
@Deprecated
|
||||
public class Streams {
|
||||
|
||||
/**
|
||||
* A reduced, and simplified version of a {@link Stream} with failable method
|
||||
* signatures.
|
||||
*
|
||||
* @param <O> The streams element type.
|
||||
* @deprecated Use
|
||||
* {@link org.apache.commons.lang3.stream.Streams.FailableStream}.
|
||||
*/
|
||||
@Deprecated
|
||||
public static class FailableStream<O extends Object> {
|
||||
|
||||
private Stream<O> stream;
|
||||
private boolean terminated;
|
||||
|
||||
/**
|
||||
* Constructs a new instance with the given {@code stream}.
|
||||
*
|
||||
* @param stream The stream.
|
||||
*/
|
||||
public FailableStream(final Stream<O> stream) {
|
||||
this.stream = stream;
|
||||
}
|
||||
|
||||
protected void assertNotTerminated() {
|
||||
if (terminated) {
|
||||
throw new IllegalStateException("This stream is already terminated.");
|
||||
}
|
||||
}
|
||||
|
||||
protected void makeTerminated() {
|
||||
assertNotTerminated();
|
||||
terminated = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a FailableStream consisting of the elements of this stream that match
|
||||
* the given FailablePredicate.
|
||||
*
|
||||
* <p>
|
||||
* This is an intermediate operation.
|
||||
*
|
||||
* @param predicate a non-interfering, stateless predicate to apply to each
|
||||
* element to determine if it should be included.
|
||||
* @return the new stream
|
||||
*/
|
||||
public FailableStream<O> filter(final FailablePredicate<O, ?> predicate) {
|
||||
assertNotTerminated();
|
||||
stream = stream.filter(Functions.asPredicate(predicate));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs an action for each element of this stream.
|
||||
*
|
||||
* <p>
|
||||
* This is a terminal operation.
|
||||
*
|
||||
* <p>
|
||||
* The behavior of this operation is explicitly nondeterministic. For parallel
|
||||
* stream pipelines, this operation does <em>not</em> guarantee to respect the
|
||||
* encounter order of the stream, as doing so would sacrifice the benefit of
|
||||
* parallelism. For any given element, the action may be performed at whatever
|
||||
* time and in whatever thread the library chooses. If the action accesses
|
||||
* shared state, it is responsible for providing the required synchronization.
|
||||
*
|
||||
* @param action a non-interfering action to perform on the elements
|
||||
*/
|
||||
public void forEach(final FailableConsumer<O, ?> action) {
|
||||
makeTerminated();
|
||||
stream().forEach(Functions.asConsumer(action));
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a mutable reduction operation on the elements of this stream using a
|
||||
* {@code Collector}. A {@code Collector} encapsulates the functions used as
|
||||
* arguments to {@link #collect(Supplier, BiConsumer, BiConsumer)}, allowing for
|
||||
* reuse of collection strategies and composition of collect operations such as
|
||||
* multiple-level grouping or partitioning.
|
||||
*
|
||||
* <p>
|
||||
* If the underlying stream is parallel, and the {@code Collector} is
|
||||
* concurrent, and either the stream is unordered or the collector is unordered,
|
||||
* then a concurrent reduction will be performed (see {@link Collector} for
|
||||
* details on concurrent reduction.)
|
||||
*
|
||||
* <p>
|
||||
* This is a terminal operation.
|
||||
*
|
||||
* <p>
|
||||
* When executed in parallel, multiple intermediate results may be instantiated,
|
||||
* populated, and merged so as to maintain isolation of mutable data structures.
|
||||
* Therefore, even when executed in parallel with non-thread-safe data
|
||||
* structures (such as {@code ArrayList}), no additional synchronization is
|
||||
* needed for a parallel reduction.
|
||||
*
|
||||
* Note The following will accumulate strings into an ArrayList:
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* @code
|
||||
* List<String> asList = stringStream.collect(Collectors.toList());
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* The following will classify {@code Person} objects by city:
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* @code
|
||||
* Map<String, List<Person>> peopleByCity = personStream.collect(Collectors.groupingBy(Person::getCity));
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* The following will classify {@code Person} objects by state and city,
|
||||
* cascading two {@code Collector}s together:
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* @code
|
||||
* Map<String, Map<String, List<Person>>> peopleByStateAndCity = personStream
|
||||
* .collect(Collectors.groupingBy(Person::getState, Collectors.groupingBy(Person::getCity)));
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* @param <R> the type of the result
|
||||
* @param <A> the intermediate accumulation type of the {@code Collector}
|
||||
* @param collector the {@code Collector} describing the reduction
|
||||
* @return the result of the reduction
|
||||
* @see #collect(Supplier, BiConsumer, BiConsumer)
|
||||
* @see Collectors
|
||||
*/
|
||||
public <A, R> R collect(final Collector<? super O, A, R> collector) {
|
||||
makeTerminated();
|
||||
return stream().collect(collector);
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a mutable reduction operation on the elements of this
|
||||
* FailableStream. A mutable reduction is one in which the reduced value is a
|
||||
* mutable result container, such as an {@code ArrayList}, and elements are
|
||||
* incorporated by updating the state of the result rather than by replacing the
|
||||
* result. This produces a result equivalent to:
|
||||
*
|
||||
* <pre>
|
||||
* {@code
|
||||
* R result = supplier.get();
|
||||
* for (T element : this stream)
|
||||
* accumulator.accept(result, element);
|
||||
* return result;
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations can
|
||||
* be parallelized without requiring additional synchronization.
|
||||
*
|
||||
* <p>
|
||||
* This is a terminal operation.
|
||||
*
|
||||
* Note There are many existing classes in the JDK whose signatures are
|
||||
* well-suited for use with method references as arguments to {@code collect()}.
|
||||
* For example, the following will accumulate strings into an {@code ArrayList}:
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* @code
|
||||
* List<String> asList = stringStream.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* The following will take a stream of strings and concatenates them into a
|
||||
* single string:
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* @code
|
||||
* String concat = stringStream.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
|
||||
* .toString();
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* @param <R> type of the result
|
||||
* @param <A> Type of the accumulator.
|
||||
* @param pupplier a function that creates a new result container. For a
|
||||
* parallel execution, this function may be called multiple
|
||||
* times and must return a fresh value each time.
|
||||
* @param accumulator An associative, non-interfering, stateless function for
|
||||
* incorporating an additional element into a result
|
||||
* @param combiner An associative, non-interfering, stateless function for
|
||||
* combining two values, which must be compatible with the
|
||||
* accumulator function
|
||||
* @return The result of the reduction
|
||||
*/
|
||||
public <A, R> R collect(final Supplier<R> pupplier, final BiConsumer<R, ? super O> accumulator,
|
||||
final BiConsumer<R, R> combiner) {
|
||||
makeTerminated();
|
||||
return stream().collect(pupplier, accumulator, combiner);
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a reduction on the elements of this stream, using the provided
|
||||
* identity value and an associative accumulation function, and returns the
|
||||
* reduced value. This is equivalent to:
|
||||
*
|
||||
* <pre>
|
||||
* {@code
|
||||
* T result = identity;
|
||||
* for (T element : this stream)
|
||||
* result = accumulator.apply(result, element)
|
||||
* return result;
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* but is not constrained to execute sequentially.
|
||||
*
|
||||
* <p>
|
||||
* The {@code identity} value must be an identity for the accumulator function.
|
||||
* This means that for all {@code t}, {@code accumulator.apply(identity, t)} is
|
||||
* equal to {@code t}. The {@code accumulator} function must be an associative
|
||||
* function.
|
||||
*
|
||||
* <p>
|
||||
* This is a terminal operation.
|
||||
*
|
||||
* Note Sum, min, max, average, and string concatenation are all special cases
|
||||
* of reduction. Summing a stream of numbers can be expressed as:
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* @code
|
||||
* Integer sum = integers.reduce(0, (a, b) -> a + b);
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* or:
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* @code
|
||||
* Integer sum = integers.reduce(0, Integer::sum);
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* While this may seem a more roundabout way to perform an aggregation compared
|
||||
* to simply mutating a running total in a loop, reduction operations
|
||||
* parallelize more gracefully, without needing additional synchronization and
|
||||
* with greatly reduced risk of data races.
|
||||
*
|
||||
* @param identity the identity value for the accumulating function
|
||||
* @param accumulator an associative, non-interfering, stateless function for
|
||||
* combining two values
|
||||
* @return the result of the reduction
|
||||
*/
|
||||
public O reduce(final O identity, final BinaryOperator<O> accumulator) {
|
||||
makeTerminated();
|
||||
return stream().reduce(identity, accumulator);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a stream consisting of the results of applying the given function to
|
||||
* the elements of this stream.
|
||||
*
|
||||
* <p>
|
||||
* This is an intermediate operation.
|
||||
*
|
||||
* @param <R> The element type of the new stream
|
||||
* @param mapper A non-interfering, stateless function to apply to each element
|
||||
* @return the new stream
|
||||
*/
|
||||
public <R> FailableStream<R> map(final FailableFunction<O, R, ?> mapper) {
|
||||
assertNotTerminated();
|
||||
return new FailableStream<>(stream.map(Functions.asFunction(mapper)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the FailableStream into an equivalent stream.
|
||||
*
|
||||
* @return A stream, which will return the same elements, which this
|
||||
* FailableStream would return.
|
||||
*/
|
||||
public Stream<O> stream() {
|
||||
return stream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether all elements of this stream match the provided predicate. May
|
||||
* not evaluate the predicate on all elements if not necessary for determining
|
||||
* the result. If the stream is empty then {@code true} is returned and the
|
||||
* predicate is not evaluated.
|
||||
*
|
||||
* <p>
|
||||
* This is a short-circuiting terminal operation.
|
||||
*
|
||||
* Note This method evaluates the <em>universal quantification</em> of the
|
||||
* predicate over the elements of the stream (for all x P(x)). If the stream is
|
||||
* empty, the quantification is said to be <em>vacuously satisfied</em> and is
|
||||
* always {@code true} (regardless of P(x)).
|
||||
*
|
||||
* @param predicate A non-interfering, stateless predicate to apply to elements
|
||||
* of this stream
|
||||
* @return {@code true} If either all elements of the stream match the provided
|
||||
* predicate or the stream is empty, otherwise {@code false}.
|
||||
*/
|
||||
public boolean allMatch(final FailablePredicate<O, ?> predicate) {
|
||||
assertNotTerminated();
|
||||
return stream().allMatch(Functions.asPredicate(predicate));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether any elements of this stream match the provided predicate. May
|
||||
* not evaluate the predicate on all elements if not necessary for determining
|
||||
* the result. If the stream is empty then {@code false} is returned and the
|
||||
* predicate is not evaluated.
|
||||
*
|
||||
* <p>
|
||||
* This is a short-circuiting terminal operation.
|
||||
*
|
||||
* Note This method evaluates the <em>existential quantification</em> of the
|
||||
* predicate over the elements of the stream (for some x P(x)).
|
||||
*
|
||||
* @param predicate A non-interfering, stateless predicate to apply to elements
|
||||
* of this stream
|
||||
* @return {@code true} if any elements of the stream match the provided
|
||||
* predicate, otherwise {@code false}
|
||||
*/
|
||||
public boolean anyMatch(final FailablePredicate<O, ?> predicate) {
|
||||
assertNotTerminated();
|
||||
return stream().anyMatch(Functions.asPredicate(predicate));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given {@link Stream stream} into a {@link FailableStream}. This
|
||||
* is basically a simplified, reduced version of the {@link Stream} class, with
|
||||
* the same underlying element stream, except that failable objects, like
|
||||
* {@link FailablePredicate}, {@link FailableFunction}, or
|
||||
* {@link FailableConsumer} may be applied, instead of {@link Predicate},
|
||||
* {@link Function}, or {@link Consumer}. The idea is to rewrite a code snippet
|
||||
* like this:
|
||||
*
|
||||
* <pre>
|
||||
* final List<O> list;
|
||||
* final Method m;
|
||||
* final Function<O, String> mapper = (o) -> {
|
||||
* try {
|
||||
* return (String) m.invoke(o);
|
||||
* } catch (Throwable t) {
|
||||
* throw Functions.rethrow(t);
|
||||
* }
|
||||
* };
|
||||
* final List<String> strList = list.stream().map(mapper).collect(Collectors.toList());
|
||||
* </pre>
|
||||
*
|
||||
* as follows:
|
||||
*
|
||||
* <pre>
|
||||
* final List<O> list;
|
||||
* final Method m;
|
||||
* final List<String> strList = Functions.stream(list.stream()).map((o) -> (String) m.invoke(o))
|
||||
* .collect(Collectors.toList());
|
||||
* </pre>
|
||||
*
|
||||
* While the second version may not be <em>quite</em> as efficient (because it
|
||||
* depends on the creation of additional, intermediate objects, of type
|
||||
* FailableStream), it is much more concise, and readable, and meets the spirit
|
||||
* of Lambdas better than the first version.
|
||||
*
|
||||
* @param <O> The streams element type.
|
||||
* @param stream The stream, which is being converted.
|
||||
* @return The {@link FailableStream}, which has been created by converting the
|
||||
* stream.
|
||||
*/
|
||||
public static <O> FailableStream<O> stream(final Stream<O> stream) {
|
||||
return new FailableStream<>(stream);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given {@link Collection} into a {@link FailableStream}. This is
|
||||
* basically a simplified, reduced version of the {@link Stream} class, with the
|
||||
* same underlying element stream, except that failable objects, like
|
||||
* {@link FailablePredicate}, {@link FailableFunction}, or
|
||||
* {@link FailableConsumer} may be applied, instead of {@link Predicate},
|
||||
* {@link Function}, or {@link Consumer}. The idea is to rewrite a code snippet
|
||||
* like this:
|
||||
*
|
||||
* <pre>
|
||||
* final List<O> list;
|
||||
* final Method m;
|
||||
* final Function<O, String> mapper = (o) -> {
|
||||
* try {
|
||||
* return (String) m.invoke(o);
|
||||
* } catch (Throwable t) {
|
||||
* throw Functions.rethrow(t);
|
||||
* }
|
||||
* };
|
||||
* final List<String> strList = list.stream().map(mapper).collect(Collectors.toList());
|
||||
* </pre>
|
||||
*
|
||||
* as follows:
|
||||
*
|
||||
* <pre>
|
||||
* final List<O> list;
|
||||
* final Method m;
|
||||
* final List<String> strList = Functions.stream(list.stream()).map((o) -> (String) m.invoke(o))
|
||||
* .collect(Collectors.toList());
|
||||
* </pre>
|
||||
*
|
||||
* While the second version may not be <em>quite</em> as efficient (because it
|
||||
* depends on the creation of additional, intermediate objects, of type
|
||||
* FailableStream), it is much more concise, and readable, and meets the spirit
|
||||
* of Lambdas better than the first version.
|
||||
*
|
||||
* @param <O> The streams element type.
|
||||
* @param stream The stream, which is being converted.
|
||||
* @return The {@link FailableStream}, which has been created by converting the
|
||||
* stream.
|
||||
*/
|
||||
public static <O> FailableStream<O> stream(final Collection<O> stream) {
|
||||
return stream(stream.stream());
|
||||
}
|
||||
|
||||
/**
|
||||
* A Collector type for arrays.
|
||||
*
|
||||
* @param <O> The array type.
|
||||
* @deprecated Use
|
||||
* {@link org.apache.commons.lang3.stream.Streams.ArrayCollector}.
|
||||
*/
|
||||
@Deprecated
|
||||
public static class ArrayCollector<O> implements Collector<O, List<O>, O[]> {
|
||||
private static final Set<Characteristics> characteristics = Collections.emptySet();
|
||||
private final Class<O> elementType;
|
||||
|
||||
/**
|
||||
* Constructs a new instance for the given element type.
|
||||
*
|
||||
* @param elementType The element type.
|
||||
*/
|
||||
public ArrayCollector(final Class<O> elementType) {
|
||||
this.elementType = elementType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Supplier<List<O>> supplier() {
|
||||
return ArrayList::new;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BiConsumer<List<O>, O> accumulator() {
|
||||
return List::add;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BinaryOperator<List<O>> combiner() {
|
||||
return (left, right) -> {
|
||||
left.addAll(right);
|
||||
return left;
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Function<List<O>, O[]> finisher() {
|
||||
return list -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
final O[] array = (O[]) Array.newInstance(elementType, list.size());
|
||||
return list.toArray(array);
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Characteristics> characteristics() {
|
||||
return characteristics;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a {@code Collector} that accumulates the input elements into a new
|
||||
* array.
|
||||
*
|
||||
* @param pElementType Type of an element in the array.
|
||||
* @param <O> the type of the input elements
|
||||
* @return a {@code Collector} which collects all the input elements into an
|
||||
* array, in encounter order
|
||||
*/
|
||||
public static <O extends Object> Collector<O, ?, O[]> toArray(final Class<O> pElementType) {
|
||||
return new ArrayCollector<>(pElementType);
|
||||
}
|
||||
}
|
10513
sources/main/java/org/apache/commons/lang3/StringUtils.java
Normal file
10513
sources/main/java/org/apache/commons/lang3/StringUtils.java
Normal file
File diff suppressed because it is too large
Load Diff
1968
sources/main/java/org/apache/commons/lang3/SystemUtils.java
Normal file
1968
sources/main/java/org/apache/commons/lang3/SystemUtils.java
Normal file
File diff suppressed because it is too large
Load Diff
526
sources/main/java/org/apache/commons/lang3/ThreadUtils.java
Normal file
526
sources/main/java/org/apache/commons/lang3/ThreadUtils.java
Normal file
@ -0,0 +1,526 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.time.DurationUtils;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Helpers for {@code java.lang.Thread} and {@code java.lang.ThreadGroup}.
|
||||
* </p>
|
||||
* <p>
|
||||
* #ThreadSafe#
|
||||
* </p>
|
||||
*
|
||||
* @see java.lang.Thread
|
||||
* @see java.lang.ThreadGroup
|
||||
* @since 3.5
|
||||
*/
|
||||
public class ThreadUtils {
|
||||
|
||||
/**
|
||||
* A predicate implementation which always returns true.
|
||||
*/
|
||||
private static final class AlwaysTruePredicate implements ThreadPredicate, ThreadGroupPredicate {
|
||||
|
||||
private AlwaysTruePredicate() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean test(final Thread thread) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean test(final ThreadGroup threadGroup) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A predicate implementation which matches a thread or threadgroup name.
|
||||
*/
|
||||
public static class NamePredicate implements ThreadPredicate, ThreadGroupPredicate {
|
||||
|
||||
private final String name;
|
||||
|
||||
/**
|
||||
* Predicate constructor
|
||||
*
|
||||
* @param name thread or threadgroup name
|
||||
* @throws IllegalArgumentException if the name is {@code null}
|
||||
*/
|
||||
public NamePredicate(final String name) {
|
||||
Validate.notNull(name, "name");
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean test(final Thread thread) {
|
||||
return thread != null && thread.getName().equals(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean test(final ThreadGroup threadGroup) {
|
||||
return threadGroup != null && threadGroup.getName().equals(name);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A predicate for selecting threadgroups.
|
||||
*/
|
||||
// When breaking BC, replace this with Predicate<ThreadGroup>
|
||||
@FunctionalInterface
|
||||
public interface ThreadGroupPredicate {
|
||||
|
||||
/**
|
||||
* Evaluates this predicate on the given threadgroup.
|
||||
*
|
||||
* @param threadGroup the threadgroup
|
||||
* @return {@code true} if the threadGroup matches the predicate, otherwise
|
||||
* {@code false}
|
||||
*/
|
||||
boolean test(ThreadGroup threadGroup);
|
||||
}
|
||||
|
||||
/**
|
||||
* A predicate implementation which matches a thread id.
|
||||
*/
|
||||
public static class ThreadIdPredicate implements ThreadPredicate {
|
||||
|
||||
private final long threadId;
|
||||
|
||||
/**
|
||||
* Predicate constructor
|
||||
*
|
||||
* @param threadId the threadId to match
|
||||
* @throws IllegalArgumentException if the threadId is zero or negative
|
||||
*/
|
||||
public ThreadIdPredicate(final long threadId) {
|
||||
if (threadId <= 0) {
|
||||
throw new IllegalArgumentException("The thread id must be greater than zero");
|
||||
}
|
||||
this.threadId = threadId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean test(final Thread thread) {
|
||||
return thread != null && thread.getId() == threadId;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A predicate for selecting threads.
|
||||
*/
|
||||
// When breaking BC, replace this with Predicate<Thread>
|
||||
@FunctionalInterface
|
||||
public interface ThreadPredicate {
|
||||
|
||||
/**
|
||||
* Evaluates this predicate on the given thread.
|
||||
*
|
||||
* @param thread the thread
|
||||
* @return {@code true} if the thread matches the predicate, otherwise
|
||||
* {@code false}
|
||||
*/
|
||||
boolean test(Thread thread);
|
||||
}
|
||||
|
||||
/**
|
||||
* Predicate which always returns true.
|
||||
*/
|
||||
public static final AlwaysTruePredicate ALWAYS_TRUE_PREDICATE = new AlwaysTruePredicate();
|
||||
|
||||
/**
|
||||
* Finds the active thread with the specified id.
|
||||
*
|
||||
* @param threadId The thread id
|
||||
* @return The thread with the specified id or {@code null} if no such thread
|
||||
* exists
|
||||
* @throws IllegalArgumentException if the specified id is zero or negative
|
||||
* @throws SecurityException if the current thread cannot access the
|
||||
* system thread group
|
||||
*
|
||||
* @throws SecurityException if the current thread cannot modify thread
|
||||
* groups from this thread's thread group up to
|
||||
* the system thread group
|
||||
*/
|
||||
public static Thread findThreadById(final long threadId) {
|
||||
final Collection<Thread> result = findThreads(new ThreadIdPredicate(threadId));
|
||||
return result.isEmpty() ? null : result.iterator().next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the active thread with the specified id if it belongs to a thread group
|
||||
* with the specified group name.
|
||||
*
|
||||
* @param threadId The thread id
|
||||
* @param threadGroupName The thread group name
|
||||
* @return The threads which belongs to a thread group with the specified group
|
||||
* name and the thread's id match the specified id. {@code null} is
|
||||
* returned if no such thread exists
|
||||
* @throws IllegalArgumentException if the specified id is zero or negative or
|
||||
* the group name is null
|
||||
* @throws SecurityException if the current thread cannot access the
|
||||
* system thread group
|
||||
*
|
||||
* @throws SecurityException if the current thread cannot modify thread
|
||||
* groups from this thread's thread group up to
|
||||
* the system thread group
|
||||
*/
|
||||
public static Thread findThreadById(final long threadId, final String threadGroupName) {
|
||||
Validate.notNull(threadGroupName, "threadGroupName");
|
||||
final Thread thread = findThreadById(threadId);
|
||||
if (thread != null && thread.getThreadGroup() != null
|
||||
&& thread.getThreadGroup().getName().equals(threadGroupName)) {
|
||||
return thread;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the active thread with the specified id if it belongs to the specified
|
||||
* thread group.
|
||||
*
|
||||
* @param threadId The thread id
|
||||
* @param threadGroup The thread group
|
||||
* @return The thread which belongs to a specified thread group and the thread's
|
||||
* id match the specified id. {@code null} is returned if no such thread
|
||||
* exists
|
||||
* @throws IllegalArgumentException if the specified id is zero or negative or
|
||||
* the group is null
|
||||
* @throws SecurityException if the current thread cannot access the
|
||||
* system thread group
|
||||
*
|
||||
* @throws SecurityException if the current thread cannot modify thread
|
||||
* groups from this thread's thread group up to
|
||||
* the system thread group
|
||||
*/
|
||||
public static Thread findThreadById(final long threadId, final ThreadGroup threadGroup) {
|
||||
Validate.notNull(threadGroup, "threadGroup");
|
||||
final Thread thread = findThreadById(threadId);
|
||||
if (thread != null && threadGroup.equals(thread.getThreadGroup())) {
|
||||
return thread;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Select all active threadgroups which match the given predicate and which is a
|
||||
* subgroup of the given thread group (or one of its subgroups).
|
||||
*
|
||||
* @param group the thread group
|
||||
* @param recurse if {@code true} then evaluate the predicate recursively on
|
||||
* all threadgroups in all subgroups of the given group
|
||||
* @param predicate the predicate
|
||||
* @return An unmodifiable {@code Collection} of active threadgroups which match
|
||||
* the given predicate and which is a subgroup of the given thread group
|
||||
* @throws IllegalArgumentException if the given group or predicate is null
|
||||
* @throws SecurityException if the current thread cannot modify thread
|
||||
* groups from this thread's thread group up to
|
||||
* the system thread group
|
||||
*/
|
||||
public static Collection<ThreadGroup> findThreadGroups(final ThreadGroup group, final boolean recurse,
|
||||
final ThreadGroupPredicate predicate) {
|
||||
Validate.notNull(group, "group");
|
||||
Validate.notNull(predicate, "predicate");
|
||||
|
||||
int count = group.activeGroupCount();
|
||||
ThreadGroup[] threadGroups;
|
||||
do {
|
||||
threadGroups = new ThreadGroup[count + (count / 2) + 1]; // slightly grow the array size
|
||||
count = group.enumerate(threadGroups, recurse);
|
||||
// return value of enumerate() must be strictly less than the array size
|
||||
// according to javadoc
|
||||
} while (count >= threadGroups.length);
|
||||
|
||||
final List<ThreadGroup> result = new ArrayList<>(count);
|
||||
for (int i = 0; i < count; ++i) {
|
||||
if (predicate.test(threadGroups[i])) {
|
||||
result.add(threadGroups[i]);
|
||||
}
|
||||
}
|
||||
return Collections.unmodifiableCollection(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Select all active threadgroups which match the given predicate.
|
||||
*
|
||||
* @param predicate the predicate
|
||||
* @return An unmodifiable {@code Collection} of active threadgroups matching
|
||||
* the given predicate
|
||||
* @throws IllegalArgumentException if the predicate is null
|
||||
* @throws SecurityException if the current thread cannot access the
|
||||
* system thread group
|
||||
* @throws SecurityException if the current thread cannot modify thread
|
||||
* groups from this thread's thread group up to
|
||||
* the system thread group
|
||||
*/
|
||||
public static Collection<ThreadGroup> findThreadGroups(final ThreadGroupPredicate predicate) {
|
||||
return findThreadGroups(getSystemThreadGroup(), true, predicate);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds active thread groups with the specified group name.
|
||||
*
|
||||
* @param threadGroupName The thread group name
|
||||
* @return the thread groups with the specified group name or an empty
|
||||
* collection if no such thread group exists. The collection returned is
|
||||
* always unmodifiable.
|
||||
* @throws IllegalArgumentException if group name is null
|
||||
* @throws SecurityException if the current thread cannot access the
|
||||
* system thread group
|
||||
*
|
||||
* @throws SecurityException if the current thread cannot modify thread
|
||||
* groups from this thread's thread group up to
|
||||
* the system thread group
|
||||
*/
|
||||
public static Collection<ThreadGroup> findThreadGroupsByName(final String threadGroupName) {
|
||||
return findThreadGroups(new NamePredicate(threadGroupName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Select all active threads which match the given predicate and which belongs
|
||||
* to the given thread group (or one of its subgroups).
|
||||
*
|
||||
* @param group the thread group
|
||||
* @param recurse if {@code true} then evaluate the predicate recursively on
|
||||
* all threads in all subgroups of the given group
|
||||
* @param predicate the predicate
|
||||
* @return An unmodifiable {@code Collection} of active threads which match the
|
||||
* given predicate and which belongs to the given thread group
|
||||
* @throws IllegalArgumentException if the given group or predicate is null
|
||||
* @throws SecurityException if the current thread cannot modify thread
|
||||
* groups from this thread's thread group up to
|
||||
* the system thread group
|
||||
*/
|
||||
public static Collection<Thread> findThreads(final ThreadGroup group, final boolean recurse,
|
||||
final ThreadPredicate predicate) {
|
||||
Validate.notNull(group, "The group must not be null");
|
||||
Validate.notNull(predicate, "The predicate must not be null");
|
||||
|
||||
int count = group.activeCount();
|
||||
Thread[] threads;
|
||||
do {
|
||||
threads = new Thread[count + (count / 2) + 1]; // slightly grow the array size
|
||||
count = group.enumerate(threads, recurse);
|
||||
// return value of enumerate() must be strictly less than the array size
|
||||
// according to javadoc
|
||||
} while (count >= threads.length);
|
||||
|
||||
final List<Thread> result = new ArrayList<>(count);
|
||||
for (int i = 0; i < count; ++i) {
|
||||
if (predicate.test(threads[i])) {
|
||||
result.add(threads[i]);
|
||||
}
|
||||
}
|
||||
return Collections.unmodifiableCollection(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Select all active threads which match the given predicate.
|
||||
*
|
||||
* @param predicate the predicate
|
||||
* @return An unmodifiable {@code Collection} of active threads matching the
|
||||
* given predicate
|
||||
*
|
||||
* @throws IllegalArgumentException if the predicate is null
|
||||
* @throws SecurityException if the current thread cannot access the
|
||||
* system thread group
|
||||
* @throws SecurityException if the current thread cannot modify thread
|
||||
* groups from this thread's thread group up to
|
||||
* the system thread group
|
||||
*/
|
||||
public static Collection<Thread> findThreads(final ThreadPredicate predicate) {
|
||||
return findThreads(getSystemThreadGroup(), true, predicate);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds active threads with the specified name.
|
||||
*
|
||||
* @param threadName The thread name
|
||||
* @return The threads with the specified name or an empty collection if no such
|
||||
* thread exists. The collection returned is always unmodifiable.
|
||||
* @throws IllegalArgumentException if the specified name is null
|
||||
* @throws SecurityException if the current thread cannot access the
|
||||
* system thread group
|
||||
*
|
||||
* @throws SecurityException if the current thread cannot modify thread
|
||||
* groups from this thread's thread group up to
|
||||
* the system thread group
|
||||
*/
|
||||
public static Collection<Thread> findThreadsByName(final String threadName) {
|
||||
return findThreads(new NamePredicate(threadName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds active threads with the specified name if they belong to a thread group
|
||||
* with the specified group name.
|
||||
*
|
||||
* @param threadName The thread name
|
||||
* @param threadGroupName The thread group name
|
||||
* @return The threads which belongs to a thread group with the specified group
|
||||
* name and the thread's name match the specified name, An empty
|
||||
* collection is returned if no such thread exists. The collection
|
||||
* returned is always unmodifiable.
|
||||
* @throws IllegalArgumentException if the specified thread name or group name
|
||||
* is null
|
||||
* @throws SecurityException if the current thread cannot access the
|
||||
* system thread group
|
||||
*
|
||||
* @throws SecurityException if the current thread cannot modify thread
|
||||
* groups from this thread's thread group up to
|
||||
* the system thread group
|
||||
*/
|
||||
public static Collection<Thread> findThreadsByName(final String threadName, final String threadGroupName) {
|
||||
Validate.notNull(threadName, "threadName");
|
||||
Validate.notNull(threadGroupName, "threadGroupName");
|
||||
|
||||
final Collection<ThreadGroup> threadGroups = findThreadGroups(new NamePredicate(threadGroupName));
|
||||
|
||||
if (threadGroups.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
final Collection<Thread> result = new ArrayList<>();
|
||||
final NamePredicate threadNamePredicate = new NamePredicate(threadName);
|
||||
for (final ThreadGroup group : threadGroups) {
|
||||
result.addAll(findThreads(group, false, threadNamePredicate));
|
||||
}
|
||||
return Collections.unmodifiableCollection(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds active threads with the specified name if they belong to a specified
|
||||
* thread group.
|
||||
*
|
||||
* @param threadName The thread name
|
||||
* @param threadGroup The thread group
|
||||
* @return The threads which belongs to a thread group and the thread's name
|
||||
* match the specified name, An empty collection is returned if no such
|
||||
* thread exists. The collection returned is always unmodifiable.
|
||||
* @throws IllegalArgumentException if the specified thread name or group is
|
||||
* null
|
||||
* @throws SecurityException if the current thread cannot access the
|
||||
* system thread group
|
||||
*
|
||||
* @throws SecurityException if the current thread cannot modify thread
|
||||
* groups from this thread's thread group up to
|
||||
* the system thread group
|
||||
*/
|
||||
public static Collection<Thread> findThreadsByName(final String threadName, final ThreadGroup threadGroup) {
|
||||
return findThreads(threadGroup, false, new NamePredicate(threadName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all active thread groups excluding the system thread group (A thread
|
||||
* group is active if it has been not destroyed).
|
||||
*
|
||||
* @return all thread groups excluding the system thread group. The collection
|
||||
* returned is always unmodifiable.
|
||||
* @throws SecurityException if the current thread cannot access the system
|
||||
* thread group
|
||||
*
|
||||
* @throws SecurityException if the current thread cannot modify thread groups
|
||||
* from this thread's thread group up to the system
|
||||
* thread group
|
||||
*/
|
||||
public static Collection<ThreadGroup> getAllThreadGroups() {
|
||||
return findThreadGroups(ALWAYS_TRUE_PREDICATE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all active threads (A thread is active if it has been started and has
|
||||
* not yet died).
|
||||
*
|
||||
* @return all active threads. The collection returned is always unmodifiable.
|
||||
* @throws SecurityException if the current thread cannot access the system
|
||||
* thread group
|
||||
*
|
||||
* @throws SecurityException if the current thread cannot modify thread groups
|
||||
* from this thread's thread group up to the system
|
||||
* thread group
|
||||
*/
|
||||
public static Collection<Thread> getAllThreads() {
|
||||
return findThreads(ALWAYS_TRUE_PREDICATE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the system thread group (sometimes also referred as "root thread
|
||||
* group").
|
||||
*
|
||||
* @return the system thread group
|
||||
* @throws SecurityException if the current thread cannot modify thread groups
|
||||
* from this thread's thread group up to the system
|
||||
* thread group
|
||||
*/
|
||||
public static ThreadGroup getSystemThreadGroup() {
|
||||
ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
|
||||
while (threadGroup.getParent() != null) {
|
||||
threadGroup = threadGroup.getParent();
|
||||
}
|
||||
return threadGroup;
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits for the given thread to die for the given duration. Implemented using
|
||||
* {@link Thread#join(long, int)}.
|
||||
*
|
||||
* @param thread The thread to join.
|
||||
* @param duration How long to wait.
|
||||
* @throws InterruptedException if any thread has interrupted the current
|
||||
* thread.
|
||||
* @see Thread#join(long, int)
|
||||
* @since 3.12.0
|
||||
*/
|
||||
public static void join(final Thread thread, final Duration duration) throws InterruptedException {
|
||||
DurationUtils.accept(thread::join, duration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sleeps the current thread for the given duration. Implemented using
|
||||
* {@link Thread#sleep(long, int)}.
|
||||
*
|
||||
* @param duration How long to sleep.
|
||||
* @throws InterruptedException if any thread has interrupted the current
|
||||
* thread.
|
||||
* @see Thread#sleep(long, int)
|
||||
* @since 3.12.0
|
||||
*/
|
||||
public static void sleep(final Duration duration) throws InterruptedException {
|
||||
DurationUtils.accept(Thread::sleep, duration);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* ThreadUtils instances should NOT be constructed in standard programming.
|
||||
* Instead, the class should be used as {@code ThreadUtils.getAllThreads()}
|
||||
* </p>
|
||||
* <p>
|
||||
* This constructor is public to permit tools that require a JavaBean instance
|
||||
* to operate.
|
||||
* </p>
|
||||
*/
|
||||
public ThreadUtils() {
|
||||
}
|
||||
}
|
1621
sources/main/java/org/apache/commons/lang3/Validate.java
Normal file
1621
sources/main/java/org/apache/commons/lang3/Validate.java
Normal file
File diff suppressed because it is too large
Load Diff
192
sources/main/java/org/apache/commons/lang3/arch/Processor.java
Normal file
192
sources/main/java/org/apache/commons/lang3/arch/Processor.java
Normal file
@ -0,0 +1,192 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.arch;
|
||||
|
||||
/**
|
||||
* The {@link Processor} represents a microprocessor and defines some properties
|
||||
* like architecture and type of the microprocessor.
|
||||
*
|
||||
* @since 3.6
|
||||
*/
|
||||
public class Processor {
|
||||
|
||||
/**
|
||||
* The {@link Arch} enum defines the architecture of a microprocessor. The
|
||||
* architecture represents the bit value of the microprocessor. The following
|
||||
* architectures are defined:
|
||||
* <ul>
|
||||
* <li>32-bit</li>
|
||||
* <li>64-bit</li>
|
||||
* <li>Unknown</li>
|
||||
* </ul>
|
||||
*/
|
||||
public enum Arch {
|
||||
|
||||
/**
|
||||
* A 32-bit processor architecture.
|
||||
*/
|
||||
BIT_32("32-bit"),
|
||||
|
||||
/**
|
||||
* A 64-bit processor architecture.
|
||||
*/
|
||||
BIT_64("64-bit"),
|
||||
|
||||
/**
|
||||
* An unknown-bit processor architecture.
|
||||
*/
|
||||
UNKNOWN("Unknown");
|
||||
|
||||
/**
|
||||
* A label suitable for display.
|
||||
*
|
||||
* @since 3.10
|
||||
*/
|
||||
private final String label;
|
||||
|
||||
Arch(final String label) {
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the label suitable for display.
|
||||
*
|
||||
* @return the label.
|
||||
*/
|
||||
public String getLabel() {
|
||||
return label;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The {@link Type} enum defines types of a microprocessor. The following types
|
||||
* are defined:
|
||||
* <ul>
|
||||
* <li>x86</li>
|
||||
* <li>ia64</li>
|
||||
* <li>PPC</li>
|
||||
* <li>Unknown</li>
|
||||
* </ul>
|
||||
*/
|
||||
public enum Type {
|
||||
|
||||
/**
|
||||
* Intel x86 series of instruction set architectures.
|
||||
*/
|
||||
X86,
|
||||
|
||||
/**
|
||||
* Intel Itanium 64-bit architecture.
|
||||
*/
|
||||
IA_64,
|
||||
|
||||
/**
|
||||
* Apple–IBM–Motorola PowerPC architecture.
|
||||
*/
|
||||
PPC,
|
||||
|
||||
/**
|
||||
* Unknown architecture.
|
||||
*/
|
||||
UNKNOWN
|
||||
}
|
||||
|
||||
private final Arch arch;
|
||||
private final Type type;
|
||||
|
||||
/**
|
||||
* Constructs a {@link Processor} object with the given parameters.
|
||||
*
|
||||
* @param arch The processor architecture.
|
||||
* @param type The processor type.
|
||||
*/
|
||||
public Processor(final Arch arch, final Type type) {
|
||||
this.arch = arch;
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the processor architecture as an {@link Arch} enum. The processor
|
||||
* architecture defines, if the processor has a 32 or 64 bit architecture.
|
||||
*
|
||||
* @return A {@link Arch} enum.
|
||||
*/
|
||||
public Arch getArch() {
|
||||
return arch;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the processor type as {@link Type} enum. The processor type defines,
|
||||
* if the processor is for example a x86 or PPA.
|
||||
*
|
||||
* @return A {@link Type} enum.
|
||||
*/
|
||||
public Type getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if {@link Processor} is 32 bit.
|
||||
*
|
||||
* @return {@code true}, if {@link Processor} is {@link Arch#BIT_32}, else
|
||||
* {@code false}.
|
||||
*/
|
||||
public boolean is32Bit() {
|
||||
return Arch.BIT_32 == arch;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if {@link Processor} is 64 bit.
|
||||
*
|
||||
* @return {@code true}, if {@link Processor} is {@link Arch#BIT_64}, else
|
||||
* {@code false}.
|
||||
*/
|
||||
public boolean is64Bit() {
|
||||
return Arch.BIT_64 == arch;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if {@link Processor} is type of x86.
|
||||
*
|
||||
* @return {@code true}, if {@link Processor} is {@link Type#X86}, else
|
||||
* {@code false}.
|
||||
*/
|
||||
public boolean isX86() {
|
||||
return Type.X86 == type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if {@link Processor} is type of Intel Itanium.
|
||||
*
|
||||
* @return {@code true}. if {@link Processor} is {@link Type#IA_64}, else
|
||||
* {@code false}.
|
||||
*/
|
||||
public boolean isIA64() {
|
||||
return Type.IA_64 == type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if {@link Processor} is type of Power PC.
|
||||
*
|
||||
* @return {@code true}. if {@link Processor} is {@link Type#PPC}, else
|
||||
* {@code false}.
|
||||
*/
|
||||
public boolean isPPC() {
|
||||
return Type.PPC == type;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.
|
||||
*/
|
||||
/**
|
||||
* Provides classes to work with the values of the os.arch system property.
|
||||
*
|
||||
* @since 3.6
|
||||
*/
|
||||
package org.apache.commons.lang3.arch;
|
@ -0,0 +1,95 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.builder;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* The Builder interface is designed to designate a class as a <em>builder</em>
|
||||
* object in the Builder design pattern. Builders are capable of creating and
|
||||
* configuring objects or results that normally take multiple steps to construct
|
||||
* or are very complex to derive.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* The builder interface defines a single method, {@link #build()}, that classes
|
||||
* must implement. The result of this method should be the final configured
|
||||
* object or result after all building operations are performed.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* It is a recommended practice that the methods supplied to configure the
|
||||
* object or result being built return a reference to {@code this} so that
|
||||
* method calls can be chained together.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Example Builder:
|
||||
*
|
||||
* <pre>
|
||||
* <code>
|
||||
* class FontBuilder implements Builder<Font> {
|
||||
* private Font font;
|
||||
*
|
||||
* public FontBuilder(String fontName) {
|
||||
* this.font = new Font(fontName, Font.PLAIN, 12);
|
||||
* }
|
||||
*
|
||||
* public FontBuilder bold() {
|
||||
* this.font = this.font.deriveFont(Font.BOLD);
|
||||
* return this; // Reference returned so calls can be chained
|
||||
* }
|
||||
*
|
||||
* public FontBuilder size(float pointSize) {
|
||||
* this.font = this.font.deriveFont(pointSize);
|
||||
* return this; // Reference returned so calls can be chained
|
||||
* }
|
||||
*
|
||||
* // Other Font construction methods
|
||||
*
|
||||
* public Font build() {
|
||||
* return this.font;
|
||||
* }
|
||||
* }
|
||||
* </code>
|
||||
* </pre>
|
||||
*
|
||||
* Example Builder Usage:
|
||||
*
|
||||
* <pre>
|
||||
* <code>
|
||||
* Font bold14ptSansSerifFont = new FontBuilder(Font.SANS_SERIF).bold()
|
||||
* .size(14.0f)
|
||||
* .build();
|
||||
* </code>
|
||||
* </pre>
|
||||
*
|
||||
*
|
||||
* @param <T> the type of object that the builder will construct or compute.
|
||||
*
|
||||
* @since 3.0
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface Builder<T> {
|
||||
|
||||
/**
|
||||
* Returns a reference to the object being constructed or result being
|
||||
* calculated by the builder.
|
||||
*
|
||||
* @return the object constructed or result calculated by the builder.
|
||||
*/
|
||||
T build();
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.builder;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Use this annotation to exclude a field from being used by the
|
||||
* {@link ReflectionToStringBuilder}.
|
||||
*
|
||||
* @since 3.5
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.FIELD)
|
||||
public @interface ToStringExclude {
|
||||
// empty
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.builder;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Use this annotation on the fields to get the summary instead of the detailed
|
||||
* information when using {@link ReflectionToStringBuilder}.
|
||||
*
|
||||
* <p>
|
||||
* Notice that not all {@link ToStringStyle} implementations support the
|
||||
* appendSummary method.
|
||||
* </p>
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.FIELD)
|
||||
public @interface ToStringSummary {
|
||||
// empty
|
||||
}
|
@ -0,0 +1,230 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.compare;
|
||||
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Utility library to provide helper methods for translating
|
||||
* {@link Comparable#compareTo} result into a boolean.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Example:
|
||||
* {@code boolean x = is(myComparable).lessThanOrEqualTo(otherComparable)}
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* #ThreadSafe#
|
||||
* </p>
|
||||
*
|
||||
* @since 3.10
|
||||
*/
|
||||
public class ComparableUtils {
|
||||
|
||||
/**
|
||||
* Provides access to the available methods
|
||||
*
|
||||
* @param <A> the type of objects that this object may be compared against.
|
||||
*/
|
||||
public static class ComparableCheckBuilder<A extends Comparable<A>> {
|
||||
|
||||
private final A a;
|
||||
|
||||
private ComparableCheckBuilder(final A a) {
|
||||
this.a = a;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if {@code [b <= a <= c]} or {@code [b >= a >= c]} where the {@code a}
|
||||
* is object passed to {@link #is}.
|
||||
*
|
||||
* @param b the object to compare to the base object
|
||||
* @param c the object to compare to the base object
|
||||
* @return true if the base object is between b and c
|
||||
*/
|
||||
public boolean between(final A b, final A c) {
|
||||
return betweenOrdered(b, c) || betweenOrdered(c, b);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if {@code (b < a < c)} or {@code (b > a > c)} where the {@code a} is
|
||||
* object passed to {@link #is}.
|
||||
*
|
||||
* @param b the object to compare to the base object
|
||||
* @param c the object to compare to the base object
|
||||
* @return true if the base object is between b and c and not equal to those
|
||||
*/
|
||||
public boolean betweenExclusive(final A b, final A c) {
|
||||
return betweenOrderedExclusive(b, c) || betweenOrderedExclusive(c, b);
|
||||
}
|
||||
|
||||
private boolean betweenOrdered(final A b, final A c) {
|
||||
return greaterThanOrEqualTo(b) && lessThanOrEqualTo(c);
|
||||
}
|
||||
|
||||
private boolean betweenOrderedExclusive(final A b, final A c) {
|
||||
return greaterThan(b) && lessThan(c);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the object passed to {@link #is} is equal to {@code b}
|
||||
*
|
||||
* @param b the object to compare to the base object
|
||||
* @return true if the value returned by {@link Comparable#compareTo} is equal
|
||||
* to {@code 0}
|
||||
*/
|
||||
public boolean equalTo(final A b) {
|
||||
return a.compareTo(b) == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the object passed to {@link #is} is greater than {@code b}
|
||||
*
|
||||
* @param b the object to compare to the base object
|
||||
* @return true if the value returned by {@link Comparable#compareTo} is greater
|
||||
* than {@code 0}
|
||||
*/
|
||||
public boolean greaterThan(final A b) {
|
||||
return a.compareTo(b) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the object passed to {@link #is} is greater than or equal to
|
||||
* {@code b}
|
||||
*
|
||||
* @param b the object to compare to the base object
|
||||
* @return true if the value returned by {@link Comparable#compareTo} is greater
|
||||
* than or equal to {@code 0}
|
||||
*/
|
||||
public boolean greaterThanOrEqualTo(final A b) {
|
||||
return a.compareTo(b) >= 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the object passed to {@link #is} is less than {@code b}
|
||||
*
|
||||
* @param b the object to compare to the base object
|
||||
* @return true if the value returned by {@link Comparable#compareTo} is less
|
||||
* than {@code 0}
|
||||
*/
|
||||
public boolean lessThan(final A b) {
|
||||
return a.compareTo(b) < 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the object passed to {@link #is} is less than or equal to {@code b}
|
||||
*
|
||||
* @param b the object to compare to the base object
|
||||
* @return true if the value returned by {@link Comparable#compareTo} is less
|
||||
* than or equal to {@code 0}
|
||||
*/
|
||||
public boolean lessThanOrEqualTo(final A b) {
|
||||
return a.compareTo(b) <= 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if {@code [b <= a <= c]} or {@code [b >= a >= c]} where the {@code a}
|
||||
* is the tested object.
|
||||
*
|
||||
* @param b the object to compare to the tested object
|
||||
* @param c the object to compare to the tested object
|
||||
* @param <A> type of the test object
|
||||
* @return a predicate for true if the tested object is between b and c
|
||||
*/
|
||||
public static <A extends Comparable<A>> Predicate<A> between(final A b, final A c) {
|
||||
return a -> is(a).between(b, c);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if {@code (b < a < c)} or {@code (b > a > c)} where the {@code a} is
|
||||
* the tested object.
|
||||
*
|
||||
* @param b the object to compare to the tested object
|
||||
* @param c the object to compare to the tested object
|
||||
* @param <A> type of the test object
|
||||
* @return a predicate for true if the tested object is between b and c and not
|
||||
* equal to those
|
||||
*/
|
||||
public static <A extends Comparable<A>> Predicate<A> betweenExclusive(final A b, final A c) {
|
||||
return a -> is(a).betweenExclusive(b, c);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the tested object is greater than or equal to {@code b}
|
||||
*
|
||||
* @param b the object to compare to the tested object
|
||||
* @param <A> type of the test object
|
||||
* @return a predicate for true if the value returned by
|
||||
* {@link Comparable#compareTo} is greater than or equal to {@code 0}
|
||||
*/
|
||||
public static <A extends Comparable<A>> Predicate<A> ge(final A b) {
|
||||
return a -> is(a).greaterThanOrEqualTo(b);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the tested object is greater than {@code b}
|
||||
*
|
||||
* @param b the object to compare to the tested object
|
||||
* @param <A> type of the test object
|
||||
* @return a predicate for true if the value returned by
|
||||
* {@link Comparable#compareTo} is greater than {@code 0}
|
||||
*/
|
||||
public static <A extends Comparable<A>> Predicate<A> gt(final A b) {
|
||||
return a -> is(a).greaterThan(b);
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides access to the available methods
|
||||
*
|
||||
* @param a base object in the further comparison
|
||||
* @param <A> type of the base object
|
||||
* @return a builder object with further methods
|
||||
*/
|
||||
public static <A extends Comparable<A>> ComparableCheckBuilder<A> is(final A a) {
|
||||
return new ComparableCheckBuilder<>(a);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the tested object is less than or equal to {@code b}
|
||||
*
|
||||
* @param b the object to compare to the tested object
|
||||
* @param <A> type of the test object
|
||||
* @return a predicate for true if the value returned by
|
||||
* {@link Comparable#compareTo} is less than or equal to {@code 0}
|
||||
*/
|
||||
public static <A extends Comparable<A>> Predicate<A> le(final A b) {
|
||||
return a -> is(a).lessThanOrEqualTo(b);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the tested object is less than {@code b}
|
||||
*
|
||||
* @param b the object to compare to the tested object
|
||||
* @param <A> type of the test object
|
||||
* @return a predicate for true if the value returned by
|
||||
* {@link Comparable#compareTo} is less than {@code 0}
|
||||
*/
|
||||
public static <A extends Comparable<A>> Predicate<A> lt(final A b) {
|
||||
return a -> is(a).lessThan(b);
|
||||
}
|
||||
|
||||
private ComparableUtils() {
|
||||
}
|
||||
}
|
@ -0,0 +1,70 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.compare;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Comparator;
|
||||
|
||||
/**
|
||||
* Compares Object's {@link Object#toString()} values.
|
||||
*
|
||||
* This class is stateless.
|
||||
*
|
||||
* @since 3.10
|
||||
*/
|
||||
public final class ObjectToStringComparator implements Comparator<Object>, Serializable {
|
||||
|
||||
/**
|
||||
* Singleton instance.
|
||||
*
|
||||
* This class is stateless.
|
||||
*/
|
||||
public static final ObjectToStringComparator INSTANCE = new ObjectToStringComparator();
|
||||
|
||||
/**
|
||||
* For {@link Serializable}.
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public int compare(final Object o1, final Object o2) {
|
||||
if (o1 == null && o2 == null) {
|
||||
return 0;
|
||||
}
|
||||
if (o1 == null) {
|
||||
return 1;
|
||||
}
|
||||
if (o2 == null) {
|
||||
return -1;
|
||||
}
|
||||
final String string1 = o1.toString();
|
||||
final String string2 = o2.toString();
|
||||
// No guarantee that toString() returns a non-null value, despite what Spotbugs
|
||||
// thinks.
|
||||
if (string1 == null && string2 == null) {
|
||||
return 0;
|
||||
}
|
||||
if (string1 == null) {
|
||||
return 1;
|
||||
}
|
||||
if (string2 == null) {
|
||||
return -1;
|
||||
}
|
||||
return string1.compareTo(string2);
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Provides classes to work with the {@link java.lang.Comparable} and
|
||||
* {@link java.util.Comparator} interfaces.
|
||||
*
|
||||
* @since 3.10
|
||||
*/
|
||||
package org.apache.commons.lang3.compare;
|
@ -0,0 +1,59 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.exception;
|
||||
|
||||
/**
|
||||
* Exception thrown when a clone cannot be created. In contrast to
|
||||
* {@link CloneNotSupportedException} this is a {@link RuntimeException}.
|
||||
*
|
||||
* @since 3.0
|
||||
*/
|
||||
public class CloneFailedException extends RuntimeException {
|
||||
// ~ Static fields/initializers ---------------------------------------------
|
||||
|
||||
private static final long serialVersionUID = 20091223L;
|
||||
|
||||
// ~ Constructors -----------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Constructs a CloneFailedException.
|
||||
*
|
||||
* @param message description of the exception
|
||||
*/
|
||||
public CloneFailedException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a CloneFailedException.
|
||||
*
|
||||
* @param cause cause of the exception
|
||||
*/
|
||||
public CloneFailedException(final Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a CloneFailedException.
|
||||
*
|
||||
* @param message description of the exception
|
||||
* @param cause cause of the exception
|
||||
*/
|
||||
public CloneFailedException(final String message, final Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.
|
||||
*/
|
||||
/**
|
||||
* <p>
|
||||
* Provides functionality for Exceptions.
|
||||
* </p>
|
||||
* <p>
|
||||
* Contains the concept of an exception with context i.e. such an exception will
|
||||
* contain a map with keys and values. This provides an easy way to pass
|
||||
* valuable state information at exception time in useful form to a calling
|
||||
* process.
|
||||
* </p>
|
||||
* <p>
|
||||
* Lastly, {@link org.apache.commons.lang3.exception.ExceptionUtils} also
|
||||
* contains {@code Throwable} manipulation and examination routines.
|
||||
* </p>
|
||||
*
|
||||
* @since 1.0
|
||||
*/
|
||||
package org.apache.commons.lang3.exception;
|
@ -0,0 +1,608 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.lang.reflect.UndeclaredThrowableException;
|
||||
import java.util.Collection;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.apache.commons.lang3.stream.Streams.FailableStream;
|
||||
|
||||
/**
|
||||
* This class provides utility functions, and classes for working with the
|
||||
* {@code java.util.function} package, or more generally, with Java 8 lambdas.
|
||||
* More specifically, it attempts to address the fact that lambdas are supposed
|
||||
* not to throw Exceptions, at least not checked Exceptions, AKA instances of
|
||||
* {@link Exception}. This enforces the use of constructs like:
|
||||
*
|
||||
* <pre>
|
||||
* Consumer<java.lang.reflect.Method-> consumer = m -> {
|
||||
* try {
|
||||
* m.invoke(o, args);
|
||||
* } catch (Throwable t) {
|
||||
* throw Failable.rethrow(t);
|
||||
* }
|
||||
* };
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* By replacing a {@link java.util.function.Consumer Consumer<O>} with a
|
||||
* {@link FailableConsumer FailableConsumer<O,? extends Throwable>}, this
|
||||
* can be written like follows:
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* Functions.accept((m) -> m.invoke(o, args));
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* Obviously, the second version is much more concise and the spirit of Lambda
|
||||
* expressions is met better than the second version.
|
||||
* </p>
|
||||
*
|
||||
* @since 3.11
|
||||
*/
|
||||
public class Failable {
|
||||
|
||||
/**
|
||||
* Consumes a consumer and rethrows any exception as a {@link RuntimeException}.
|
||||
*
|
||||
* @param consumer the consumer to consume
|
||||
* @param object1 the first object to consume by {@code consumer}
|
||||
* @param object2 the second object to consume by {@code consumer}
|
||||
* @param <T> the type of the first argument the consumer accepts
|
||||
* @param <U> the type of the second argument the consumer accepts
|
||||
* @param <E> the type of checked exception the consumer may throw
|
||||
*/
|
||||
public static <T, U, E extends Throwable> void accept(final FailableBiConsumer<T, U, E> consumer, final T object1,
|
||||
final U object2) {
|
||||
run(() -> consumer.accept(object1, object2));
|
||||
}
|
||||
|
||||
/**
|
||||
* Consumes a consumer and rethrows any exception as a {@link RuntimeException}.
|
||||
*
|
||||
* @param consumer the consumer to consume
|
||||
* @param object the object to consume by {@code consumer}
|
||||
* @param <T> the type the consumer accepts
|
||||
* @param <E> the type of checked exception the consumer may throw
|
||||
*/
|
||||
public static <T, E extends Throwable> void accept(final FailableConsumer<T, E> consumer, final T object) {
|
||||
run(() -> consumer.accept(object));
|
||||
}
|
||||
|
||||
/**
|
||||
* Consumes a consumer and rethrows any exception as a {@link RuntimeException}.
|
||||
*
|
||||
* @param consumer the consumer to consume
|
||||
* @param value the value to consume by {@code consumer}
|
||||
* @param <E> the type of checked exception the consumer may throw
|
||||
*/
|
||||
public static <E extends Throwable> void accept(final FailableDoubleConsumer<E> consumer, final double value) {
|
||||
run(() -> consumer.accept(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Consumes a consumer and rethrows any exception as a {@link RuntimeException}.
|
||||
*
|
||||
* @param consumer the consumer to consume
|
||||
* @param value the value to consume by {@code consumer}
|
||||
* @param <E> the type of checked exception the consumer may throw
|
||||
*/
|
||||
public static <E extends Throwable> void accept(final FailableIntConsumer<E> consumer, final int value) {
|
||||
run(() -> consumer.accept(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Consumes a consumer and rethrows any exception as a {@link RuntimeException}.
|
||||
*
|
||||
* @param consumer the consumer to consume
|
||||
* @param value the value to consume by {@code consumer}
|
||||
* @param <E> the type of checked exception the consumer may throw
|
||||
*/
|
||||
public static <E extends Throwable> void accept(final FailableLongConsumer<E> consumer, final long value) {
|
||||
run(() -> consumer.accept(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a function and rethrows any exception as a {@link RuntimeException}.
|
||||
*
|
||||
* @param function the function to apply
|
||||
* @param input1 the first input to apply {@code function} on
|
||||
* @param input2 the second input to apply {@code function} on
|
||||
* @param <T> the type of the first argument the function accepts
|
||||
* @param <U> the type of the second argument the function accepts
|
||||
* @param <R> the return type of the function
|
||||
* @param <E> the type of checked exception the function may throw
|
||||
* @return the value returned from the function
|
||||
*/
|
||||
public static <T, U, R, E extends Throwable> R apply(final FailableBiFunction<T, U, R, E> function, final T input1,
|
||||
final U input2) {
|
||||
return get(() -> function.apply(input1, input2));
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a function and rethrows any exception as a {@link RuntimeException}.
|
||||
*
|
||||
* @param function the function to apply
|
||||
* @param input the input to apply {@code function} on
|
||||
* @param <T> the type of the argument the function accepts
|
||||
* @param <R> the return type of the function
|
||||
* @param <E> the type of checked exception the function may throw
|
||||
* @return the value returned from the function
|
||||
*/
|
||||
public static <T, R, E extends Throwable> R apply(final FailableFunction<T, R, E> function, final T input) {
|
||||
return get(() -> function.apply(input));
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a function and rethrows any exception as a {@link RuntimeException}.
|
||||
*
|
||||
* @param function the function to apply
|
||||
* @param left the first input to apply {@code function} on
|
||||
* @param right the second input to apply {@code function} on
|
||||
* @param <E> the type of checked exception the function may throw
|
||||
* @return the value returned from the function
|
||||
*/
|
||||
public static <E extends Throwable> double applyAsDouble(final FailableDoubleBinaryOperator<E> function,
|
||||
final double left, final double right) {
|
||||
return getAsDouble(() -> function.applyAsDouble(left, right));
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given {@link FailableBiConsumer} into a standard
|
||||
* {@link BiConsumer}.
|
||||
*
|
||||
* @param <T> the type of the first argument of the consumers
|
||||
* @param <U> the type of the second argument of the consumers
|
||||
* @param consumer a failable {@code BiConsumer}
|
||||
* @return a standard {@code BiConsumer}
|
||||
*/
|
||||
public static <T, U> BiConsumer<T, U> asBiConsumer(final FailableBiConsumer<T, U, ?> consumer) {
|
||||
return (input1, input2) -> accept(consumer, input1, input2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given {@link FailableBiFunction} into a standard
|
||||
* {@link BiFunction}.
|
||||
*
|
||||
* @param <T> the type of the first argument of the input of the functions
|
||||
* @param <U> the type of the second argument of the input of the functions
|
||||
* @param <R> the type of the output of the functions
|
||||
* @param function a {@code FailableBiFunction}
|
||||
* @return a standard {@code BiFunction}
|
||||
*/
|
||||
public static <T, U, R> BiFunction<T, U, R> asBiFunction(final FailableBiFunction<T, U, R, ?> function) {
|
||||
return (input1, input2) -> apply(function, input1, input2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given {@link FailableBiPredicate} into a standard
|
||||
* {@link BiPredicate}.
|
||||
*
|
||||
* @param <T> the type of the first argument used by the predicates
|
||||
* @param <U> the type of the second argument used by the predicates
|
||||
* @param predicate a {@code FailableBiPredicate}
|
||||
* @return a standard {@code BiPredicate}
|
||||
*/
|
||||
public static <T, U> BiPredicate<T, U> asBiPredicate(final FailableBiPredicate<T, U, ?> predicate) {
|
||||
return (input1, input2) -> test(predicate, input1, input2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given {@link FailableCallable} into a standard {@link Callable}.
|
||||
*
|
||||
* @param <V> the type used by the callables
|
||||
* @param callable a {@code FailableCallable}
|
||||
* @return a standard {@code Callable}
|
||||
*/
|
||||
public static <V> Callable<V> asCallable(final FailableCallable<V, ?> callable) {
|
||||
return () -> call(callable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given {@link FailableConsumer} into a standard {@link Consumer}.
|
||||
*
|
||||
* @param <T> the type used by the consumers
|
||||
* @param consumer a {@code FailableConsumer}
|
||||
* @return a standard {@code Consumer}
|
||||
*/
|
||||
public static <T> Consumer<T> asConsumer(final FailableConsumer<T, ?> consumer) {
|
||||
return input -> accept(consumer, input);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given {@link FailableFunction} into a standard {@link Function}.
|
||||
*
|
||||
* @param <T> the type of the input of the functions
|
||||
* @param <R> the type of the output of the functions
|
||||
* @param function a {code FailableFunction}
|
||||
* @return a standard {@code Function}
|
||||
*/
|
||||
public static <T, R> Function<T, R> asFunction(final FailableFunction<T, R, ?> function) {
|
||||
return input -> apply(function, input);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given {@link FailablePredicate} into a standard
|
||||
* {@link Predicate}.
|
||||
*
|
||||
* @param <T> the type used by the predicates
|
||||
* @param predicate a {@code FailablePredicate}
|
||||
* @return a standard {@code Predicate}
|
||||
*/
|
||||
public static <T> Predicate<T> asPredicate(final FailablePredicate<T, ?> predicate) {
|
||||
return input -> test(predicate, input);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given {@link FailableRunnable} into a standard {@link Runnable}.
|
||||
*
|
||||
* @param runnable a {@code FailableRunnable}
|
||||
* @return a standard {@code Runnable}
|
||||
*/
|
||||
public static Runnable asRunnable(final FailableRunnable<?> runnable) {
|
||||
return () -> run(runnable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given {@link FailableSupplier} into a standard {@link Supplier}.
|
||||
*
|
||||
* @param <T> the type supplied by the suppliers
|
||||
* @param supplier a {@code FailableSupplier}
|
||||
* @return a standard {@code Supplier}
|
||||
*/
|
||||
public static <T> Supplier<T> asSupplier(final FailableSupplier<T, ?> supplier) {
|
||||
return () -> get(supplier);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls a callable and rethrows any exception as a {@link RuntimeException}.
|
||||
*
|
||||
* @param callable the callable to call
|
||||
* @param <V> the return type of the callable
|
||||
* @param <E> the type of checked exception the callable may throw
|
||||
* @return the value returned from the callable
|
||||
*/
|
||||
public static <V, E extends Throwable> V call(final FailableCallable<V, E> callable) {
|
||||
return get(callable::call);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes a supplier, and returns the result.
|
||||
*
|
||||
* @param supplier The supplier to invoke.
|
||||
* @param <T> The suppliers output type.
|
||||
* @param <E> The type of checked exception, which the supplier can throw.
|
||||
* @return The object, which has been created by the supplier
|
||||
*/
|
||||
public static <T, E extends Throwable> T get(final FailableSupplier<T, E> supplier) {
|
||||
try {
|
||||
return supplier.get();
|
||||
} catch (final Throwable t) {
|
||||
throw rethrow(t);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes a boolean supplier, and returns the result.
|
||||
*
|
||||
* @param supplier The boolean supplier to invoke.
|
||||
* @param <E> The type of checked exception, which the supplier can throw.
|
||||
* @return The boolean, which has been created by the supplier
|
||||
*/
|
||||
public static <E extends Throwable> boolean getAsBoolean(final FailableBooleanSupplier<E> supplier) {
|
||||
try {
|
||||
return supplier.getAsBoolean();
|
||||
} catch (final Throwable t) {
|
||||
throw rethrow(t);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes a double supplier, and returns the result.
|
||||
*
|
||||
* @param supplier The double supplier to invoke.
|
||||
* @param <E> The type of checked exception, which the supplier can throw.
|
||||
* @return The double, which has been created by the supplier
|
||||
*/
|
||||
public static <E extends Throwable> double getAsDouble(final FailableDoubleSupplier<E> supplier) {
|
||||
try {
|
||||
return supplier.getAsDouble();
|
||||
} catch (final Throwable t) {
|
||||
throw rethrow(t);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes an int supplier, and returns the result.
|
||||
*
|
||||
* @param supplier The int supplier to invoke.
|
||||
* @param <E> The type of checked exception, which the supplier can throw.
|
||||
* @return The int, which has been created by the supplier
|
||||
*/
|
||||
public static <E extends Throwable> int getAsInt(final FailableIntSupplier<E> supplier) {
|
||||
try {
|
||||
return supplier.getAsInt();
|
||||
} catch (final Throwable t) {
|
||||
throw rethrow(t);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes a long supplier, and returns the result.
|
||||
*
|
||||
* @param supplier The long supplier to invoke.
|
||||
* @param <E> The type of checked exception, which the supplier can throw.
|
||||
* @return The long, which has been created by the supplier
|
||||
*/
|
||||
public static <E extends Throwable> long getAsLong(final FailableLongSupplier<E> supplier) {
|
||||
try {
|
||||
return supplier.getAsLong();
|
||||
} catch (final Throwable t) {
|
||||
throw rethrow(t);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes a short supplier, and returns the result.
|
||||
*
|
||||
* @param supplier The short supplier to invoke.
|
||||
* @param <E> The type of checked exception, which the supplier can throw.
|
||||
* @return The short, which has been created by the supplier
|
||||
*/
|
||||
public static <E extends Throwable> short getAsShort(final FailableShortSupplier<E> supplier) {
|
||||
try {
|
||||
return supplier.getAsShort();
|
||||
} catch (final Throwable t) {
|
||||
throw rethrow(t);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Rethrows a {@link Throwable} as an unchecked exception. If the argument is
|
||||
* already unchecked, namely a {@code RuntimeException} or {@code Error} then
|
||||
* the argument will be rethrown without modification. If the exception is
|
||||
* {@code IOException} then it will be wrapped into a
|
||||
* {@code UncheckedIOException}. In every other cases the exception will be
|
||||
* wrapped into a {@code
|
||||
* UndeclaredThrowableException}
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Note that there is a declared return type for this method, even though it
|
||||
* never returns. The reason for that is to support the usual pattern:
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* throw rethrow(myUncheckedException);
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* instead of just calling the method. This pattern may help the Java compiler
|
||||
* to recognize that at that point an exception will be thrown and the code flow
|
||||
* analysis will not demand otherwise mandatory commands that could follow the
|
||||
* method call, like a {@code return} statement from a value returning method.
|
||||
* </p>
|
||||
*
|
||||
* @param throwable The throwable to rethrow ossibly wrapped into an unchecked
|
||||
* exception
|
||||
* @return Never returns anything, this method never terminates normally.
|
||||
*/
|
||||
public static RuntimeException rethrow(final Throwable throwable) {
|
||||
Objects.requireNonNull(throwable, "throwable");
|
||||
if (throwable instanceof RuntimeException) {
|
||||
throw (RuntimeException) throwable;
|
||||
} else if (throwable instanceof Error) {
|
||||
throw (Error) throwable;
|
||||
} else if (throwable instanceof IOException) {
|
||||
throw new UncheckedIOException((IOException) throwable);
|
||||
} else {
|
||||
throw new UndeclaredThrowableException(throwable);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a runnable and rethrows any exception as a {@link RuntimeException}.
|
||||
*
|
||||
* @param runnable The runnable to run
|
||||
* @param <E> the type of checked exception the runnable may throw
|
||||
*/
|
||||
public static <E extends Throwable> void run(final FailableRunnable<E> runnable) {
|
||||
try {
|
||||
runnable.run();
|
||||
} catch (final Throwable t) {
|
||||
throw rethrow(t);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given collection into a {@link FailableStream}. The
|
||||
* {@link FailableStream} consists of the collections elements. Shortcut for
|
||||
*
|
||||
* <pre>
|
||||
* Functions.stream(collection.stream());
|
||||
* </pre>
|
||||
*
|
||||
* @param collection The collection, which is being converted into a
|
||||
* {@link FailableStream}.
|
||||
* @param <E> The collections element type. (In turn, the result streams
|
||||
* element type.)
|
||||
* @return The created {@link FailableStream}.
|
||||
*/
|
||||
public static <E> FailableStream<E> stream(final Collection<E> collection) {
|
||||
return new FailableStream<>(collection.stream());
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given stream into a {@link FailableStream}. The
|
||||
* {@link FailableStream} consists of the same elements, than the input stream.
|
||||
* However, failable lambdas, like {@link FailablePredicate},
|
||||
* {@link FailableFunction}, and {@link FailableConsumer} may be applied, rather
|
||||
* than {@link Predicate}, {@link Function}, {@link Consumer}, etc.
|
||||
*
|
||||
* @param stream The stream, which is being converted into a
|
||||
* {@link FailableStream}.
|
||||
* @param <T> The streams element type.
|
||||
* @return The created {@link FailableStream}.
|
||||
*/
|
||||
public static <T> FailableStream<T> stream(final Stream<T> stream) {
|
||||
return new FailableStream<>(stream);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests a predicate and rethrows any exception as a {@link RuntimeException}.
|
||||
*
|
||||
* @param predicate the predicate to test
|
||||
* @param object1 the first input to test by {@code predicate}
|
||||
* @param object2 the second input to test by {@code predicate}
|
||||
* @param <T> the type of the first argument the predicate tests
|
||||
* @param <U> the type of the second argument the predicate tests
|
||||
* @param <E> the type of checked exception the predicate may throw
|
||||
* @return the boolean value returned by the predicate
|
||||
*/
|
||||
public static <T, U, E extends Throwable> boolean test(final FailableBiPredicate<T, U, E> predicate,
|
||||
final T object1, final U object2) {
|
||||
return getAsBoolean(() -> predicate.test(object1, object2));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests a predicate and rethrows any exception as a {@link RuntimeException}.
|
||||
*
|
||||
* @param predicate the predicate to test
|
||||
* @param object the input to test by {@code predicate}
|
||||
* @param <T> the type of argument the predicate tests
|
||||
* @param <E> the type of checked exception the predicate may throw
|
||||
* @return the boolean value returned by the predicate
|
||||
*/
|
||||
public static <T, E extends Throwable> boolean test(final FailablePredicate<T, E> predicate, final T object) {
|
||||
return getAsBoolean(() -> predicate.test(object));
|
||||
}
|
||||
|
||||
/**
|
||||
* A simple try-with-resources implementation, that can be used, if your objects
|
||||
* do not implement the {@link AutoCloseable} interface. The method executes the
|
||||
* {@code action}. The method guarantees, that <em>all</em> the
|
||||
* {@code resources} are being executed, in the given order, afterwards, and
|
||||
* regardless of success, or failure. If either the original action, or any of
|
||||
* the resource action fails, then the <em>first</em> failure (AKA
|
||||
* {@link Throwable} is rethrown. Example use:
|
||||
*
|
||||
* <pre>
|
||||
* final FileInputStream fis = new FileInputStream("my.file");
|
||||
* Functions.tryWithResources(useInputStream(fis), null, () -> fis.close());
|
||||
* </pre>
|
||||
*
|
||||
* @param action The action to execute. This object <em>will</em> always
|
||||
* be invoked.
|
||||
* @param errorHandler An optional error handler, which will be invoked finally,
|
||||
* if any error occurred. The error handler will receive the
|
||||
* first error, AKA {@link Throwable}.
|
||||
* @param resources The resource actions to execute. <em>All</em> resource
|
||||
* actions will be invoked, in the given order. A resource
|
||||
* action is an instance of {@link FailableRunnable}, which
|
||||
* will be executed.
|
||||
* @see #tryWithResources(FailableRunnable, FailableRunnable...)
|
||||
*/
|
||||
@SafeVarargs
|
||||
public static void tryWithResources(final FailableRunnable<? extends Throwable> action,
|
||||
final FailableConsumer<Throwable, ? extends Throwable> errorHandler,
|
||||
final FailableRunnable<? extends Throwable>... resources) {
|
||||
final FailableConsumer<Throwable, ? extends Throwable> actualErrorHandler;
|
||||
if (errorHandler == null) {
|
||||
actualErrorHandler = Failable::rethrow;
|
||||
} else {
|
||||
actualErrorHandler = errorHandler;
|
||||
}
|
||||
if (resources != null) {
|
||||
for (final FailableRunnable<? extends Throwable> failableRunnable : resources) {
|
||||
Objects.requireNonNull(failableRunnable, "runnable");
|
||||
}
|
||||
}
|
||||
Throwable th = null;
|
||||
try {
|
||||
action.run();
|
||||
} catch (final Throwable t) {
|
||||
th = t;
|
||||
}
|
||||
if (resources != null) {
|
||||
for (final FailableRunnable<?> runnable : resources) {
|
||||
try {
|
||||
runnable.run();
|
||||
} catch (final Throwable t) {
|
||||
if (th == null) {
|
||||
th = t;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (th != null) {
|
||||
try {
|
||||
actualErrorHandler.accept(th);
|
||||
} catch (final Throwable t) {
|
||||
throw rethrow(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A simple try-with-resources implementation, that can be used, if your objects
|
||||
* do not implement the {@link AutoCloseable} interface. The method executes the
|
||||
* {@code action}. The method guarantees, that <em>all</em> the
|
||||
* {@code resources} are being executed, in the given order, afterwards, and
|
||||
* regardless of success, or failure. If either the original action, or any of
|
||||
* the resource action fails, then the <em>first</em> failure (AKA
|
||||
* {@link Throwable} is rethrown. Example use:
|
||||
*
|
||||
* <pre>
|
||||
* final FileInputStream fis = new FileInputStream("my.file");
|
||||
* Functions.tryWithResources(useInputStream(fis), () -> fis.close());
|
||||
* </pre>
|
||||
*
|
||||
* @param action The action to execute. This object <em>will</em> always be
|
||||
* invoked.
|
||||
* @param resources The resource actions to execute. <em>All</em> resource
|
||||
* actions will be invoked, in the given order. A resource
|
||||
* action is an instance of {@link FailableRunnable}, which
|
||||
* will be executed.
|
||||
* @see #tryWithResources(FailableRunnable, FailableConsumer,
|
||||
* FailableRunnable...)
|
||||
*/
|
||||
@SafeVarargs
|
||||
public static void tryWithResources(final FailableRunnable<? extends Throwable> action,
|
||||
final FailableRunnable<? extends Throwable>... resources) {
|
||||
tryWithResources(action, null, resources);
|
||||
}
|
||||
|
||||
private Failable() {
|
||||
// empty
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,77 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link BiConsumer} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <T> Consumed type 1.
|
||||
* @param <U> Consumed type 2.
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableBiConsumer<T, U, E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableBiConsumer NOP = (t, u) -> {
|
||||
/* NOP */};
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <T> Consumed type 1.
|
||||
* @param <U> Consumed type 2.
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <T, U, E extends Throwable> FailableBiConsumer<T, U, E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts the consumer.
|
||||
*
|
||||
* @param t the first parameter for the consumable to accept
|
||||
* @param u the second parameter for the consumable to accept
|
||||
* @throws E Thrown when the consumer fails.
|
||||
*/
|
||||
void accept(T t, U u) throws E;
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailableBiConsumer} like
|
||||
* {@link BiConsumer#andThen(BiConsumer)}.
|
||||
*
|
||||
* @param after the operation to perform after this one.
|
||||
* @return a composed {@code FailableBiConsumer} like
|
||||
* {@link BiConsumer#andThen(BiConsumer)}.
|
||||
* @throws NullPointerException when {@code after} is null.
|
||||
*/
|
||||
default FailableBiConsumer<T, U, E> andThen(final FailableBiConsumer<? super T, ? super U, E> after) {
|
||||
Objects.requireNonNull(after);
|
||||
return (t, u) -> {
|
||||
accept(t, u);
|
||||
after.accept(t, u);
|
||||
};
|
||||
}
|
||||
}
|
@ -0,0 +1,79 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link BiFunction} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <T> Input type 1.
|
||||
* @param <U> Input type 2.
|
||||
* @param <R> Return type.
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableBiFunction<T, U, R, E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableBiFunction NOP = (t, u) -> null;
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <T> Consumed type 1.
|
||||
* @param <U> Consumed type 2.
|
||||
* @param <R> Return type.
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <T, U, R, E extends Throwable> FailableBiFunction<T, U, R, E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailableBiFunction} that like
|
||||
* {@link BiFunction#andThen(Function)}.
|
||||
*
|
||||
* @param <V> the output type of the {@code after} function, and of the
|
||||
* composed function.
|
||||
* @param after the operation to perform after this one.
|
||||
* @return a composed {@code FailableBiFunction} that like
|
||||
* {@link BiFunction#andThen(Function)}.
|
||||
* @throws NullPointerException when {@code after} is null.
|
||||
*/
|
||||
default <V> FailableBiFunction<T, U, V, E> andThen(final FailableFunction<? super R, ? extends V, E> after) {
|
||||
Objects.requireNonNull(after);
|
||||
return (final T t, final U u) -> after.apply(apply(t, u));
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies this function.
|
||||
*
|
||||
* @param input1 the first input for the function
|
||||
* @param input2 the second input for the function
|
||||
* @return the result of the function
|
||||
* @throws E Thrown when the function fails.
|
||||
*/
|
||||
R apply(T input1, U input2) throws E;
|
||||
}
|
@ -0,0 +1,113 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.BiPredicate;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link BiPredicate} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <T> Predicate type 1.
|
||||
* @param <U> Predicate type 2.
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableBiPredicate<T, U, E extends Throwable> {
|
||||
|
||||
/** FALSE singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableBiPredicate FALSE = (t, u) -> false;
|
||||
|
||||
/** TRUE singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableBiPredicate TRUE = (t, u) -> true;
|
||||
|
||||
/**
|
||||
* Returns The FALSE singleton.
|
||||
*
|
||||
* @param <T> Consumed type 1.
|
||||
* @param <U> Consumed type 2.
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <T, U, E extends Throwable> FailableBiPredicate<T, U, E> falsePredicate() {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns The FALSE TRUE.
|
||||
*
|
||||
* @param <T> Consumed type 1.
|
||||
* @param <U> Consumed type 2.
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <T, U, E extends Throwable> FailableBiPredicate<T, U, E> truePredicate() {
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailableBiPredicate} like
|
||||
* {@link BiPredicate#and(BiPredicate)}.
|
||||
*
|
||||
* @param other a predicate that will be logically-ANDed with this predicate.
|
||||
* @return a composed {@code FailableBiPredicate} like
|
||||
* {@link BiPredicate#and(BiPredicate)}.
|
||||
* @throws NullPointerException if other is null
|
||||
*/
|
||||
default FailableBiPredicate<T, U, E> and(final FailableBiPredicate<? super T, ? super U, E> other) {
|
||||
Objects.requireNonNull(other);
|
||||
return (final T t, final U u) -> test(t, u) && other.test(t, u);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a predicate that negates this predicate.
|
||||
*
|
||||
* @return a predicate that negates this predicate.
|
||||
*/
|
||||
default FailableBiPredicate<T, U, E> negate() {
|
||||
return (final T t, final U u) -> !test(t, u);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailableBiPredicate} like
|
||||
* {@link BiPredicate#and(BiPredicate)}.
|
||||
*
|
||||
* @param other a predicate that will be logically-ORed with this predicate.
|
||||
* @return a composed {@code FailableBiPredicate} like
|
||||
* {@link BiPredicate#and(BiPredicate)}.
|
||||
* @throws NullPointerException if other is null
|
||||
*/
|
||||
default FailableBiPredicate<T, U, E> or(final FailableBiPredicate<? super T, ? super U, E> other) {
|
||||
Objects.requireNonNull(other);
|
||||
return (final T t, final U u) -> test(t, u) || other.test(t, u);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the predicate.
|
||||
*
|
||||
* @param object1 the first object to test the predicate on
|
||||
* @param object2 the second object to test the predicate on
|
||||
* @return the predicate's evaluation
|
||||
* @throws E Thrown when this predicate fails.
|
||||
*/
|
||||
boolean test(T object1, U object2) throws E;
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link BooleanSupplier} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableBooleanSupplier<E extends Throwable> {
|
||||
|
||||
/**
|
||||
* Supplies a boolean.
|
||||
*
|
||||
* @return a result
|
||||
* @throws E if the supplier fails
|
||||
*/
|
||||
boolean getAsBoolean() throws E;
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link java.util.concurrent.Callable} that
|
||||
* declares a {@code Throwable}.
|
||||
*
|
||||
* @param <R> Return type.
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableCallable<R, E extends Throwable> {
|
||||
|
||||
/**
|
||||
* Calls the callable.
|
||||
*
|
||||
* @return The value returned from the callable
|
||||
* @throws E if the callable fails
|
||||
*/
|
||||
R call() throws E;
|
||||
}
|
@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link Consumer} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <T> Consumed type 1.
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableConsumer<T, E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableConsumer NOP = t -> {
|
||||
/* NOP */};
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <T> Consumed type 1.
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <T, E extends Throwable> FailableConsumer<T, E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts the consumer.
|
||||
*
|
||||
* @param object the parameter for the consumable to accept
|
||||
* @throws E Thrown when the consumer fails.
|
||||
*/
|
||||
void accept(T object) throws E;
|
||||
|
||||
/**
|
||||
* Returns a composed {@code Consumer} like {@link Consumer#andThen(Consumer)}.
|
||||
*
|
||||
* @param after the operation to perform after this operation
|
||||
* @return a composed {@code Consumer} like {@link Consumer#andThen(Consumer)}.
|
||||
* @throws NullPointerException when {@code after} is null
|
||||
*/
|
||||
default FailableConsumer<T, E> andThen(final FailableConsumer<? super T, E> after) {
|
||||
Objects.requireNonNull(after);
|
||||
return (final T t) -> {
|
||||
accept(t);
|
||||
after.accept(t);
|
||||
};
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.DoubleBinaryOperator;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link DoubleBinaryOperator} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableDoubleBinaryOperator<E extends Throwable> {
|
||||
|
||||
/**
|
||||
* Applies this operator to the given operands.
|
||||
*
|
||||
* @param left the first operand
|
||||
* @param right the second operand
|
||||
* @return the operator result
|
||||
* @throws E if the operation fails
|
||||
*/
|
||||
double applyAsDouble(double left, double right) throws E;
|
||||
}
|
@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.DoubleConsumer;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link DoubleConsumer} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableDoubleConsumer<E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableDoubleConsumer NOP = t -> {
|
||||
/* NOP */};
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <E extends Throwable> FailableDoubleConsumer<E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts the consumer.
|
||||
*
|
||||
* @param value the parameter for the consumable to accept
|
||||
* @throws E Thrown when the consumer fails.
|
||||
*/
|
||||
void accept(double value) throws E;
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailableDoubleConsumer} like
|
||||
* {@link DoubleConsumer#andThen(DoubleConsumer)}.
|
||||
*
|
||||
* @param after the operation to perform after this one.
|
||||
* @return a composed {@code FailableDoubleConsumer} like
|
||||
* {@link DoubleConsumer#andThen(DoubleConsumer)}.
|
||||
* @throws NullPointerException when {@code after} is null.
|
||||
*/
|
||||
default FailableDoubleConsumer<E> andThen(final FailableDoubleConsumer<E> after) {
|
||||
Objects.requireNonNull(after);
|
||||
return (final double t) -> {
|
||||
accept(t);
|
||||
after.accept(t);
|
||||
};
|
||||
}
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.DoubleFunction;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link DoubleFunction} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <R> Return type.
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableDoubleFunction<R, E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableDoubleFunction NOP = t -> null;
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <R> Return type.
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <R, E extends Throwable> FailableDoubleFunction<R, E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies this function.
|
||||
*
|
||||
* @param input the input for the function
|
||||
* @return the result of the function
|
||||
* @throws E Thrown when the function fails.
|
||||
*/
|
||||
R apply(double input) throws E;
|
||||
}
|
@ -0,0 +1,107 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.DoublePredicate;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link DoublePredicate} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableDoublePredicate<E extends Throwable> {
|
||||
|
||||
/** FALSE singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableDoublePredicate FALSE = t -> false;
|
||||
|
||||
/** TRUE singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableDoublePredicate TRUE = t -> true;
|
||||
|
||||
/**
|
||||
* Returns The FALSE singleton.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <E extends Throwable> FailableDoublePredicate<E> falsePredicate() {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns The FALSE TRUE.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <E extends Throwable> FailableDoublePredicate<E> truePredicate() {
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailableDoublePredicate} like
|
||||
* {@link DoublePredicate#and(DoublePredicate)}.
|
||||
*
|
||||
* @param other a predicate that will be logically-ANDed with this predicate.
|
||||
* @return a composed {@code FailableDoublePredicate} like
|
||||
* {@link DoublePredicate#and(DoublePredicate)}.
|
||||
* @throws NullPointerException if other is null
|
||||
*/
|
||||
default FailableDoublePredicate<E> and(final FailableDoublePredicate<E> other) {
|
||||
Objects.requireNonNull(other);
|
||||
return t -> test(t) && other.test(t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a predicate that negates this predicate.
|
||||
*
|
||||
* @return a predicate that negates this predicate.
|
||||
*/
|
||||
default FailableDoublePredicate<E> negate() {
|
||||
return t -> !test(t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailableDoublePredicate} like
|
||||
* {@link DoublePredicate#and(DoublePredicate)}.
|
||||
*
|
||||
* @param other a predicate that will be logically-ORed with this predicate.
|
||||
* @return a composed {@code FailableDoublePredicate} like
|
||||
* {@link DoublePredicate#and(DoublePredicate)}.
|
||||
* @throws NullPointerException if other is null
|
||||
*/
|
||||
default FailableDoublePredicate<E> or(final FailableDoublePredicate<E> other) {
|
||||
Objects.requireNonNull(other);
|
||||
return t -> test(t) || other.test(t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the predicate.
|
||||
*
|
||||
* @param value the parameter for the predicate to accept.
|
||||
* @return {@code true} if the input argument matches the predicate,
|
||||
* {@code false} otherwise.
|
||||
* @throws E Thrown when the consumer fails.
|
||||
*/
|
||||
boolean test(double value) throws E;
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.DoubleSupplier;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link DoubleSupplier} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableDoubleSupplier<E extends Throwable> {
|
||||
|
||||
/**
|
||||
* Supplies a double.
|
||||
*
|
||||
* @return a result
|
||||
* @throws E if the supplier fails
|
||||
*/
|
||||
double getAsDouble() throws E;
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.DoubleToIntFunction;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link DoubleToIntFunction} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableDoubleToIntFunction<E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableDoubleToIntFunction NOP = t -> 0;
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <E extends Throwable> FailableDoubleToIntFunction<E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies this function to the given argument.
|
||||
*
|
||||
* @param value the function argument
|
||||
* @return the function result
|
||||
* @throws E Thrown when the function fails.
|
||||
*/
|
||||
int applyAsInt(double value) throws E;
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.DoubleToLongFunction;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link DoubleToLongFunction} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableDoubleToLongFunction<E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableDoubleToLongFunction NOP = t -> 0;
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <E extends Throwable> FailableDoubleToLongFunction<E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies this function to the given argument.
|
||||
*
|
||||
* @param value the function argument
|
||||
* @return the function result
|
||||
* @throws E if the operation fails
|
||||
*/
|
||||
int applyAsLong(double value) throws E;
|
||||
}
|
@ -0,0 +1,94 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.DoubleUnaryOperator;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link DoubleUnaryOperator} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
public interface FailableDoubleUnaryOperator<E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableDoubleUnaryOperator NOP = t -> 0d;
|
||||
|
||||
/**
|
||||
* Returns a unary operator that always returns its input argument.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @return a unary operator that always returns its input argument
|
||||
*/
|
||||
static <E extends Throwable> FailableDoubleUnaryOperator<E> identity() {
|
||||
return t -> t;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <E extends Throwable> FailableDoubleUnaryOperator<E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailableDoubleUnaryOperator} like
|
||||
* {@link DoubleUnaryOperator#andThen(DoubleUnaryOperator)}.
|
||||
*
|
||||
* @param after the operator to apply after this one.
|
||||
* @return a composed {@code FailableDoubleUnaryOperator} like
|
||||
* {@link DoubleUnaryOperator#andThen(DoubleUnaryOperator)}.
|
||||
* @throws NullPointerException if after is null.
|
||||
* @see #compose(FailableDoubleUnaryOperator)
|
||||
*/
|
||||
default FailableDoubleUnaryOperator<E> andThen(final FailableDoubleUnaryOperator<E> after) {
|
||||
Objects.requireNonNull(after);
|
||||
return (final double t) -> after.applyAsDouble(applyAsDouble(t));
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies this operator to the given operand.
|
||||
*
|
||||
* @param operand the operand
|
||||
* @return the operator result
|
||||
* @throws E Thrown when a consumer fails.
|
||||
*/
|
||||
double applyAsDouble(double operand) throws E;
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailableDoubleUnaryOperator} like
|
||||
* {@link DoubleUnaryOperator#compose(DoubleUnaryOperator)}.
|
||||
*
|
||||
* @param before the operator to apply before this one.
|
||||
* @return a composed {@code FailableDoubleUnaryOperator} like
|
||||
* {@link DoubleUnaryOperator#compose(DoubleUnaryOperator)}.
|
||||
* @throws NullPointerException if before is null.
|
||||
* @see #andThen(FailableDoubleUnaryOperator)
|
||||
*/
|
||||
default FailableDoubleUnaryOperator<E> compose(final FailableDoubleUnaryOperator<E> before) {
|
||||
Objects.requireNonNull(before);
|
||||
return (final double v) -> applyAsDouble(before.applyAsDouble(v));
|
||||
}
|
||||
}
|
@ -0,0 +1,103 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link Function} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <T> Input type 1.
|
||||
* @param <R> Return type.
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableFunction<T, R, E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableFunction NOP = t -> null;
|
||||
|
||||
/**
|
||||
* Returns a function that always returns its input argument.
|
||||
*
|
||||
* @param <T> the type of the input and output objects to the function
|
||||
* @param <E> Thrown exception.
|
||||
* @return a function that always returns its input argument
|
||||
*/
|
||||
static <T, E extends Throwable> FailableFunction<T, T, E> identity() {
|
||||
return t -> t;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <T> Consumed type 1.
|
||||
* @param <R> Return type.
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <T, R, E extends Throwable> FailableFunction<T, R, E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailableFunction} like
|
||||
* {@link Function#andThen(Function)}.
|
||||
*
|
||||
* @param <V> the output type of the {@code after} function, and of the composed
|
||||
* function.
|
||||
* @return a composed {@code FailableFunction} like
|
||||
* {@link Function#andThen(Function)}.
|
||||
* @param after the operation to perform after this one.
|
||||
* @throws NullPointerException when {@code after} is null.
|
||||
*/
|
||||
default <V> FailableFunction<T, V, E> andThen(final FailableFunction<? super R, ? extends V, E> after) {
|
||||
Objects.requireNonNull(after);
|
||||
return (final T t) -> after.apply(apply(t));
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies this function.
|
||||
*
|
||||
* @param input the input for the function
|
||||
* @return the result of the function
|
||||
* @throws E Thrown when the function fails.
|
||||
*/
|
||||
R apply(T input) throws E;
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailableFunction} like
|
||||
* {@link Function#compose(Function)}.
|
||||
*
|
||||
* @param <V> the input type to the {@code before} function, and to the
|
||||
* composed function.
|
||||
* @param before the operator to apply before this one.
|
||||
* @return a a composed {@code FailableFunction} like
|
||||
* {@link Function#compose(Function)}.
|
||||
* @throws NullPointerException if before is null.
|
||||
* @see #andThen(FailableFunction)
|
||||
*/
|
||||
default <V> FailableFunction<V, R, E> compose(final FailableFunction<? super V, ? extends T, E> before) {
|
||||
Objects.requireNonNull(before);
|
||||
return (final V v) -> apply(before.apply(v));
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.IntBinaryOperator;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link IntBinaryOperator} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableIntBinaryOperator<E extends Throwable> {
|
||||
|
||||
/**
|
||||
* Applies this operator to the given operands.
|
||||
*
|
||||
* @param left the first operand
|
||||
* @param right the second operand
|
||||
* @return the operator result
|
||||
* @throws E if the operation fails
|
||||
*/
|
||||
int applyAsInt(int left, int right) throws E;
|
||||
}
|
@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.IntConsumer;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link IntConsumer} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableIntConsumer<E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableIntConsumer NOP = t -> {
|
||||
/* NOP */};
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <E extends Throwable> FailableIntConsumer<E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts the consumer.
|
||||
*
|
||||
* @param value the parameter for the consumable to accept
|
||||
* @throws E Thrown when the consumer fails.
|
||||
*/
|
||||
void accept(int value) throws E;
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailableIntConsumer} like
|
||||
* {@link IntConsumer#andThen(IntConsumer)}.
|
||||
*
|
||||
* @param after the operation to perform after this one.
|
||||
* @return a composed {@code FailableLongConsumer} like
|
||||
* {@link IntConsumer#andThen(IntConsumer)}.
|
||||
* @throws NullPointerException if {@code after} is null
|
||||
*/
|
||||
default FailableIntConsumer<E> andThen(final FailableIntConsumer<E> after) {
|
||||
Objects.requireNonNull(after);
|
||||
return (final int t) -> {
|
||||
accept(t);
|
||||
after.accept(t);
|
||||
};
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.IntFunction;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link IntFunction} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <R> Return type.
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableIntFunction<R, E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableIntFunction NOP = t -> null;
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <R> Return type.
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <R, E extends Throwable> FailableIntFunction<R, E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies this function.
|
||||
*
|
||||
* @param input the input for the function
|
||||
* @return the result of the function
|
||||
* @throws E Thrown when the function fails.
|
||||
*/
|
||||
R apply(int input) throws E;
|
||||
}
|
@ -0,0 +1,107 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.IntPredicate;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link IntPredicate} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableIntPredicate<E extends Throwable> {
|
||||
|
||||
/** FALSE singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableIntPredicate FALSE = t -> false;
|
||||
|
||||
/** TRUE singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableIntPredicate TRUE = t -> true;
|
||||
|
||||
/**
|
||||
* Returns The FALSE singleton.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <E extends Throwable> FailableIntPredicate<E> falsePredicate() {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns The FALSE TRUE.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <E extends Throwable> FailableIntPredicate<E> truePredicate() {
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailableIntPredicate} like
|
||||
* {@link IntPredicate#and(IntPredicate)}.
|
||||
*
|
||||
* @param other a predicate that will be logically-ANDed with this predicate.
|
||||
* @return a composed {@code FailableIntPredicate} like
|
||||
* {@link IntPredicate#and(IntPredicate)}.
|
||||
* @throws NullPointerException if other is null
|
||||
*/
|
||||
default FailableIntPredicate<E> and(final FailableIntPredicate<E> other) {
|
||||
Objects.requireNonNull(other);
|
||||
return t -> test(t) && other.test(t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a predicate that negates this predicate.
|
||||
*
|
||||
* @return a predicate that negates this predicate.
|
||||
*/
|
||||
default FailableIntPredicate<E> negate() {
|
||||
return t -> !test(t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailableIntPredicate} like
|
||||
* {@link IntPredicate#and(IntPredicate)}.
|
||||
*
|
||||
* @param other a predicate that will be logically-ORed with this predicate.
|
||||
* @return a composed {@code FailableIntPredicate} like
|
||||
* {@link IntPredicate#and(IntPredicate)}.
|
||||
* @throws NullPointerException if other is null
|
||||
*/
|
||||
default FailableIntPredicate<E> or(final FailableIntPredicate<E> other) {
|
||||
Objects.requireNonNull(other);
|
||||
return t -> test(t) || other.test(t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the predicate.
|
||||
*
|
||||
* @param value the parameter for the predicate to accept.
|
||||
* @return {@code true} if the input argument matches the predicate,
|
||||
* {@code false} otherwise.
|
||||
* @throws E Thrown when the consumer fails.
|
||||
*/
|
||||
boolean test(int value) throws E;
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.IntSupplier;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link IntSupplier} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableIntSupplier<E extends Throwable> {
|
||||
|
||||
/**
|
||||
* Supplies an int.
|
||||
*
|
||||
* @return a result
|
||||
* @throws E if the supplier fails
|
||||
*/
|
||||
int getAsInt() throws E;
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.IntToDoubleFunction;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link IntToDoubleFunction} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableIntToDoubleFunction<E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableIntToDoubleFunction NOP = t -> 0d;
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <E extends Throwable> FailableIntToDoubleFunction<E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies this function to the given argument.
|
||||
*
|
||||
* @param value the function argument
|
||||
* @return the function result
|
||||
* @throws E Thrown when the function fails.
|
||||
*/
|
||||
double applyAsDouble(int value) throws E;
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.IntToLongFunction;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link IntToLongFunction} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableIntToLongFunction<E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableIntToLongFunction NOP = t -> 0L;
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <E extends Throwable> FailableIntToLongFunction<E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies this function to the given argument.
|
||||
*
|
||||
* @param value the function argument
|
||||
* @return the function result
|
||||
* @throws E Thrown when the function fails.
|
||||
*/
|
||||
long applyAsLong(int value) throws E;
|
||||
}
|
@ -0,0 +1,94 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.IntUnaryOperator;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link IntUnaryOperator} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
public interface FailableIntUnaryOperator<E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableIntUnaryOperator NOP = t -> 0;
|
||||
|
||||
/**
|
||||
* Returns a unary operator that always returns its input argument.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @return a unary operator that always returns its input argument
|
||||
*/
|
||||
static <E extends Throwable> FailableIntUnaryOperator<E> identity() {
|
||||
return t -> t;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <E extends Throwable> FailableIntUnaryOperator<E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailableDoubleUnaryOperator} like
|
||||
* {@link IntUnaryOperator#andThen(IntUnaryOperator)}.
|
||||
*
|
||||
* @param after the operator to apply after this one.
|
||||
* @return a composed {@code FailableIntUnaryOperator} like
|
||||
* {@link IntUnaryOperator#andThen(IntUnaryOperator)}.
|
||||
* @throws NullPointerException if after is null.
|
||||
* @see #compose(FailableIntUnaryOperator)
|
||||
*/
|
||||
default FailableIntUnaryOperator<E> andThen(final FailableIntUnaryOperator<E> after) {
|
||||
Objects.requireNonNull(after);
|
||||
return (final int t) -> after.applyAsInt(applyAsInt(t));
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies this operator to the given operand.
|
||||
*
|
||||
* @param operand the operand
|
||||
* @return the operator result
|
||||
* @throws E Thrown when a consumer fails.
|
||||
*/
|
||||
int applyAsInt(int operand) throws E;
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailableIntUnaryOperator} like
|
||||
* {@link IntUnaryOperator#compose(IntUnaryOperator)}.
|
||||
*
|
||||
* @param before the operator to apply before this one.
|
||||
* @return a composed {@code FailableIntUnaryOperator} like
|
||||
* {@link IntUnaryOperator#compose(IntUnaryOperator)}.
|
||||
* @throws NullPointerException if before is null.
|
||||
* @see #andThen(FailableIntUnaryOperator)
|
||||
*/
|
||||
default FailableIntUnaryOperator<E> compose(final FailableIntUnaryOperator<E> before) {
|
||||
Objects.requireNonNull(before);
|
||||
return (final int v) -> applyAsInt(before.applyAsInt(v));
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.LongBinaryOperator;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link LongBinaryOperator} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableLongBinaryOperator<E extends Throwable> {
|
||||
|
||||
/**
|
||||
* Applies this operator to the given operands.
|
||||
*
|
||||
* @param left the first operand
|
||||
* @param right the second operand
|
||||
* @return the operator result
|
||||
* @throws E if the operation fails
|
||||
*/
|
||||
long applyAsLong(long left, long right) throws E;
|
||||
}
|
@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.LongConsumer;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link LongConsumer} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableLongConsumer<E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableLongConsumer NOP = t -> {
|
||||
/* NOP */};
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <E extends Throwable> FailableLongConsumer<E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts the consumer.
|
||||
*
|
||||
* @param object the parameter for the consumable to accept
|
||||
* @throws E Thrown when the consumer fails.
|
||||
*/
|
||||
void accept(long object) throws E;
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailableLongConsumer} like
|
||||
* {@link LongConsumer#andThen(LongConsumer)}.
|
||||
*
|
||||
* @param after the operation to perform after this one.
|
||||
* @return a composed {@code FailableLongConsumer} like
|
||||
* {@link LongConsumer#andThen(LongConsumer)}.
|
||||
* @throws NullPointerException if {@code after} is null
|
||||
*/
|
||||
default FailableLongConsumer<E> andThen(final FailableLongConsumer<E> after) {
|
||||
Objects.requireNonNull(after);
|
||||
return (final long t) -> {
|
||||
accept(t);
|
||||
after.accept(t);
|
||||
};
|
||||
}
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.LongFunction;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link LongFunction} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <R> Return type.
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableLongFunction<R, E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableLongFunction NOP = t -> null;
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <R> Return type.
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <R, E extends Throwable> FailableLongFunction<R, E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies this function.
|
||||
*
|
||||
* @param input the input for the function
|
||||
* @return the result of the function
|
||||
* @throws E Thrown when the function fails.
|
||||
*/
|
||||
R apply(long input) throws E;
|
||||
}
|
@ -0,0 +1,107 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.LongPredicate;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link LongPredicate} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableLongPredicate<E extends Throwable> {
|
||||
|
||||
/** FALSE singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableLongPredicate FALSE = t -> false;
|
||||
|
||||
/** TRUE singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableLongPredicate TRUE = t -> true;
|
||||
|
||||
/**
|
||||
* Returns The FALSE singleton.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <E extends Throwable> FailableLongPredicate<E> falsePredicate() {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns The FALSE TRUE.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <E extends Throwable> FailableLongPredicate<E> truePredicate() {
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailableLongPredicate} like
|
||||
* {@link LongPredicate#and(LongPredicate)}.
|
||||
*
|
||||
* @param other a predicate that will be logically-ANDed with this predicate.
|
||||
* @return a composed {@code FailableLongPredicate} like
|
||||
* {@link LongPredicate#and(LongPredicate)}.
|
||||
* @throws NullPointerException if other is null
|
||||
*/
|
||||
default FailableLongPredicate<E> and(final FailableLongPredicate<E> other) {
|
||||
Objects.requireNonNull(other);
|
||||
return t -> test(t) && other.test(t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a predicate that negates this predicate.
|
||||
*
|
||||
* @return a predicate that negates this predicate.
|
||||
*/
|
||||
default FailableLongPredicate<E> negate() {
|
||||
return t -> !test(t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailableLongPredicate} like
|
||||
* {@link LongPredicate#and(LongPredicate)}.
|
||||
*
|
||||
* @param other a predicate that will be logically-ORed with this predicate.
|
||||
* @return a composed {@code FailableLongPredicate} like
|
||||
* {@link LongPredicate#and(LongPredicate)}.
|
||||
* @throws NullPointerException if other is null
|
||||
*/
|
||||
default FailableLongPredicate<E> or(final FailableLongPredicate<E> other) {
|
||||
Objects.requireNonNull(other);
|
||||
return t -> test(t) || other.test(t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the predicate.
|
||||
*
|
||||
* @param value the parameter for the predicate to accept.
|
||||
* @return {@code true} if the input argument matches the predicate,
|
||||
* {@code false} otherwise.
|
||||
* @throws E Thrown when the consumer fails.
|
||||
*/
|
||||
boolean test(long value) throws E;
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.LongSupplier;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link LongSupplier} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableLongSupplier<E extends Throwable> {
|
||||
|
||||
/**
|
||||
* Supplies a long.
|
||||
*
|
||||
* @return a result
|
||||
* @throws E if the supplier fails
|
||||
*/
|
||||
long getAsLong() throws E;
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.LongToDoubleFunction;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link LongToDoubleFunction} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableLongToDoubleFunction<E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableLongToDoubleFunction NOP = t -> 0d;
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <E extends Throwable> FailableLongToDoubleFunction<E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies this function to the given argument.
|
||||
*
|
||||
* @param value the function argument
|
||||
* @return the function result
|
||||
* @throws E Thrown when the function fails.
|
||||
*/
|
||||
double applyAsDouble(long value) throws E;
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.LongToIntFunction;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link LongToIntFunction} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableLongToIntFunction<E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableLongToIntFunction NOP = t -> 0;
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <E extends Throwable> FailableLongToIntFunction<E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies this function to the given argument.
|
||||
*
|
||||
* @param value the function argument
|
||||
* @return the function result
|
||||
* @throws E Thrown when the function fails.
|
||||
*/
|
||||
int applyAsInt(long value) throws E;
|
||||
}
|
@ -0,0 +1,94 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.LongUnaryOperator;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link LongUnaryOperator} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
public interface FailableLongUnaryOperator<E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableLongUnaryOperator NOP = t -> 0L;
|
||||
|
||||
/**
|
||||
* Returns a unary operator that always returns its input argument.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @return a unary operator that always returns its input argument
|
||||
*/
|
||||
static <E extends Throwable> FailableLongUnaryOperator<E> identity() {
|
||||
return t -> t;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <E extends Throwable> FailableLongUnaryOperator<E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailableDoubleUnaryOperator} like
|
||||
* {@link LongUnaryOperator#andThen(LongUnaryOperator)}.
|
||||
*
|
||||
* @param after the operator to apply after this one.
|
||||
* @return a composed {@code FailableLongUnaryOperator} like
|
||||
* {@link LongUnaryOperator#andThen(LongUnaryOperator)}.
|
||||
* @throws NullPointerException if after is null.
|
||||
* @see #compose(FailableLongUnaryOperator)
|
||||
*/
|
||||
default FailableLongUnaryOperator<E> andThen(final FailableLongUnaryOperator<E> after) {
|
||||
Objects.requireNonNull(after);
|
||||
return (final long t) -> after.applyAsLong(applyAsLong(t));
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies this operator to the given operand.
|
||||
*
|
||||
* @param operand the operand
|
||||
* @return the operator result
|
||||
* @throws E Thrown when a consumer fails.
|
||||
*/
|
||||
long applyAsLong(long operand) throws E;
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailableLongUnaryOperator} like
|
||||
* {@link LongUnaryOperator#compose(LongUnaryOperator)}.
|
||||
*
|
||||
* @param before the operator to apply before this one.
|
||||
* @return a composed {@code FailableLongUnaryOperator} like
|
||||
* {@link LongUnaryOperator#compose(LongUnaryOperator)}.
|
||||
* @throws NullPointerException if before is null.
|
||||
* @see #andThen(FailableLongUnaryOperator)
|
||||
*/
|
||||
default FailableLongUnaryOperator<E> compose(final FailableLongUnaryOperator<E> before) {
|
||||
Objects.requireNonNull(before);
|
||||
return (final long v) -> applyAsLong(before.applyAsLong(v));
|
||||
}
|
||||
}
|
@ -0,0 +1,57 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.ObjDoubleConsumer;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link ObjDoubleConsumer} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <T> the type of the object argument to the operation.
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableObjDoubleConsumer<T, E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableObjDoubleConsumer NOP = (t, u) -> {
|
||||
/* NOP */};
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <T> the type of the object argument to the operation.
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <T, E extends Throwable> FailableObjDoubleConsumer<T, E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts the consumer.
|
||||
*
|
||||
* @param object the object parameter for the consumable to accept.
|
||||
* @param value the double parameter for the consumable to accept.
|
||||
* @throws E Thrown when the consumer fails.
|
||||
*/
|
||||
void accept(T object, double value) throws E;
|
||||
}
|
@ -0,0 +1,57 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.ObjIntConsumer;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link ObjIntConsumer} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <T> the type of the object argument to the operation.
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableObjIntConsumer<T, E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableObjIntConsumer NOP = (t, u) -> {
|
||||
/* NOP */};
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <T> the type of the object argument to the operation.
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <T, E extends Throwable> FailableObjIntConsumer<T, E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts the consumer.
|
||||
*
|
||||
* @param object the object parameter for the consumable to accept.
|
||||
* @param value the int parameter for the consumable to accept.
|
||||
* @throws E Thrown when the consumer fails.
|
||||
*/
|
||||
void accept(T object, int value) throws E;
|
||||
}
|
@ -0,0 +1,57 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.ObjLongConsumer;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link ObjLongConsumer} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <T> the type of the object argument to the operation.
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableObjLongConsumer<T, E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableObjLongConsumer NOP = (t, u) -> {
|
||||
/* NOP */};
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <T> the type of the object argument to the operation.
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <T, E extends Throwable> FailableObjLongConsumer<T, E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts the consumer.
|
||||
*
|
||||
* @param object the object parameter for the consumable to accept.
|
||||
* @param value the long parameter for the consumable to accept.
|
||||
* @throws E Thrown when the consumer fails.
|
||||
*/
|
||||
void accept(T object, long value) throws E;
|
||||
}
|
@ -0,0 +1,109 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link Predicate} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <T> Predicate type.
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailablePredicate<T, E extends Throwable> {
|
||||
|
||||
/** FALSE singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailablePredicate FALSE = t -> false;
|
||||
|
||||
/** TRUE singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailablePredicate TRUE = t -> true;
|
||||
|
||||
/**
|
||||
* Returns The FALSE singleton.
|
||||
*
|
||||
* @param <T> Predicate type.
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <T, E extends Throwable> FailablePredicate<T, E> falsePredicate() {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns The FALSE TRUE.
|
||||
*
|
||||
* @param <T> Predicate type.
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <T, E extends Throwable> FailablePredicate<T, E> truePredicate() {
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailablePredicate} like
|
||||
* {@link Predicate#and(Predicate)}.
|
||||
*
|
||||
* @param other a predicate that will be logically-ANDed with this predicate.
|
||||
* @return a composed {@code FailablePredicate} like
|
||||
* {@link Predicate#and(Predicate)}.
|
||||
* @throws NullPointerException if other is null
|
||||
*/
|
||||
default FailablePredicate<T, E> and(final FailablePredicate<? super T, E> other) {
|
||||
Objects.requireNonNull(other);
|
||||
return t -> test(t) && other.test(t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a predicate that negates this predicate.
|
||||
*
|
||||
* @return a predicate that negates this predicate.
|
||||
*/
|
||||
default FailablePredicate<T, E> negate() {
|
||||
return t -> !test(t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a composed {@code FailablePredicate} like
|
||||
* {@link Predicate#and(Predicate)}.
|
||||
*
|
||||
* @param other a predicate that will be logically-ORed with this predicate.
|
||||
* @return a composed {@code FailablePredicate} like
|
||||
* {@link Predicate#and(Predicate)}.
|
||||
* @throws NullPointerException if other is null
|
||||
*/
|
||||
default FailablePredicate<T, E> or(final FailablePredicate<? super T, E> other) {
|
||||
Objects.requireNonNull(other);
|
||||
return t -> test(t) || other.test(t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the predicate.
|
||||
*
|
||||
* @param object the object to test the predicate on
|
||||
* @return the predicate's evaluation
|
||||
* @throws E if the predicate fails
|
||||
*/
|
||||
boolean test(T object) throws E;
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link Runnable} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableRunnable<E extends Throwable> {
|
||||
|
||||
/**
|
||||
* Runs the function.
|
||||
*
|
||||
* @throws E Thrown when the function fails.
|
||||
*/
|
||||
void run() throws E;
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.IntSupplier;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link IntSupplier} but for {@code short} that
|
||||
* declares a {@code Throwable}.
|
||||
*
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.12.0
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableShortSupplier<E extends Throwable> {
|
||||
|
||||
/**
|
||||
* Supplies an int.
|
||||
*
|
||||
* @return a result
|
||||
* @throws E if the supplier fails
|
||||
*/
|
||||
short getAsShort() throws E;
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link Supplier} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <R> Return type.
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableSupplier<R, E extends Throwable> {
|
||||
|
||||
/**
|
||||
* Supplies an object
|
||||
*
|
||||
* @return a result
|
||||
* @throws E if the supplier fails
|
||||
*/
|
||||
R get() throws E;
|
||||
}
|
@ -0,0 +1,59 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.ToDoubleBiFunction;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link ToDoubleBiFunction} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <T> the type of the first argument to the function
|
||||
* @param <U> the type of the second argument to the function
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableToDoubleBiFunction<T, U, E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableToDoubleBiFunction NOP = (t, u) -> 0d;
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <T> the type of the first argument to the function
|
||||
* @param <U> the type of the second argument to the function
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <T, U, E extends Throwable> FailableToDoubleBiFunction<T, U, E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies this function to the given arguments.
|
||||
*
|
||||
* @param t the first function argument
|
||||
* @param u the second function argument
|
||||
* @return the function result
|
||||
* @throws E Thrown when the function fails.
|
||||
*/
|
||||
double applyAsDouble(T t, U u) throws E;
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.ToDoubleFunction;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link ToDoubleFunction} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <T> the type of the argument to the function
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableToDoubleFunction<T, E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableToDoubleFunction NOP = t -> 0d;
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <T> the type of the argument to the function
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <T, E extends Throwable> FailableToDoubleFunction<T, E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies this function to the given arguments.
|
||||
*
|
||||
* @param t the first function argument
|
||||
* @return the function result
|
||||
* @throws E Thrown when the function fails.
|
||||
*/
|
||||
double applyAsDouble(T t) throws E;
|
||||
}
|
@ -0,0 +1,59 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.ToIntBiFunction;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link ToIntBiFunction} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <T> the type of the first argument to the function
|
||||
* @param <U> the type of the second argument to the function
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableToIntBiFunction<T, U, E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableToIntBiFunction NOP = (t, u) -> 0;
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <T> the type of the first argument to the function
|
||||
* @param <U> the type of the second argument to the function
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <T, U, E extends Throwable> FailableToIntBiFunction<T, U, E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies this function to the given arguments.
|
||||
*
|
||||
* @param t the first function argument
|
||||
* @param u the second function argument
|
||||
* @return the function result
|
||||
* @throws E Thrown when the function fails.
|
||||
*/
|
||||
int applyAsInt(T t, U u) throws E;
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.ToIntFunction;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link ToIntFunction} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <T> the type of the argument to the function
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableToIntFunction<T, E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableToIntFunction NOP = t -> 0;
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <T> the type of the argument to the function
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <T, E extends Throwable> FailableToIntFunction<T, E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies this function to the given arguments.
|
||||
*
|
||||
* @param t the first function argument
|
||||
* @return the function result
|
||||
* @throws E Thrown when the function fails.
|
||||
*/
|
||||
int applyAsInt(T t) throws E;
|
||||
}
|
@ -0,0 +1,59 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.ToLongBiFunction;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link ToLongBiFunction} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <T> the type of the first argument to the function
|
||||
* @param <U> the type of the second argument to the function
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableToLongBiFunction<T, U, E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableToLongBiFunction NOP = (t, u) -> 0;
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <T> the type of the first argument to the function
|
||||
* @param <U> the type of the second argument to the function
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <T, U, E extends Throwable> FailableToLongBiFunction<T, U, E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies this function to the given arguments.
|
||||
*
|
||||
* @param t the first function argument
|
||||
* @param u the second function argument
|
||||
* @return the function result
|
||||
* @throws E Thrown when the function fails.
|
||||
*/
|
||||
long applyAsLong(T t, U u) throws E;
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.ToLongFunction;
|
||||
|
||||
/**
|
||||
* A functional interface like {@link ToLongFunction} that declares a
|
||||
* {@code Throwable}.
|
||||
*
|
||||
* @param <T> the type of the first argument to the function
|
||||
* @param <E> Thrown exception.
|
||||
* @since 3.11
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FailableToLongFunction<T, E extends Throwable> {
|
||||
|
||||
/** NOP singleton */
|
||||
@SuppressWarnings("rawtypes")
|
||||
FailableToLongFunction NOP = t -> 0L;
|
||||
|
||||
/**
|
||||
* Returns The NOP singleton.
|
||||
*
|
||||
* @param <T> the type of the argument to the function
|
||||
* @param <E> Thrown exception.
|
||||
* @return The NOP singleton.
|
||||
*/
|
||||
static <T, E extends Throwable> FailableToLongFunction<T, E> nop() {
|
||||
return NOP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies this function to the given arguments.
|
||||
*
|
||||
* @param t the first function argument
|
||||
* @return the function result
|
||||
* @throws E Thrown when the function fails.
|
||||
*/
|
||||
long applyAsLong(T t) throws E;
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.function.BiFunction;
|
||||
|
||||
/**
|
||||
* A function that accepts two arguments and produces a boolean result. This is
|
||||
* the {@code boolean}-producing primitive specialization for
|
||||
* {@link BiFunction}.
|
||||
*
|
||||
* @param <T> the type of the first argument to the function.
|
||||
* @param <U> the type of the second argument to the function.
|
||||
*
|
||||
* @see BiFunction
|
||||
* @since 3.12.0
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface ToBooleanBiFunction<T, U> {
|
||||
|
||||
/**
|
||||
* Applies this function to the given arguments.
|
||||
*
|
||||
* @param t the first function argument.
|
||||
* @param u the second function argument.
|
||||
* @return the function result.
|
||||
*/
|
||||
boolean applyAsBoolean(T t, U u);
|
||||
}
|
@ -0,0 +1,69 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.function;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* Represents a function that accepts three arguments and produces a result.
|
||||
* This is the three-arity specialization of {@link Function}.
|
||||
*
|
||||
* <p>
|
||||
* This is a <a href="package-summary.html">functional interface</a> whose
|
||||
* functional method is {@link #apply(Object, Object, Object)}.
|
||||
* </p>
|
||||
*
|
||||
* @param <T> the type of the first argument to the function
|
||||
* @param <U> the type of the second argument to the function
|
||||
* @param <V> the type of the third argument to the function
|
||||
* @param <R> the type of the result of the function
|
||||
*
|
||||
* @see Function
|
||||
* @since 3.12.0
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface TriFunction<T, U, V, R> {
|
||||
|
||||
/**
|
||||
* Applies this function to the given arguments.
|
||||
*
|
||||
* @param t the first function argument
|
||||
* @param u the second function argument
|
||||
* @param v the third function argument
|
||||
* @return the function result
|
||||
*/
|
||||
R apply(T t, U u, V v);
|
||||
|
||||
/**
|
||||
* Returns a composed function that first applies this function to its input,
|
||||
* and then applies the {@code after} function to the result. If evaluation of
|
||||
* either function throws an exception, it is relayed to the caller of the
|
||||
* composed function.
|
||||
*
|
||||
* @param <W> the type of output of the {@code after} function, and of the
|
||||
* composed function
|
||||
* @param after the function to apply after this function is applied
|
||||
* @return a composed function that first applies this function and then applies
|
||||
* the {@code after} function
|
||||
* @throws NullPointerException if after is null
|
||||
*/
|
||||
default <W> TriFunction<T, U, V, W> andThen(final Function<? super R, ? extends W> after) {
|
||||
Objects.requireNonNull(after);
|
||||
return (final T t, final U u, final V v) -> after.apply(apply(t, u, v));
|
||||
}
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.
|
||||
*/
|
||||
/**
|
||||
* Provides functional interfaces to complement those in
|
||||
* {@code java.lang.function} and utilities for working with Java 8 lambdas.
|
||||
*
|
||||
* <p>
|
||||
* Contains failable functional interfaces that address the fact that lambdas
|
||||
* are supposed not to throw Exceptions, at least not checked Exceptions, A.K.A.
|
||||
* instances of {@link java.lang.Exception}. A failable functional interface
|
||||
* declares a type of Exception that may be raised if the function fails.
|
||||
* </p>
|
||||
*
|
||||
* @since 3.11
|
||||
*/
|
||||
package org.apache.commons.lang3.function;
|
1025
sources/main/java/org/apache/commons/lang3/math/Fraction.java
Normal file
1025
sources/main/java/org/apache/commons/lang3/math/Fraction.java
Normal file
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,295 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.math;
|
||||
|
||||
import org.apache.commons.lang3.Validate;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Provides IEEE-754r variants of NumberUtils methods.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* See: <a href=
|
||||
* "http://en.wikipedia.org/wiki/IEEE_754r">http://en.wikipedia.org/wiki/IEEE_754r</a>
|
||||
* </p>
|
||||
*
|
||||
* @since 2.4
|
||||
*/
|
||||
public class IEEE754rUtils {
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Returns the minimum value in an array.
|
||||
* </p>
|
||||
*
|
||||
* @param array an array, must not be null or empty
|
||||
* @return the minimum value in the array
|
||||
* @throws NullPointerException if {@code array} is {@code null}
|
||||
* @throws IllegalArgumentException if {@code array} is empty
|
||||
* @since 3.4 Changed signature from min(double[]) to min(double...)
|
||||
*/
|
||||
public static double min(final double... array) {
|
||||
Validate.notNull(array, "array");
|
||||
Validate.isTrue(array.length != 0, "Array cannot be empty.");
|
||||
|
||||
// Finds and returns min
|
||||
double min = array[0];
|
||||
for (int i = 1; i < array.length; i++) {
|
||||
min = min(array[i], min);
|
||||
}
|
||||
|
||||
return min;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Returns the minimum value in an array.
|
||||
* </p>
|
||||
*
|
||||
* @param array an array, must not be null or empty
|
||||
* @return the minimum value in the array
|
||||
* @throws NullPointerException if {@code array} is {@code null}
|
||||
* @throws IllegalArgumentException if {@code array} is empty
|
||||
* @since 3.4 Changed signature from min(float[]) to min(float...)
|
||||
*/
|
||||
public static float min(final float... array) {
|
||||
Validate.notNull(array, "array");
|
||||
Validate.isTrue(array.length != 0, "Array cannot be empty.");
|
||||
|
||||
// Finds and returns min
|
||||
float min = array[0];
|
||||
for (int i = 1; i < array.length; i++) {
|
||||
min = min(array[i], min);
|
||||
}
|
||||
|
||||
return min;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets the minimum of three {@code double} values.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* NaN is only returned if all numbers are NaN as per IEEE-754r.
|
||||
* </p>
|
||||
*
|
||||
* @param a value 1
|
||||
* @param b value 2
|
||||
* @param c value 3
|
||||
* @return the smallest of the values
|
||||
*/
|
||||
public static double min(final double a, final double b, final double c) {
|
||||
return min(min(a, b), c);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets the minimum of two {@code double} values.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* NaN is only returned if all numbers are NaN as per IEEE-754r.
|
||||
* </p>
|
||||
*
|
||||
* @param a value 1
|
||||
* @param b value 2
|
||||
* @return the smallest of the values
|
||||
*/
|
||||
public static double min(final double a, final double b) {
|
||||
if (Double.isNaN(a)) {
|
||||
return b;
|
||||
} else if (Double.isNaN(b)) {
|
||||
return a;
|
||||
} else {
|
||||
return Math.min(a, b);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets the minimum of three {@code float} values.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* NaN is only returned if all numbers are NaN as per IEEE-754r.
|
||||
* </p>
|
||||
*
|
||||
* @param a value 1
|
||||
* @param b value 2
|
||||
* @param c value 3
|
||||
* @return the smallest of the values
|
||||
*/
|
||||
public static float min(final float a, final float b, final float c) {
|
||||
return min(min(a, b), c);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets the minimum of two {@code float} values.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* NaN is only returned if all numbers are NaN as per IEEE-754r.
|
||||
* </p>
|
||||
*
|
||||
* @param a value 1
|
||||
* @param b value 2
|
||||
* @return the smallest of the values
|
||||
*/
|
||||
public static float min(final float a, final float b) {
|
||||
if (Float.isNaN(a)) {
|
||||
return b;
|
||||
} else if (Float.isNaN(b)) {
|
||||
return a;
|
||||
} else {
|
||||
return Math.min(a, b);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Returns the maximum value in an array.
|
||||
* </p>
|
||||
*
|
||||
* @param array an array, must not be null or empty
|
||||
* @return the minimum value in the array
|
||||
* @throws NullPointerException if {@code array} is {@code null}
|
||||
* @throws IllegalArgumentException if {@code array} is empty
|
||||
* @since 3.4 Changed signature from max(double[]) to max(double...)
|
||||
*/
|
||||
public static double max(final double... array) {
|
||||
Validate.notNull(array, "array");
|
||||
Validate.isTrue(array.length != 0, "Array cannot be empty.");
|
||||
|
||||
// Finds and returns max
|
||||
double max = array[0];
|
||||
for (int j = 1; j < array.length; j++) {
|
||||
max = max(array[j], max);
|
||||
}
|
||||
|
||||
return max;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Returns the maximum value in an array.
|
||||
* </p>
|
||||
*
|
||||
* @param array an array, must not be null or empty
|
||||
* @return the minimum value in the array
|
||||
* @throws NullPointerException if {@code array} is {@code null}
|
||||
* @throws IllegalArgumentException if {@code array} is empty
|
||||
* @since 3.4 Changed signature from max(float[]) to max(float...)
|
||||
*/
|
||||
public static float max(final float... array) {
|
||||
Validate.notNull(array, "array");
|
||||
Validate.isTrue(array.length != 0, "Array cannot be empty.");
|
||||
|
||||
// Finds and returns max
|
||||
float max = array[0];
|
||||
for (int j = 1; j < array.length; j++) {
|
||||
max = max(array[j], max);
|
||||
}
|
||||
|
||||
return max;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets the maximum of three {@code double} values.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* NaN is only returned if all numbers are NaN as per IEEE-754r.
|
||||
* </p>
|
||||
*
|
||||
* @param a value 1
|
||||
* @param b value 2
|
||||
* @param c value 3
|
||||
* @return the largest of the values
|
||||
*/
|
||||
public static double max(final double a, final double b, final double c) {
|
||||
return max(max(a, b), c);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets the maximum of two {@code double} values.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* NaN is only returned if all numbers are NaN as per IEEE-754r.
|
||||
* </p>
|
||||
*
|
||||
* @param a value 1
|
||||
* @param b value 2
|
||||
* @return the largest of the values
|
||||
*/
|
||||
public static double max(final double a, final double b) {
|
||||
if (Double.isNaN(a)) {
|
||||
return b;
|
||||
} else if (Double.isNaN(b)) {
|
||||
return a;
|
||||
} else {
|
||||
return Math.max(a, b);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets the maximum of three {@code float} values.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* NaN is only returned if all numbers are NaN as per IEEE-754r.
|
||||
* </p>
|
||||
*
|
||||
* @param a value 1
|
||||
* @param b value 2
|
||||
* @param c value 3
|
||||
* @return the largest of the values
|
||||
*/
|
||||
public static float max(final float a, final float b, final float c) {
|
||||
return max(max(a, b), c);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Gets the maximum of two {@code float} values.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* NaN is only returned if all numbers are NaN as per IEEE-754r.
|
||||
* </p>
|
||||
*
|
||||
* @param a value 1
|
||||
* @param b value 2
|
||||
* @return the largest of the values
|
||||
*/
|
||||
public static float max(final float a, final float b) {
|
||||
if (Float.isNaN(a)) {
|
||||
return b;
|
||||
} else if (Float.isNaN(b)) {
|
||||
return a;
|
||||
} else {
|
||||
return Math.max(a, b);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
2027
sources/main/java/org/apache/commons/lang3/math/NumberUtils.java
Normal file
2027
sources/main/java/org/apache/commons/lang3/math/NumberUtils.java
Normal file
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,47 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.
|
||||
*/
|
||||
/**
|
||||
* <p>
|
||||
* Extends {@link java.math} for business mathematical classes. This package is
|
||||
* intended for business mathematical use, not scientific use. See
|
||||
* <a href="https://commons.apache.org/math/">Commons Math</a> for a more
|
||||
* complete set of mathematical classes. These classes are immutable, and
|
||||
* therefore thread-safe.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Although Commons Math also exists, some basic mathematical functions are
|
||||
* contained within Lang. These include classes to a
|
||||
* {@link org.apache.commons.lang3.math.Fraction} class, various utilities for
|
||||
* random numbers, and the flagship class,
|
||||
* {@link org.apache.commons.lang3.math.NumberUtils} which contains a handful of
|
||||
* classic number functions.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* There are two aspects of this package that should be highlighted. The first
|
||||
* is {@link org.apache.commons.lang3.math.NumberUtils#createNumber(String)}, a
|
||||
* method which does its best to convert a String into a
|
||||
* {@link java.lang.Number} object. You have no idea what type of Number it will
|
||||
* return, so you should call the relevant {@code xxxValue} method when you
|
||||
* reach the point of needing a number. NumberUtils also has a related
|
||||
* {@link org.apache.commons.lang3.math.NumberUtils#isCreatable(String)} method.
|
||||
* </p>
|
||||
*
|
||||
* @since 2.0
|
||||
*/
|
||||
package org.apache.commons.lang3.math;
|
@ -0,0 +1,53 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.mutable;
|
||||
|
||||
/**
|
||||
* Provides mutable access to a value.
|
||||
* <p>
|
||||
* {@code Mutable} is used as a generic interface to the implementations in this
|
||||
* package.
|
||||
* <p>
|
||||
* A typical use case would be to enable a primitive or string to be passed to a
|
||||
* method and allow that method to effectively change the value of the
|
||||
* primitive/string. Another use case is to store a frequently changing
|
||||
* primitive in a collection (for example a total in a map) without needing to
|
||||
* create new Integer/Long wrapper objects.
|
||||
*
|
||||
* @param <T> the type to set and get
|
||||
* @since 2.1
|
||||
*/
|
||||
public interface Mutable<T> {
|
||||
|
||||
/**
|
||||
* Gets the value of this mutable.
|
||||
*
|
||||
* @return the stored value
|
||||
*/
|
||||
T getValue();
|
||||
|
||||
/**
|
||||
* Sets the value of this mutable.
|
||||
*
|
||||
* @param value the value to store
|
||||
* @throws NullPointerException if the object is null and null is invalid
|
||||
* @throws ClassCastException if the type is invalid
|
||||
*/
|
||||
void setValue(T value);
|
||||
|
||||
}
|
@ -0,0 +1,213 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.mutable;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.apache.commons.lang3.BooleanUtils;
|
||||
|
||||
/**
|
||||
* A mutable {@code boolean} wrapper.
|
||||
* <p>
|
||||
* Note that as MutableBoolean does not extend Boolean, it is not treated by
|
||||
* HString.format as a Boolean parameter.
|
||||
*
|
||||
* @see Boolean
|
||||
* @since 2.2
|
||||
*/
|
||||
public class MutableBoolean implements Mutable<Boolean>, Serializable, Comparable<MutableBoolean> {
|
||||
|
||||
/**
|
||||
* Required for serialization support.
|
||||
*
|
||||
* @see java.io.Serializable
|
||||
*/
|
||||
private static final long serialVersionUID = -4830728138360036487L;
|
||||
|
||||
/** The mutable value. */
|
||||
private boolean value;
|
||||
|
||||
/**
|
||||
* Constructs a new MutableBoolean with the default value of false.
|
||||
*/
|
||||
public MutableBoolean() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new MutableBoolean with the specified value.
|
||||
*
|
||||
* @param value the initial value to store
|
||||
*/
|
||||
public MutableBoolean(final boolean value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new MutableBoolean with the specified value.
|
||||
*
|
||||
* @param value the initial value to store, not null
|
||||
* @throws NullPointerException if the object is null
|
||||
*/
|
||||
public MutableBoolean(final Boolean value) {
|
||||
this.value = value.booleanValue();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Gets the value as a Boolean instance.
|
||||
*
|
||||
* @return the value as a Boolean, never null
|
||||
*/
|
||||
@Override
|
||||
public Boolean getValue() {
|
||||
return Boolean.valueOf(this.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value.
|
||||
*
|
||||
* @param value the value to set
|
||||
*/
|
||||
public void setValue(final boolean value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value to false.
|
||||
*
|
||||
* @since 3.3
|
||||
*/
|
||||
public void setFalse() {
|
||||
this.value = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value to true.
|
||||
*
|
||||
* @since 3.3
|
||||
*/
|
||||
public void setTrue() {
|
||||
this.value = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value from any Boolean instance.
|
||||
*
|
||||
* @param value the value to set, not null
|
||||
* @throws NullPointerException if the object is null
|
||||
*/
|
||||
@Override
|
||||
public void setValue(final Boolean value) {
|
||||
this.value = value.booleanValue();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Checks if the current value is {@code true}.
|
||||
*
|
||||
* @return {@code true} if the current value is {@code true}
|
||||
* @since 2.5
|
||||
*/
|
||||
public boolean isTrue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the current value is {@code false}.
|
||||
*
|
||||
* @return {@code true} if the current value is {@code false}
|
||||
* @since 2.5
|
||||
*/
|
||||
public boolean isFalse() {
|
||||
return !value;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Returns the value of this MutableBoolean as a boolean.
|
||||
*
|
||||
* @return the boolean value represented by this object.
|
||||
*/
|
||||
public boolean booleanValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Gets this mutable as an instance of Boolean.
|
||||
*
|
||||
* @return a Boolean instance containing the value from this mutable, never null
|
||||
* @since 2.5
|
||||
*/
|
||||
public Boolean toBoolean() {
|
||||
return Boolean.valueOf(booleanValue());
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Compares this object to the specified object. The result is {@code true} if
|
||||
* and only if the argument is not {@code null} and is an {@code MutableBoolean}
|
||||
* object that contains the same {@code boolean} value as this object.
|
||||
*
|
||||
* @param obj the object to compare with, null returns false
|
||||
* @return {@code true} if the objects are the same; {@code false} otherwise.
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (obj instanceof MutableBoolean) {
|
||||
return value == ((MutableBoolean) obj).booleanValue();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a suitable hash code for this mutable.
|
||||
*
|
||||
* @return the hash code returned by {@code Boolean.TRUE} or
|
||||
* {@code Boolean.FALSE}
|
||||
*/
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return value ? Boolean.TRUE.hashCode() : Boolean.FALSE.hashCode();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Compares this mutable to another in ascending order.
|
||||
*
|
||||
* @param other the other mutable to compare to, not null
|
||||
* @return negative if this is less, zero if equal, positive if greater where
|
||||
* false is less than true
|
||||
*/
|
||||
@Override
|
||||
public int compareTo(final MutableBoolean other) {
|
||||
return BooleanUtils.compare(this.value, other.value);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Returns the String value of this mutable.
|
||||
*
|
||||
* @return the mutable value as a string
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.valueOf(value);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,404 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.mutable;
|
||||
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
|
||||
/**
|
||||
* A mutable {@code byte} wrapper.
|
||||
* <p>
|
||||
* Note that as MutableByte does not extend Byte, it is not treated by
|
||||
* HString.format as a Byte parameter.
|
||||
*
|
||||
* @see Byte
|
||||
* @since 2.1
|
||||
*/
|
||||
public class MutableByte extends Number implements Comparable<MutableByte>, Mutable<Number> {
|
||||
|
||||
/**
|
||||
* Required for serialization support.
|
||||
*
|
||||
* @see java.io.Serializable
|
||||
*/
|
||||
private static final long serialVersionUID = -1585823265L;
|
||||
|
||||
/** The mutable value. */
|
||||
private byte value;
|
||||
|
||||
/**
|
||||
* Constructs a new MutableByte with the default value of zero.
|
||||
*/
|
||||
public MutableByte() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new MutableByte with the specified value.
|
||||
*
|
||||
* @param value the initial value to store
|
||||
*/
|
||||
public MutableByte(final byte value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new MutableByte with the specified value.
|
||||
*
|
||||
* @param value the initial value to store, not null
|
||||
* @throws NullPointerException if the object is null
|
||||
*/
|
||||
public MutableByte(final Number value) {
|
||||
this.value = value.byteValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new MutableByte parsing the given string.
|
||||
*
|
||||
* @param value the string to parse, not null
|
||||
* @throws NumberFormatException if the string cannot be parsed into a byte
|
||||
* @since 2.5
|
||||
*/
|
||||
public MutableByte(final String value) {
|
||||
this.value = Byte.parseByte(value);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Gets the value as a Byte instance.
|
||||
*
|
||||
* @return the value as a Byte, never null
|
||||
*/
|
||||
@Override
|
||||
public Byte getValue() {
|
||||
return Byte.valueOf(this.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value.
|
||||
*
|
||||
* @param value the value to set
|
||||
*/
|
||||
public void setValue(final byte value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value from any Number instance.
|
||||
*
|
||||
* @param value the value to set, not null
|
||||
* @throws NullPointerException if the object is null
|
||||
*/
|
||||
@Override
|
||||
public void setValue(final Number value) {
|
||||
this.value = value.byteValue();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Increments the value.
|
||||
*
|
||||
* @since 2.2
|
||||
*/
|
||||
public void increment() {
|
||||
value++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments this instance's value by 1; this method returns the value
|
||||
* associated with the instance immediately prior to the increment operation.
|
||||
* This method is not thread safe.
|
||||
*
|
||||
* @return the value associated with the instance before it was incremented
|
||||
* @since 3.5
|
||||
*/
|
||||
public byte getAndIncrement() {
|
||||
final byte last = value;
|
||||
value++;
|
||||
return last;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments this instance's value by 1; this method returns the value
|
||||
* associated with the instance immediately after the increment operation. This
|
||||
* method is not thread safe.
|
||||
*
|
||||
* @return the value associated with the instance after it is incremented
|
||||
* @since 3.5
|
||||
*/
|
||||
public byte incrementAndGet() {
|
||||
value++;
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrements the value.
|
||||
*
|
||||
* @since 2.2
|
||||
*/
|
||||
public void decrement() {
|
||||
value--;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrements this instance's value by 1; this method returns the value
|
||||
* associated with the instance immediately prior to the decrement operation.
|
||||
* This method is not thread safe.
|
||||
*
|
||||
* @return the value associated with the instance before it was decremented
|
||||
* @since 3.5
|
||||
*/
|
||||
public byte getAndDecrement() {
|
||||
final byte last = value;
|
||||
value--;
|
||||
return last;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrements this instance's value by 1; this method returns the value
|
||||
* associated with the instance immediately after the decrement operation. This
|
||||
* method is not thread safe.
|
||||
*
|
||||
* @return the value associated with the instance after it is decremented
|
||||
* @since 3.5
|
||||
*/
|
||||
public byte decrementAndGet() {
|
||||
value--;
|
||||
return value;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Adds a value to the value of this instance.
|
||||
*
|
||||
* @param operand the value to add, not null
|
||||
* @since 2.2
|
||||
*/
|
||||
public void add(final byte operand) {
|
||||
this.value += operand;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a value to the value of this instance.
|
||||
*
|
||||
* @param operand the value to add, not null
|
||||
* @throws NullPointerException if the object is null
|
||||
* @since 2.2
|
||||
*/
|
||||
public void add(final Number operand) {
|
||||
this.value += operand.byteValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Subtracts a value from the value of this instance.
|
||||
*
|
||||
* @param operand the value to subtract, not null
|
||||
* @since 2.2
|
||||
*/
|
||||
public void subtract(final byte operand) {
|
||||
this.value -= operand;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subtracts a value from the value of this instance.
|
||||
*
|
||||
* @param operand the value to subtract, not null
|
||||
* @throws NullPointerException if the object is null
|
||||
* @since 2.2
|
||||
*/
|
||||
public void subtract(final Number operand) {
|
||||
this.value -= operand.byteValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments this instance's value by {@code operand}; this method returns the
|
||||
* value associated with the instance immediately after the addition operation.
|
||||
* This method is not thread safe.
|
||||
*
|
||||
* @param operand the quantity to add, not null
|
||||
* @return the value associated with this instance after adding the operand
|
||||
* @since 3.5
|
||||
*/
|
||||
public byte addAndGet(final byte operand) {
|
||||
this.value += operand;
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments this instance's value by {@code operand}; this method returns the
|
||||
* value associated with the instance immediately after the addition operation.
|
||||
* This method is not thread safe.
|
||||
*
|
||||
* @param operand the quantity to add, not null
|
||||
* @throws NullPointerException if {@code operand} is null
|
||||
* @return the value associated with this instance after adding the operand
|
||||
* @since 3.5
|
||||
*/
|
||||
public byte addAndGet(final Number operand) {
|
||||
this.value += operand.byteValue();
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments this instance's value by {@code operand}; this method returns the
|
||||
* value associated with the instance immediately prior to the addition
|
||||
* operation. This method is not thread safe.
|
||||
*
|
||||
* @param operand the quantity to add, not null
|
||||
* @return the value associated with this instance immediately before the
|
||||
* operand was added
|
||||
* @since 3.5
|
||||
*/
|
||||
public byte getAndAdd(final byte operand) {
|
||||
final byte last = value;
|
||||
this.value += operand;
|
||||
return last;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments this instance's value by {@code operand}; this method returns the
|
||||
* value associated with the instance immediately prior to the addition
|
||||
* operation. This method is not thread safe.
|
||||
*
|
||||
* @param operand the quantity to add, not null
|
||||
* @throws NullPointerException if {@code operand} is null
|
||||
* @return the value associated with this instance immediately before the
|
||||
* operand was added
|
||||
* @since 3.5
|
||||
*/
|
||||
public byte getAndAdd(final Number operand) {
|
||||
final byte last = value;
|
||||
this.value += operand.byteValue();
|
||||
return last;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// shortValue relies on Number implementation
|
||||
/**
|
||||
* Returns the value of this MutableByte as a byte.
|
||||
*
|
||||
* @return the numeric value represented by this object after conversion to type
|
||||
* byte.
|
||||
*/
|
||||
@Override
|
||||
public byte byteValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of this MutableByte as an int.
|
||||
*
|
||||
* @return the numeric value represented by this object after conversion to type
|
||||
* int.
|
||||
*/
|
||||
@Override
|
||||
public int intValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of this MutableByte as a long.
|
||||
*
|
||||
* @return the numeric value represented by this object after conversion to type
|
||||
* long.
|
||||
*/
|
||||
@Override
|
||||
public long longValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of this MutableByte as a float.
|
||||
*
|
||||
* @return the numeric value represented by this object after conversion to type
|
||||
* float.
|
||||
*/
|
||||
@Override
|
||||
public float floatValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of this MutableByte as a double.
|
||||
*
|
||||
* @return the numeric value represented by this object after conversion to type
|
||||
* double.
|
||||
*/
|
||||
@Override
|
||||
public double doubleValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Gets this mutable as an instance of Byte.
|
||||
*
|
||||
* @return a Byte instance containing the value from this mutable
|
||||
*/
|
||||
public Byte toByte() {
|
||||
return Byte.valueOf(byteValue());
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Compares this object to the specified object. The result is {@code true} if
|
||||
* and only if the argument is not {@code null} and is a {@code MutableByte}
|
||||
* object that contains the same {@code byte} value as this object.
|
||||
*
|
||||
* @param obj the object to compare with, null returns false
|
||||
* @return {@code true} if the objects are the same; {@code false} otherwise.
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (obj instanceof MutableByte) {
|
||||
return value == ((MutableByte) obj).byteValue();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a suitable hash code for this mutable.
|
||||
*
|
||||
* @return a suitable hash code
|
||||
*/
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return value;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Compares this mutable to another in ascending order.
|
||||
*
|
||||
* @param other the other mutable to compare to, not null
|
||||
* @return negative if this is less, zero if equal, positive if greater
|
||||
*/
|
||||
@Override
|
||||
public int compareTo(final MutableByte other) {
|
||||
return NumberUtils.compare(this.value, other.value);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Returns the String value of this mutable.
|
||||
*
|
||||
* @return the mutable value as a string
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.valueOf(value);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,434 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF 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.apache.commons.lang3.mutable;
|
||||
|
||||
/**
|
||||
* A mutable {@code double} wrapper.
|
||||
* <p>
|
||||
* Note that as MutableDouble does not extend Double, it is not treated by
|
||||
* HString.format as a Double parameter.
|
||||
*
|
||||
* @see Double
|
||||
* @since 2.1
|
||||
*/
|
||||
public class MutableDouble extends Number implements Comparable<MutableDouble>, Mutable<Number> {
|
||||
|
||||
/**
|
||||
* Required for serialization support.
|
||||
*
|
||||
* @see java.io.Serializable
|
||||
*/
|
||||
private static final long serialVersionUID = 1587163916L;
|
||||
|
||||
/** The mutable value. */
|
||||
private double value;
|
||||
|
||||
/**
|
||||
* Constructs a new MutableDouble with the default value of zero.
|
||||
*/
|
||||
public MutableDouble() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new MutableDouble with the specified value.
|
||||
*
|
||||
* @param value the initial value to store
|
||||
*/
|
||||
public MutableDouble(final double value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new MutableDouble with the specified value.
|
||||
*
|
||||
* @param value the initial value to store, not null
|
||||
* @throws NullPointerException if the object is null
|
||||
*/
|
||||
public MutableDouble(final Number value) {
|
||||
this.value = value.doubleValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new MutableDouble parsing the given string.
|
||||
*
|
||||
* @param value the string to parse, not null
|
||||
* @throws NumberFormatException if the string cannot be parsed into a double
|
||||
* @since 2.5
|
||||
*/
|
||||
public MutableDouble(final String value) {
|
||||
this.value = Double.parseDouble(value);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Gets the value as a Double instance.
|
||||
*
|
||||
* @return the value as a Double, never null
|
||||
*/
|
||||
@Override
|
||||
public Double getValue() {
|
||||
return Double.valueOf(this.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value.
|
||||
*
|
||||
* @param value the value to set
|
||||
*/
|
||||
public void setValue(final double value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value from any Number instance.
|
||||
*
|
||||
* @param value the value to set, not null
|
||||
* @throws NullPointerException if the object is null
|
||||
*/
|
||||
@Override
|
||||
public void setValue(final Number value) {
|
||||
this.value = value.doubleValue();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Checks whether the double value is the special NaN value.
|
||||
*
|
||||
* @return true if NaN
|
||||
*/
|
||||
public boolean isNaN() {
|
||||
return Double.isNaN(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the double value is infinite.
|
||||
*
|
||||
* @return true if infinite
|
||||
*/
|
||||
public boolean isInfinite() {
|
||||
return Double.isInfinite(value);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Increments the value.
|
||||
*
|
||||
* @since 2.2
|
||||
*/
|
||||
public void increment() {
|
||||
value++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments this instance's value by 1; this method returns the value
|
||||
* associated with the instance immediately prior to the increment operation.
|
||||
* This method is not thread safe.
|
||||
*
|
||||
* @return the value associated with the instance before it was incremented
|
||||
* @since 3.5
|
||||
*/
|
||||
public double getAndIncrement() {
|
||||
final double last = value;
|
||||
value++;
|
||||
return last;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments this instance's value by 1; this method returns the value
|
||||
* associated with the instance immediately after the increment operation. This
|
||||
* method is not thread safe.
|
||||
*
|
||||
* @return the value associated with the instance after it is incremented
|
||||
* @since 3.5
|
||||
*/
|
||||
public double incrementAndGet() {
|
||||
value++;
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrements the value.
|
||||
*
|
||||
* @since 2.2
|
||||
*/
|
||||
public void decrement() {
|
||||
value--;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrements this instance's value by 1; this method returns the value
|
||||
* associated with the instance immediately prior to the decrement operation.
|
||||
* This method is not thread safe.
|
||||
*
|
||||
* @return the value associated with the instance before it was decremented
|
||||
* @since 3.5
|
||||
*/
|
||||
public double getAndDecrement() {
|
||||
final double last = value;
|
||||
value--;
|
||||
return last;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrements this instance's value by 1; this method returns the value
|
||||
* associated with the instance immediately after the decrement operation. This
|
||||
* method is not thread safe.
|
||||
*
|
||||
* @return the value associated with the instance after it is decremented
|
||||
* @since 3.5
|
||||
*/
|
||||
public double decrementAndGet() {
|
||||
value--;
|
||||
return value;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Adds a value to the value of this instance.
|
||||
*
|
||||
* @param operand the value to add
|
||||
* @since 2.2
|
||||
*/
|
||||
public void add(final double operand) {
|
||||
this.value += operand;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a value to the value of this instance.
|
||||
*
|
||||
* @param operand the value to add, not null
|
||||
* @throws NullPointerException if the object is null
|
||||
* @since 2.2
|
||||
*/
|
||||
public void add(final Number operand) {
|
||||
this.value += operand.doubleValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Subtracts a value from the value of this instance.
|
||||
*
|
||||
* @param operand the value to subtract, not null
|
||||
* @since 2.2
|
||||
*/
|
||||
public void subtract(final double operand) {
|
||||
this.value -= operand;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subtracts a value from the value of this instance.
|
||||
*
|
||||
* @param operand the value to subtract, not null
|
||||
* @throws NullPointerException if the object is null
|
||||
* @since 2.2
|
||||
*/
|
||||
public void subtract(final Number operand) {
|
||||
this.value -= operand.doubleValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments this instance's value by {@code operand}; this method returns the
|
||||
* value associated with the instance immediately after the addition operation.
|
||||
* This method is not thread safe.
|
||||
*
|
||||
* @param operand the quantity to add, not null
|
||||
* @return the value associated with this instance after adding the operand
|
||||
* @since 3.5
|
||||
*/
|
||||
public double addAndGet(final double operand) {
|
||||
this.value += operand;
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments this instance's value by {@code operand}; this method returns the
|
||||
* value associated with the instance immediately after the addition operation.
|
||||
* This method is not thread safe.
|
||||
*
|
||||
* @param operand the quantity to add, not null
|
||||
* @throws NullPointerException if {@code operand} is null
|
||||
* @return the value associated with this instance after adding the operand
|
||||
* @since 3.5
|
||||
*/
|
||||
public double addAndGet(final Number operand) {
|
||||
this.value += operand.doubleValue();
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments this instance's value by {@code operand}; this method returns the
|
||||
* value associated with the instance immediately prior to the addition
|
||||
* operation. This method is not thread safe.
|
||||
*
|
||||
* @param operand the quantity to add, not null
|
||||
* @return the value associated with this instance immediately before the
|
||||
* operand was added
|
||||
* @since 3.5
|
||||
*/
|
||||
public double getAndAdd(final double operand) {
|
||||
final double last = value;
|
||||
this.value += operand;
|
||||
return last;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments this instance's value by {@code operand}; this method returns the
|
||||
* value associated with the instance immediately prior to the addition
|
||||
* operation. This method is not thread safe.
|
||||
*
|
||||
* @param operand the quantity to add, not null
|
||||
* @throws NullPointerException if {@code operand} is null
|
||||
* @return the value associated with this instance immediately before the
|
||||
* operand was added
|
||||
* @since 3.5
|
||||
*/
|
||||
public double getAndAdd(final Number operand) {
|
||||
final double last = value;
|
||||
this.value += operand.doubleValue();
|
||||
return last;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// shortValue and byteValue rely on Number implementation
|
||||
/**
|
||||
* Returns the value of this MutableDouble as an int.
|
||||
*
|
||||
* @return the numeric value represented by this object after conversion to type
|
||||
* int.
|
||||
*/
|
||||
@Override
|
||||
public int intValue() {
|
||||
return (int) value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of this MutableDouble as a long.
|
||||
*
|
||||
* @return the numeric value represented by this object after conversion to type
|
||||
* long.
|
||||
*/
|
||||
@Override
|
||||
public long longValue() {
|
||||
return (long) value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of this MutableDouble as a float.
|
||||
*
|
||||
* @return the numeric value represented by this object after conversion to type
|
||||
* float.
|
||||
*/
|
||||
@Override
|
||||
public float floatValue() {
|
||||
return (float) value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of this MutableDouble as a double.
|
||||
*
|
||||
* @return the numeric value represented by this object after conversion to type
|
||||
* double.
|
||||
*/
|
||||
@Override
|
||||
public double doubleValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Gets this mutable as an instance of Double.
|
||||
*
|
||||
* @return a Double instance containing the value from this mutable, never null
|
||||
*/
|
||||
public Double toDouble() {
|
||||
return Double.valueOf(doubleValue());
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Compares this object against the specified object. The result is {@code true}
|
||||
* if and only if the argument is not {@code null} and is a {@code Double}
|
||||
* object that represents a double that has the identical bit pattern to the bit
|
||||
* pattern of the double represented by this object. For this purpose, two
|
||||
* {@code double} values are considered to be the same if and only if the method
|
||||
* {@link Double#doubleToLongBits(double)}returns the same long value when
|
||||
* applied to each.
|
||||
* <p>
|
||||
* Note that in most cases, for two instances of class {@code Double},{@code d1}
|
||||
* and {@code d2}, the value of {@code d1.equals(d2)} is {@code true} if and
|
||||
* only if <blockquote>
|
||||
*
|
||||
* <pre>
|
||||
* d1.doubleValue() == d2.doubleValue()
|
||||
* </pre>
|
||||
*
|
||||
* </blockquote>
|
||||
* <p>
|
||||
* also has the value {@code true}. However, there are two exceptions:
|
||||
* <ul>
|
||||
* <li>If {@code d1} and {@code d2} both represent {@code Double.NaN}, then the
|
||||
* {@code equals} method returns {@code true}, even though
|
||||
* {@code Double.NaN==Double.NaN} has the value {@code false}.
|
||||
* <li>If {@code d1} represents {@code +0.0} while {@code d2} represents
|
||||
* {@code -0.0}, or vice versa, the {@code equal} test has the value
|
||||
* {@code false}, even though {@code +0.0==-0.0} has the value {@code true}.
|
||||
* This allows hashtables to operate properly.
|
||||
* </ul>
|
||||
*
|
||||
* @param obj the object to compare with, null returns false
|
||||
* @return {@code true} if the objects are the same; {@code false} otherwise.
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
return obj instanceof MutableDouble
|
||||
&& Double.doubleToLongBits(((MutableDouble) obj).value) == Double.doubleToLongBits(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a suitable hash code for this mutable.
|
||||
*
|
||||
* @return a suitable hash code
|
||||
*/
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final long bits = Double.doubleToLongBits(value);
|
||||
return (int) (bits ^ bits >>> 32);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Compares this mutable to another in ascending order.
|
||||
*
|
||||
* @param other the other mutable to compare to, not null
|
||||
* @return negative if this is less, zero if equal, positive if greater
|
||||
*/
|
||||
@Override
|
||||
public int compareTo(final MutableDouble other) {
|
||||
return Double.compare(this.value, other.value);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
/**
|
||||
* Returns the String value of this mutable.
|
||||
*
|
||||
* @return the mutable value as a string
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.valueOf(value);
|
||||
}
|
||||
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user